id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
3,880
ratelimit_manager.h
typesense_typesense/include/ratelimit_manager.h
#pragma once #include <string> #include <vector> #include <tuple> #include <unordered_map> #include <mutex> #include <shared_mutex> #include <json.hpp> #include <magic_enum.hpp> #include "lru/lru.hpp" #include "option.h" #include "store.h" // Action enum for rate limit rules enum class RateLimitAction { allow, block, throttle }; // Entity type enum for rate limit rules enum class RateLimitedEntityType { ip, api_key }; // overload operator! to get inverse of RateLimitedEntityType inline RateLimitedEntityType operator!(const RateLimitedEntityType& entity_type) { switch (entity_type) { case RateLimitedEntityType::ip: return RateLimitedEntityType::api_key; case RateLimitedEntityType::api_key: return RateLimitedEntityType::ip; } } // Max requests struct for rate limit rules struct rate_limit_max_requests_t { int64_t minute_threshold = -1; int64_t hour_threshold = -1; }; // Entry struct for rate limit rule pointer hash map as key struct rate_limit_entity_t { RateLimitedEntityType entity_type; std::string entity_id; // Equality operator for rate_limit_entity_t bool operator==(const rate_limit_entity_t& other) const { return std::tie(entity_type, entity_id) == std::tie(other.entity_type, other.entity_id); } }; // Struct for rate limit rules struct rate_limit_rule_t { uint32_t id; RateLimitAction action; std::vector<rate_limit_entity_t> entities; rate_limit_max_requests_t max_requests; int64_t auto_ban_1m_threshold = -1; int64_t auto_ban_1m_duration_hours = -1; bool apply_limit_per_entity = false; uint32_t priority = 0; const nlohmann::json to_json() const; }; // Request counter struct for ip addresses to keep track of requests for current and previous sampling period struct request_counter_t { int64_t current_requests_count_minute = 0; int64_t current_requests_count_hour = 0; int64_t previous_requests_count_minute = 0; int64_t previous_requests_count_hour = 0; int64_t threshold_exceed_count_minute = 0; time_t last_reset_time_minute = 0; time_t last_reset_time_hour = 0; void reset() { current_requests_count_minute = 0; current_requests_count_hour = 0; threshold_exceed_count_minute = 0; previous_requests_count_minute = 0; previous_requests_count_hour = 0; last_reset_time_minute = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); last_reset_time_hour = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); } // not-equal operator overload bool operator!=(const request_counter_t& other) const{ return std::tie(current_requests_count_minute, current_requests_count_hour, previous_requests_count_minute, previous_requests_count_hour, last_reset_time_minute, last_reset_time_hour) != std::tie(other.current_requests_count_minute, other.current_requests_count_hour, other.previous_requests_count_minute, other.previous_requests_count_hour, other.last_reset_time_minute, other.last_reset_time_hour); } }; // Struct to store ban information for ip addresses struct rate_limit_status_t { uint32_t status_id; int64_t throttling_from; int64_t throttling_to; rate_limit_entity_t entity; // optional second entity for AND bans Option<rate_limit_entity_t> and_entity = Option<rate_limit_entity_t>(404, "Not Found"); rate_limit_status_t(const uint32_t status_id, const int64_t throttling_from, const int64_t throttling_to, const rate_limit_entity_t &entity, const rate_limit_entity_t* and_entity = nullptr) : status_id(status_id), throttling_from(throttling_from), throttling_to(throttling_to), entity(entity) { if (and_entity != nullptr) { this->and_entity = Option<rate_limit_entity_t>(*and_entity); } } // default constructor rate_limit_status_t() = default; const nlohmann::json to_json() const; void parse_json(const nlohmann::json& json); }; // Struct to store how many requests made by exceeded rate limit entities struct rate_limit_exceed_t { uint32_t rule_id; std::string entities; uint64_t request_count = 0; const nlohmann::json to_json() const { nlohmann::json json; std::string api_key = entities.substr(0, entities.find("_")); std::string ip = entities.substr(entities.find("_") + 1); json["id"] = rule_id; json["api_key"] = api_key; json["ip"] = ip; json["request_count"] = request_count; return json; } }; // Hash function for rate_limit_entity_t namespace std { template <> struct hash<rate_limit_entity_t> { std::size_t operator()(const rate_limit_entity_t& k) const{ return ((std::hash<int>()(static_cast<int>(k.entity_type)) ^ (std::hash<std::string>()(k.entity_id) << 1)) >> 1); } }; } class RateLimitManager { public: RateLimitManager(const RateLimitManager&) = delete; RateLimitManager& operator=(const RateLimitManager&) = delete; RateLimitManager(RateLimitManager&&) = delete; RateLimitManager& operator=(RateLimitManager&&) = delete; static RateLimitManager* getInstance(); // Get vector of banned entities const std::vector<rate_limit_status_t> get_banned_entities(const RateLimitedEntityType entity_type); // Check if request is rate limited for given entities bool is_rate_limited(const rate_limit_entity_t& api_key_entity, const rate_limit_entity_t& ip_entity); // Add rule by JSON Option<nlohmann::json> add_rule(const nlohmann::json &rule_json); // Edit rule by JSON Option<nlohmann::json> edit_rule(const uint64_t id, const nlohmann::json &rule_json); // Find rule by ID Option<nlohmann::json> find_rule_by_id(const uint64_t id); // Delete rule by ID bool delete_rule_by_id(const uint64_t id); // Delete ban by ID bool delete_ban_by_id(const uint64_t id); // Delete throttle by ID bool delete_throttle_by_id(const uint32_t id); // Get All rules as vector const std::vector<rate_limit_rule_t> get_all_rules(); // Get all rules as json const nlohmann::json get_all_rules_json(); // Get exceeded entities and request counts as JSON const nlohmann::json get_exceeded_entities_json(); // Get autobanned entities as JSON const nlohmann::json get_throttled_entities_json(); // Clear all rules void clear_all(); // Internal function to set base time void _set_base_timestamp(const time_t& base_time); // Set store Option<bool> init(Store* store); private: RateLimitManager() { rate_limit_request_counts.capacity(10000); } // Store for rate limit rules Store *store; // Using a $ prefix so that these meta keys stay above record entries in a lexicographically ordered KV store // Prefix for rate limit rules static constexpr const char* RULES_NEXT_ID = "$RLN"; static constexpr const char* RULES_PREFIX = "$RLRP"; // Prefix for bans static constexpr const char* BANS_NEXT_ID = "$RLBN"; static constexpr const char* BANS_PREFIX = "$RLBP"; // Static instance of wildcard entities inline static const rate_limit_entity_t WILDCARD_IP = rate_limit_entity_t{RateLimitedEntityType::ip, ".*"}; inline static const rate_limit_entity_t WILDCARD_API_KEY = rate_limit_entity_t{RateLimitedEntityType::api_key, ".*"}; // ID of latest added rule inline static uint32_t last_rule_id = 0; // ID of latest added ban inline static uint32_t last_ban_id = 0; // ID of latest added throttle inline static uint32_t last_throttle_id = 0; // Store for rate_limit_rule_t std::unordered_map<uint64_t,rate_limit_rule_t> rule_store; // LRU Cache to store rate limit and request counts for entities LRU::Cache<std::string, request_counter_t> rate_limit_request_counts; // Unordered map to point rules from rule store for entities std::unordered_map<rate_limit_entity_t, std::vector<rate_limit_rule_t*>> rate_limit_entities; // Unordered map to store banned entities std::unordered_map<std::string, rate_limit_status_t> throttled_entities; // Hash map to store exceeds std::unordered_map<std::string, rate_limit_exceed_t> rate_limit_exceeds; // Mutex to protect access to ip_rate_limits and api_key_rate_limits std::shared_mutex rate_limit_mutex; // Helper function to ban an entity temporarily void temp_ban_entity(const rate_limit_entity_t& entity, const uint64_t number_of_hours); // Helper function to ban an entity temporarily without locking mutex void temp_ban_entity_wrapped(const rate_limit_entity_t& entity, const uint64_t number_of_hours, const rate_limit_entity_t* and_entity = nullptr); // Helper function to check if JSON rule is valid Option<bool> is_valid_rule(const nlohmann::json &rule_json); // Parse JSON rule to rate_limit_rule_t static Option<rate_limit_rule_t> parse_rule(const nlohmann::json &rule_json); // Helper function to insert rule in store void insert_rule(const rate_limit_rule_t &rule); // Helper function to get rule key for DB store from ID std::string get_rule_key(const uint32_t id); // Helper function to get ban key for DB store from ID std::string get_ban_key(const uint32_t id); // Base timestamp time_t base_timestamp = 0; // Helper function to get current timestamp time_t get_current_time(); // Helper function to get throttle key for entity if exists Option<std::string> get_throttle_key(const rate_limit_entity_t& ip_entity, const rate_limit_entity_t& api_key_entity); // Helper function to get request counter key according to rule type static const std::string get_request_counter_key(const rate_limit_rule_t& rule, const rate_limit_entity_t& ip_entity, const rate_limit_entity_t& api_key_entity); // Fill bucket rule for the given entity void fill_bucket(const rate_limit_entity_t& target_entity, const rate_limit_entity_t& other_entity, std::vector<rate_limit_rule_t*> &rules_bucket); // Singleton instance inline static RateLimitManager *instance; };
10,685
C++
.h
224
40.754464
298
0.679722
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,881
join.h
typesense_typesense/include/join.h
#pragma once #include "option.h" #include "json.hpp" #include "tsl/htrie_map.h" #include "field.h" #include "tsl/htrie_set.h" #include "filter_result_iterator.h" struct reference_info_t { std::string collection; std::string field; bool is_async; std::string referenced_field_name; reference_info_t(std::string collection, std::string field, bool is_async, std::string referenced_field_name = "") : collection(std::move(collection)), field(std::move(field)), is_async(is_async), referenced_field_name(std::move(referenced_field_name)) {} bool operator < (const reference_info_t& other) const noexcept { if (collection == other.collection) { return field < other.field; } return collection < other.collection; } }; struct ref_include_collection_names_t { std::set<std::string> collection_names; ref_include_collection_names_t* nested_include = nullptr; ~ref_include_collection_names_t() { delete nested_include; } }; class Join { public: static Option<bool> add_reference_helper_fields(nlohmann::json& document, const tsl::htrie_map<char, field>& schema, const spp::sparse_hash_map<std::string, reference_info_t>& reference_fields, tsl::htrie_set<char>& object_reference_helper_fields, const bool& is_update); static Option<bool> prune_ref_doc(nlohmann::json& doc, const reference_filter_result_t& references, const tsl::htrie_set<char>& ref_include_fields_full, const tsl::htrie_set<char>& ref_exclude_fields_full, const bool& is_reference_array, const ref_include_exclude_fields& ref_include_exclude); static Option<bool> include_references(nlohmann::json& doc, const uint32_t& seq_id, Collection *const collection, const std::map<std::string, reference_filter_result_t>& reference_filter_results, const std::vector<ref_include_exclude_fields>& ref_include_exclude_fields_vec, const nlohmann::json& original_doc); static Option<bool> parse_reference_filter(const std::string& filter_query, std::queue<std::string>& tokens, size_t& index, std::set<std::string>& ref_collection_names); static Option<bool> split_reference_include_exclude_fields(const std::string& include_exclude_fields, size_t& index, std::string& token); static void get_reference_collection_names(const std::string& filter_query, ref_include_collection_names_t*& ref_include); // Separate out the reference includes and excludes into `ref_include_exclude_fields_vec`. static Option<bool> initialize_ref_include_exclude_fields_vec(const std::string& filter_query, std::vector<std::string>& include_fields_vec, std::vector<std::string>& exclude_fields_vec, std::vector<ref_include_exclude_fields>& ref_include_exclude_fields_vec); [[nodiscard]] static bool merge_join_conditions(string& embedded_filter, string& query_filter); };
3,695
C++
.h
58
45.482759
139
0.568904
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,882
japanese_localizer.h
typesense_typesense/include/japanese_localizer.h
#pragma once #include <string> #include <mutex> class JapaneseLocalizer { private: JapaneseLocalizer(); ~JapaneseLocalizer() = default; static void write_data_file(const std::string& base64_data, const std::string& file_name); std::mutex m; public: static JapaneseLocalizer & get_instance() { static JapaneseLocalizer instance; return instance; } bool init(); char* normalize(const std::string& text); };
462
C++
.h
17
22.823529
94
0.704128
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,883
query_analytics.h
typesense_typesense/include/query_analytics.h
#pragma once #include <string> #include <vector> #include <tsl/htrie_map.h> #include <json.hpp> #include <atomic> #include <shared_mutex> class QueryAnalytics { public: struct QWithTimestamp { std::string query; uint64_t timestamp; QWithTimestamp(const std::string& query, uint64_t timestamp) : query(query), timestamp(timestamp) {} }; static const size_t QUERY_FINALIZATION_INTERVAL_MICROS = 4 * 1000 * 1000; private: size_t k; const size_t max_size; const size_t max_query_length = 1024; bool expand_query = false; bool auto_aggregation_enabled; // counts aggregated within the current node tsl::htrie_map<char, uint32_t> local_counts; std::shared_mutex lmutex; std::unordered_map<std::string, std::vector<QWithTimestamp>> user_prefix_queries; std::shared_mutex umutex; public: QueryAnalytics(size_t k, bool enable_auto_aggregation = true); void add(const std::string& value, const std::string& expanded_key, const bool live_query, const std::string& user_id, uint64_t now_ts_us = 0); void compact_user_queries(uint64_t now_ts_us); void serialize_as_docs(std::string& docs); void reset_local_counts(); size_t get_k(); std::unordered_map<std::string, std::vector<QWithTimestamp>> get_user_prefix_queries(); tsl::htrie_map<char, uint32_t> get_local_counts(); void set_expand_query(bool expand_query); bool is_auto_aggregation_enabled() const; };
1,494
C++
.h
39
33.512821
108
0.703343
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,884
text_embedder_tokenizer.h
typesense_typesense/include/text_embedder_tokenizer.h
#pragma #include <vector> #include <unordered_map> #include <sentencepiece_processor.h> #include <tokenizer/bert_tokenizer.hpp> #include <clip_tokenizer.h> #include <core/session/onnxruntime_cxx_api.h> #include <mutex> enum class TokenizerType { bert, distilbert, xlm_roberta, clip }; struct encoded_input_t { std::vector<int64_t> input_ids; std::vector<int64_t> token_type_ids; std::vector<int64_t> attention_mask; }; struct batch_encoded_input_t { std::vector<std::vector<int64_t>> input_ids; std::vector<std::vector<int64_t>> token_type_ids; std::vector<std::vector<int64_t>> attention_mask; }; // Create a base class for all tokenizers to inherit from class TextEmbeddingTokenizer { private: public: virtual encoded_input_t Encode(const std::string& text) = 0; virtual ~TextEmbeddingTokenizer() = default; virtual TokenizerType get_tokenizer_type() = 0; }; class BertTokenizerWrapper : public TextEmbeddingTokenizer { protected: std::unique_ptr<BertTokenizer> bert_tokenizer_; public: BertTokenizerWrapper(const std::string& vocab_path); encoded_input_t Encode(const std::string& text) override; virtual TokenizerType get_tokenizer_type() override { return TokenizerType::bert; } }; class DistilbertTokenizer : public BertTokenizerWrapper { public: DistilbertTokenizer(const std::string& vocab_path); encoded_input_t Encode(const std::string& text) override; }; class XLMRobertaTokenizer : public TextEmbeddingTokenizer { private: inline static constexpr uint8_t fairseq_offset = 1; std::unordered_map<std::string, int64_t> fairseq_tokens_to_ids_ = { {"<s>", 0}, {"<pad>", 1}, {"</s>", 2}, {"<unk>", 3}, }; std::unique_ptr<sentencepiece::SentencePieceProcessor> sentencepiece_tokenizer_; const int token_to_id(const std::string& token); const std::vector<std::string> tokenize(const std::string& text); public: XLMRobertaTokenizer(const std::string& model_path); encoded_input_t Encode(const std::string& text) override; virtual TokenizerType get_tokenizer_type() override { return TokenizerType::xlm_roberta; } }; class CLIPTokenizerWrapper : public TextEmbeddingTokenizer { private: std::unique_ptr<CLIPTokenizer> clip_tokenizer_; std::mutex mutex_; public: CLIPTokenizerWrapper(const std::string& vocab_path); encoded_input_t Encode(const std::string& text) override; virtual TokenizerType get_tokenizer_type() override { return TokenizerType::clip; } };
2,740
C++
.h
77
29.675325
88
0.679985
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,885
conversation_manager.h
typesense_typesense/include/conversation_manager.h
#pragma once #include <string> #include <unordered_map> #include <unordered_set> #include <shared_mutex> #include <mutex> #include <json.hpp> #include "option.h" #include "store.h" #include "sole.hpp" #include "collection_manager.h" #include "conversation_model_manager.h" class ConversationManager { public: ConversationManager(const ConversationManager&) = delete; ConversationManager(ConversationManager&&) = delete; ConversationManager& operator=(const ConversationManager&) = delete; ConversationManager& operator=(ConversationManager&&) = delete; static ConversationManager& get_instance() { static ConversationManager instance; return instance; } Option<std::string> add_conversation(const nlohmann::json& conversation, const nlohmann::json& model, const std::string& id = ""); Option<nlohmann::json> get_conversation(const std::string& conversation_id); static Option<nlohmann::json> truncate_conversation(nlohmann::json conversation, size_t limit); Option<nlohmann::json> delete_conversation(const std::string& conversation_id); Option<bool> check_conversation_exists(const std::string& conversation_id); Option<std::unordered_set<std::string>> get_conversation_ids(); static constexpr size_t MAX_TOKENS = 3000; Option<bool> init(ReplicationState* raft_server); void clear_expired_conversations(); void run(); void stop(); void _set_ttl_offset(size_t offset) { TTL_OFFSET = offset; } Option<bool> validate_conversation_store_schema(Collection* collection); Option<bool> validate_conversation_store_collection(const std::string& collection); Option<Collection*> get_history_collection(const std::string& conversation_id); private: ConversationManager() {} std::mutex conversations_mutex; ReplicationState* raft_server; size_t TTL_OFFSET = 0; std::atomic<bool> quit = false; std::condition_variable cv; Option<nlohmann::json> delete_conversation_unsafe(const std::string& conversation_id); };
2,189
C++
.h
48
38.583333
138
0.698778
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,886
core_api_utils.h
typesense_typesense/include/core_api_utils.h
#pragma once #include <cstdlib> #include <vector> #include "collection.h" #include "http_data.h" struct deletion_state_t: public req_state_t { Collection* collection; std::vector<std::pair<size_t, uint32_t*>> index_ids; // ids_len -> ids std::vector<size_t> offsets; size_t num_removed; ~deletion_state_t() override { for(auto& kv: index_ids) { delete [] kv.second; } } }; struct export_state_t: public req_state_t { Collection* collection; filter_result_t filter_result; size_t offset = 0; tsl::htrie_set<char> include_fields; tsl::htrie_set<char> exclude_fields; std::vector<ref_include_exclude_fields> ref_include_exclude_fields_vec; size_t export_batch_size = 100; std::string* res_body; bool filtered_export = false; rocksdb::Iterator* it = nullptr; std::string iter_upper_bound_key; rocksdb::Slice* iter_upper_bound = nullptr; ~export_state_t() override { delete iter_upper_bound; delete it; } }; Option<bool> stateful_remove_docs(deletion_state_t* deletion_state, size_t batch_size, bool& done); Option<bool> stateful_export_docs(export_state_t* export_state, size_t batch_size, bool& done);
1,231
C++
.h
36
29.555556
99
0.679293
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,887
stemmer_manager.h
typesense_typesense/include/stemmer_manager.h
#pragma once #include <unordered_map> #include <string> #include <vector> #include <memory> #include <mutex> #include <libstemmer.h> #include "lru/lru.hpp" class Stemmer { private: sb_stemmer * stemmer = nullptr; LRU::Cache<std::string, std::string> cache; std::mutex mutex; public: Stemmer(const char * language); ~Stemmer(); std::string stem(const std::string & word); }; class StemmerManager { private: std::unordered_map<std::string, std::shared_ptr<Stemmer>> stemmers; StemmerManager() {} std::mutex mutex; public: static StemmerManager& get_instance() { static StemmerManager instance; return instance; } StemmerManager(StemmerManager const&) = delete; void operator=(StemmerManager const&) = delete; StemmerManager(StemmerManager&&) = delete; void operator=(StemmerManager&&) = delete; ~StemmerManager(); std::shared_ptr<Stemmer> get_stemmer(const std::string& language); void delete_stemmer(const std::string& language); void delete_all_stemmers(); const bool validate_language(const std::string& language); };
1,224
C++
.h
38
25.815789
75
0.647208
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,888
text_embedder.h
typesense_typesense/include/text_embedder.h
#pragma once #include <sentencepiece_processor.h> #include <core/session/onnxruntime_cxx_api.h> #include <tokenizer/bert_tokenizer.hpp> #include <vector> #include "option.h" #include "text_embedder_tokenizer.h" #include "text_embedder_remote.h" class TextEmbedder { public: // Constructor for local or public models TextEmbedder(const std::string& model_path); // Constructor for remote models TextEmbedder(const nlohmann::json& model_config, size_t num_dims, const bool has_custom_dims = false); ~TextEmbedder(); embedding_res_t Embed(const std::string& text, const size_t remote_embedder_timeout_ms = 30000, const size_t remote_embedding_num_tries = 2); std::vector<embedding_res_t> batch_embed(const std::vector<std::string>& inputs, const size_t remote_embedding_batch_size = 200, const size_t remote_embedding_timeout_ms = 60000, const size_t remote_embedding_num_tries = 2); const std::string& get_vocab_file_name() const; const size_t get_num_dim() const; bool is_remote() { return remote_embedder_ != nullptr; } Option<bool> validate(); std::shared_ptr<Ort::Session> get_session() { return session_; } std::shared_ptr<Ort::Env> get_env() { return env_; } const TokenizerType get_tokenizer_type() { return tokenizer_->get_tokenizer_type(); } bool update_remote_embedder_apikey(const std::string& api_key) { return remote_embedder_->update_api_key(api_key); } private: std::shared_ptr<Ort::Session> session_; std::shared_ptr<Ort::Env> env_; encoded_input_t Encode(const std::string& text); batch_encoded_input_t batch_encode(const std::vector<std::string>& inputs); std::unique_ptr<TextEmbeddingTokenizer> tokenizer_; std::unique_ptr<RemoteEmbedder> remote_embedder_; std::string vocab_file_name; static std::vector<float> mean_pooling(const std::vector<std::vector<float>>& input, const std::vector<int64_t>& attention_mask); std::string output_tensor_name; size_t num_dim; std::mutex mutex_; };
2,276
C++
.h
49
37.836735
149
0.643082
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,889
thread_local_vars.h
typesense_typesense/include/thread_local_vars.h
#include <chrono> extern thread_local int64_t write_log_index; // These are used for circuit breaking search requests // NOTE: if you fork off main search thread, care must be taken to initialize these from parent thread values extern thread_local uint64_t search_begin_us; extern thread_local uint64_t search_stop_us; extern thread_local bool search_cutoff;
360
C++
.h
7
50.285714
109
0.809659
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,890
collection_manager.h
typesense_typesense/include/collection_manager.h
#pragma once #include <iostream> #include <string> #include <sparsepp.h> #include "store.h" #include "field.h" #include "collection.h" #include "auth_manager.h" #include "threadpool.h" #include "batched_indexer.h" template<typename ResourceType> struct locked_resource_view_t { locked_resource_view_t(std::shared_mutex &mutex, ResourceType &resource) : _lock(mutex), _resource(&resource) {} locked_resource_view_t(std::shared_mutex &mutex, ResourceType *resource) : _lock(mutex), _resource(resource) {} locked_resource_view_t(ResourceType &&) = delete; locked_resource_view_t(const ResourceType &) = delete; locked_resource_view_t &operator=(const ResourceType &) = delete; ResourceType* operator->() { return _resource; } bool operator==(const ResourceType* other) { return other == _resource; } bool operator!=(const ResourceType* other) { return other != _resource; } void unlock() { _lock.unlock(); } ResourceType* get() { return _resource; } private: std::shared_lock<std::shared_mutex> _lock; ResourceType* _resource; }; // Singleton, for managing meta information of all collections and house keeping class CollectionManager { private: mutable std::shared_mutex mutex; mutable std::shared_mutex noop_coll_mutex; Store *store; ThreadPool* thread_pool; AuthManager auth_manager; spp::sparse_hash_map<std::string, Collection*> collections; spp::sparse_hash_map<uint32_t, std::string> collection_id_names; spp::sparse_hash_map<std::string, std::string> collection_symlinks; spp::sparse_hash_map<std::string, nlohmann::json> preset_configs; // Auto incrementing ID assigned to each collection // Using a ID instead of a collection's name makes renaming possible std::atomic<uint32_t> next_collection_id; std::string bootstrap_auth_key; std::atomic<float> max_memory_ratio; std::atomic<bool>* quit; // All the references to a particular collection are stored until it is created. std::map<std::string, std::set<reference_info_t>> referenced_in_backlog; CollectionManager(); ~CollectionManager() = default; static std::string get_first_index_error(const std::vector<index_record>& index_records) { for(const auto & index_record: index_records) { if(!index_record.indexed.ok()) { return index_record.indexed.error(); } } return ""; } public: static constexpr const size_t DEFAULT_NUM_MEMORY_SHARDS = 4; static constexpr const char* NEXT_COLLECTION_ID_KEY = "$CI"; static constexpr const char* SYMLINK_PREFIX = "$SL"; static constexpr const char* PRESET_PREFIX = "$PS"; uint16_t filter_by_max_ops; static CollectionManager & get_instance() { static CollectionManager instance; return instance; } CollectionManager(CollectionManager const&) = delete; void operator=(CollectionManager const&) = delete; static Collection* init_collection(const nlohmann::json & collection_meta, const uint32_t collection_next_seq_id, Store* store, float max_memory_ratio, spp::sparse_hash_map<std::string, std::string>& referenced_in, spp::sparse_hash_map<std::string, std::set<reference_pair_t>>& async_referenced_ins); static Option<bool> load_collection(const nlohmann::json& collection_meta, const size_t batch_size, const StoreStatus& next_coll_id_status, const std::atomic<bool>& quit, spp::sparse_hash_map<std::string, std::string>& referenced_in, spp::sparse_hash_map<std::string, std::set<reference_pair_t>>& async_referenced_ins); Option<Collection*> clone_collection(const std::string& existing_name, const nlohmann::json& req_json); void add_to_collections(Collection* collection); Option<std::vector<Collection*>> get_collections(uint32_t limit = 0, uint32_t offset = 0, const std::vector<std::string>& api_key_collections = {}) const; std::vector<std::string> get_collection_names() const; Collection* get_collection_unsafe(const std::string & collection_name) const; // PUBLICLY EXPOSED API void init(Store *store, ThreadPool* thread_pool, const float max_memory_ratio, const std::string & auth_key, std::atomic<bool>& quit, const uint16_t& filter_by_max_operations = Config::FILTER_BY_DEFAULT_OPERATIONS); // only for tests! void init(Store *store, const float max_memory_ratio, const std::string & auth_key, std::atomic<bool>& exit, const uint16_t& filter_by_max_operations = Config::FILTER_BY_DEFAULT_OPERATIONS); Option<bool> load(const size_t collection_batch_size, const size_t document_batch_size); // frees in-memory data structures when server is shutdown - helps us run a memory leak detector properly void dispose(); bool auth_key_matches(const string& req_auth_key, const string& action, const std::vector<collection_key_t>& collection_keys, std::map<std::string, std::string>& params, std::vector<nlohmann::json>& embedded_params_vec) const; static Option<Collection*> create_collection(nlohmann::json& req_json); Option<Collection*> create_collection(const std::string& name, const size_t num_memory_shards, const std::vector<field> & fields, const std::string & default_sorting_field="", const uint64_t created_at = static_cast<uint64_t>(std::time(nullptr)), const std::string& fallback_field_type = "", const std::vector<std::string>& symbols_to_index = {}, const std::vector<std::string>& token_separators = {}, const bool enable_nested_fields = false, std::shared_ptr<VQModel> model = nullptr, const nlohmann::json& metadata = {}); locked_resource_view_t<Collection> get_collection(const std::string & collection_name) const; locked_resource_view_t<Collection> get_collection_with_id(uint32_t collection_id) const; Option<nlohmann::json> get_collection_summaries(uint32_t limit = 0 , uint32_t offset = 0, const std::vector<std::string>& exclude_fields = {}, const std::vector<std::string>& api_key_collections = {}) const; Option<nlohmann::json> drop_collection(const std::string& collection_name, const bool remove_from_store = true, const bool compact_store = true); uint32_t get_next_collection_id() const; static std::string get_symlink_key(const std::string & symlink_name); static std::string get_preset_key(const std::string & preset_name); Store* get_store(); ThreadPool* get_thread_pool() const; AuthManager& getAuthManager(); static Option<bool> do_search(std::map<std::string, std::string>& req_params, nlohmann::json& embedded_params, std::string& results_json_str, uint64_t start_ts); static bool parse_sort_by_str(std::string sort_by_str, std::vector<sort_by>& sort_fields); // symlinks Option<std::string> resolve_symlink(const std::string & symlink_name) const; spp::sparse_hash_map<std::string, std::string> get_symlinks() const; Option<bool> upsert_symlink(const std::string & symlink_name, const std::string & collection_name); Option<bool> delete_symlink(const std::string & symlink_name); // presets spp::sparse_hash_map<std::string, nlohmann::json> get_presets() const; Option<bool> get_preset(const std::string & preset_name, nlohmann::json& preset) const; Option<bool> upsert_preset(const std::string & preset_name, const nlohmann::json& preset_config); Option<bool> delete_preset(const std::string & preset_name); void add_referenced_in_backlog(const std::string& collection_name, reference_info_t&& ref_info); std::map<std::string, std::set<reference_info_t>> _get_referenced_in_backlog() const; void process_embedding_field_delete(const std::string& model_name); static void _populate_referenced_ins(const std::string& collection_meta_json, std::map<std::string, spp::sparse_hash_map<std::string, std::string>>& referenced_ins, std::map<std::string, spp::sparse_hash_map<std::string, std::set<reference_pair_t>>>& async_referenced_ins); std::unordered_set<std::string> get_collection_references(const std::string& coll_name); bool is_valid_api_key_collection(const std::vector<std::string>& api_key_collections, Collection* coll) const; Option<bool> update_collection_metadata(const std::string& collection, const nlohmann::json& metadata); };
9,630
C++
.h
159
47.949686
149
0.62476
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,891
archive_utils.h
typesense_typesense/include/archive_utils.h
#pragma once #include <string> #include <vector> #include <archive.h> #include <archive_entry.h> #include <fcntl.h> #include <sys/stat.h> class ArchiveUtils { public: static constexpr const char* TAR_GZ_EXTENSION = ".tar.gz"; static bool extract_tar_gz_from_file(const std::string& archive_path, const std::string& destination_path); static bool extract_tar_gz_from_memory(const std::string& archive_content, const std::string& destination_path); static bool verify_tar_gz_archive(const std::string& archive_content); private: static constexpr size_t BUFFER_SIZE = (10 * 1024 * 1024); static int copy_data(struct archive* ar, struct archive* aw); static bool create_directory(const std::string& path); static std::string create_temp_tar_gz(const std::string& content); static void cleanup(const std::string& file_path); };
862
C++
.h
20
40.15
116
0.740167
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,892
analytics_manager.h
typesense_typesense/include/analytics_manager.h
#pragma once #include "query_analytics.h" #include "option.h" #include "raft_server.h" #include <vector> #include <string> #include <unordered_map> #include <shared_mutex> #include "lru/lru.hpp" struct event_type_collection { std::string event_type; std::string destination_collection; std::vector<std::string> src_collections; bool log_to_store = false; std::string analytic_rule; QueryAnalytics* queries_ptr = nullptr; }; struct event_t { std::string query; std::string event_type; uint64_t timestamp; std::string user_id; std::string doc_id; std::string name; std::vector<std::pair<std::string, std::string>> data; bool log_to_store; event_t() = delete; ~event_t() = default; event_t(const std::string& q, const std::string& type, uint64_t ts, const std::string& uid, const std::string& id, const std::string& event_name, bool should_log_to_store, const std::vector<std::pair<std::string, std::string>> datavec) { query = q; event_type = type; timestamp = ts; user_id = uid; doc_id = id; name = event_name; log_to_store = should_log_to_store; data = datavec; } event_t& operator=(event_t& other) { if (this != &other) { query = other.query; event_type = other.event_type; timestamp = other.timestamp; user_id = other.user_id; doc_id = other.doc_id; name = other.name; data = other.data; return *this; } } void to_json(nlohmann::json& obj, const std::string& coll) const; }; struct counter_event_t { std::string counter_field; std::map<std::string, uint64_t> docid_counts; std::map<std::string, uint16_t> event_weight_map; void serialize_as_docs(std::string& docs); }; struct event_cache_t { uint64_t last_update_time; uint64_t count; bool operator == (const event_cache_t& res) const { return last_update_time == res.last_update_time; } bool operator != (const event_cache_t& res) const { return last_update_time != res.last_update_time; } }; class AnalyticsManager { private: mutable std::mutex mutex; std::condition_variable cv; std::atomic<bool> quit = false; const size_t QUERY_COMPACTION_INTERVAL_S = 30; struct suggestion_config_t { std::string name; std::string destination_collection; std::vector<std::string> src_collections; size_t limit; std::string rule_type; bool expand_query = false; nlohmann::json events; std::string counter_field; void to_json(nlohmann::json& obj) const { obj["name"] = name; obj["type"] = rule_type; obj["params"] = nlohmann::json::object(); obj["params"]["limit"] = limit; obj["params"]["source"]["collections"] = src_collections; obj["params"]["destination"]["collection"] = destination_collection; if(rule_type == POPULAR_QUERIES_TYPE) { obj["params"]["expand_query"] = expand_query; } if(!events.empty()) { obj["params"]["source"]["events"] = events; obj["params"]["destination"]["counter_field"] = counter_field; } } }; // config name => config std::unordered_map<std::string, suggestion_config_t> suggestion_configs; // query collection => suggestion collections std::unordered_map<std::string, std::vector<std::string>> query_collection_mapping; // suggestion collection => popular queries std::unordered_map<std::string, QueryAnalytics*> popular_queries; // suggestion collection => nohits queries std::unordered_map<std::string, QueryAnalytics*> nohits_queries; // collection => popular clicks std::unordered_map<std::string, counter_event_t> counter_events; //query collection => events std::unordered_map<std::string, std::vector<event_t>> query_collection_events; //event_name => collection std::unordered_map<std::string, event_type_collection> event_collection_map; // per_ip cache for rate limiting LRU::Cache<std::string, event_cache_t> events_cache; Store* store = nullptr; Store* analytics_store = nullptr; bool isRateLimitEnabled = true; uint32_t analytics_minute_rate_limit; AnalyticsManager() {} ~AnalyticsManager(); Option<bool> remove_index(const std::string& name); Option<bool> create_index(nlohmann::json &payload, bool upsert, bool write_to_disk); public: static constexpr const char* ANALYTICS_RULE_PREFIX = "$AR"; static constexpr const char* POPULAR_QUERIES_TYPE = "popular_queries"; static constexpr const char* NOHITS_QUERIES_TYPE = "nohits_queries"; static constexpr const char* COUNTER_TYPE = "counter"; static constexpr const char* LOG_TYPE = "log"; static constexpr const char* CLICK_EVENT = "click"; static constexpr const char* CONVERSION_EVENT = "conversion"; static constexpr const char* VISIT_EVENT = "visit"; static constexpr const char* CUSTOM_EVENT = "custom"; static constexpr const char* SEARCH_EVENT = "search"; static AnalyticsManager& get_instance() { static AnalyticsManager instance; return instance; } AnalyticsManager(AnalyticsManager const&) = delete; void operator=(AnalyticsManager const&) = delete; void init(Store* store, Store* analytics_store, uint32_t analytics_minute_rate_limit); void run(ReplicationState* raft_server); Option<nlohmann::json> list_rules(); Option<nlohmann::json> get_rule(const std::string& name); Option<bool> create_rule(nlohmann::json& payload, bool upsert, bool write_to_disk); Option<bool> remove_rule(const std::string& name); Option<bool> remove_all_rules(); void add_suggestion(const std::string& query_collection, const std::string& query, const std::string& expanded_query, bool live_query, const std::string& user_id); void stop(); void dispose(); void persist_query_events(ReplicationState *raft_server, uint64_t prev_persistence_s); std::unordered_map<std::string, QueryAnalytics*> get_popular_queries(); Option<bool> add_event(const std::string& client_ip, const std::string& event_type, const std::string& event_name, const nlohmann::json& event_data); void persist_events(ReplicationState *raft_server, uint64_t prev_persistence_s); void persist_popular_events(ReplicationState *raft_server, uint64_t prev_persistence_s); std::unordered_map<std::string, counter_event_t> get_popular_clicks(); void add_nohits_query(const std::string& query_collection, const std::string& query, bool live_query, const std::string& user_id); std::unordered_map<std::string, QueryAnalytics*> get_nohits_queries(); void resetToggleRateLimit(bool toggle); bool write_to_db(const nlohmann::json& payload); void get_last_N_events(const std::string& userid, const std::string& event_name, uint32_t N, std::vector<std::string>& values); #ifdef TEST_BUILD std::unordered_map<std::string, std::vector<event_t>> get_log_events() { return query_collection_events; } #endif };
7,473
C++
.h
174
35.689655
134
0.653405
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,893
http_proxy.h
typesense_typesense/include/http_proxy.h
#pragma once #include <unordered_map> #include <string> #include "http_client.h" #include "lru/lru.hpp" struct http_proxy_res_t { std::string body; std::map<std::string, std::string> headers; long status_code; bool operator==(const http_proxy_res_t& other) const { return body == other.body && headers == other.headers && status_code == other.status_code; } bool operator!=(const http_proxy_res_t& other) const { return !(*this == other); } }; class HttpProxy { // singleton class for http proxy public: static const size_t default_timeout_ms = 60000; static const size_t default_num_try = 2; static HttpProxy& get_instance() { static HttpProxy instance; return instance; } HttpProxy(const HttpProxy&) = delete; void operator=(const HttpProxy&) = delete; HttpProxy(HttpProxy&&) = delete; void operator=(HttpProxy&&) = delete; http_proxy_res_t send(const std::string& url, const std::string& method, const std::string& req_body, std::unordered_map<std::string, std::string>& req_headers); private: HttpProxy(); ~HttpProxy() = default; http_proxy_res_t call(const std::string& url, const std::string& method, const std::string& req_body = "", const std::unordered_map<std::string, std::string>& req_headers = {}, const size_t timeout_ms = default_timeout_ms); // lru cache for http requests std::shared_mutex mutex; LRU::TimedCache<uint64_t, http_proxy_res_t> cache; };
1,637
C++
.h
40
33.2
169
0.621537
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,894
collection.h
typesense_typesense/include/collection.h
#pragma once #include <string> #include <vector> #include <string> #include <unordered_map> #include <thread> #include <mutex> #include <condition_variable> #include <shared_mutex> #include "art.h" #include "index.h" #include "number.h" #include "store.h" #include "topster.h" #include "json.hpp" #include "field.h" #include "option.h" #include "tsl/htrie_map.h" #include "tokenizer.h" #include "synonym_index.h" #include "vq_model_manager.h" #include "join.h" struct doc_seq_id_t { uint32_t seq_id; bool is_new; }; struct highlight_field_t { std::string name; bool fully_highlighted; bool infix; bool is_string; tsl::htrie_map<char, token_leaf> qtoken_leaves; highlight_field_t(const std::string& name, bool fully_highlighted, bool infix, bool is_string): name(name), fully_highlighted(fully_highlighted), infix(infix), is_string(is_string) { } }; class Collection { private: mutable std::shared_mutex mutex; // ensures that a Collection* is not destructed while in use by multiple threads mutable std::shared_mutex lifecycle_mutex; const uint8_t CURATED_RECORD_IDENTIFIER = 100; struct highlight_t { size_t field_index; std::string field; std::vector<std::string> snippets; std::vector<std::string> values; std::vector<size_t> indices; uint64_t match_score; std::vector<std::vector<std::string>> matched_tokens; highlight_t(): field_index(0), match_score(0) { } bool operator<(const highlight_t& a) const { return std::tie(match_score, field_index) > std::tie(a.match_score, field_index); } }; struct match_index_t { Match match; uint64_t match_score = 0; size_t index; match_index_t(Match match, uint64_t match_score, size_t index): match(match), match_score(match_score), index(index) { } bool operator<(const match_index_t& a) const { if(match_score != a.match_score) { return match_score > a.match_score; } return index < a.index; } }; const std::string name; const std::atomic<uint32_t> collection_id; const std::atomic<uint64_t> created_at; std::atomic<size_t> num_documents; // Auto incrementing record ID used internally for indexing - not exposed to the client std::atomic<uint32_t> next_seq_id; Store* store; std::vector<field> fields; tsl::htrie_map<char, field> search_schema; std::map<std::string, override_t> overrides; // maps tag name => override_ids std::map<std::string, std::set<std::string>> override_tags; std::string default_sorting_field; const float max_memory_ratio; std::string fallback_field_type; std::unordered_map<std::string, field> dynamic_fields; tsl::htrie_map<char, field> nested_fields; tsl::htrie_map<char, field> embedding_fields; bool enable_nested_fields; std::vector<char> symbols_to_index; std::vector<char> token_separators; SynonymIndex* synonym_index; /// "field name" -> reference_info(referenced_collection_name, referenced_field_name, is_async) spp::sparse_hash_map<std::string, reference_info_t> reference_fields; /// Contains the info where the current collection is referenced. /// Useful to perform operations such as cascading delete. /// collection_name -> field_name spp::sparse_hash_map<std::string, std::string> referenced_in; /// "field name" -> List of <collection, field> pairs where this collection is referenced and is marked as `async`. spp::sparse_hash_map<std::string, std::set<reference_pair_t>> async_referenced_ins; /// Reference helper fields that are part of an object. The reference doc of these fields will be included in the /// object rather than in the document. tsl::htrie_set<char> object_reference_helper_fields; // Keep index as the last field since it is initialized in the constructor via init_index(). Add a new field before it. Index* index; std::shared_ptr<VQModel> vq_model = nullptr; nlohmann::json metadata; // methods std::string get_doc_id_key(const std::string & doc_id) const; std::string get_seq_id_key(uint32_t seq_id) const; void highlight_result(const std::string& h_obj, const field &search_field, const size_t search_field_index, const tsl::htrie_map<char, token_leaf>& qtoken_leaves, const KV* field_order_kv, const nlohmann::json &document, nlohmann::json& highlight_doc, StringUtils & string_utils, const size_t snippet_threshold, const size_t highlight_affix_num_tokens, bool highlight_fully, bool is_infix_search, const std::string& highlight_start_tag, const std::string& highlight_end_tag, const uint8_t* index_symbols, highlight_t &highlight, bool& found_highlight, bool& found_full_highlight) const; void remove_document(nlohmann::json & document, const uint32_t seq_id, bool remove_from_store); void process_remove_field_for_embedding_fields(const field& del_field, std::vector<field>& garbage_embed_fields); bool does_override_match(const override_t& override, std::string& query, std::set<uint32_t>& excluded_set, std::string& actual_query, const std::string& filter_query, bool already_segmented, const bool tags_matched, const bool wildcard_tag_matched, const std::map<size_t, std::vector<std::string>>& pinned_hits, const std::vector<std::string>& hidden_hits, std::vector<std::pair<uint32_t, uint32_t>>& included_ids, std::vector<uint32_t>& excluded_ids, std::vector<const override_t*>& filter_overrides, bool& filter_curated_hits, std::string& curated_sort_by, nlohmann::json& override_metadata) const; void curate_results(std::string& actual_query, const std::string& filter_query, bool enable_overrides, bool already_segmented, const std::set<std::string>& tags, const std::map<size_t, std::vector<std::string>>& pinned_hits, const std::vector<std::string>& hidden_hits, std::vector<std::pair<uint32_t, uint32_t>>& included_ids, std::vector<uint32_t>& excluded_ids, std::vector<const override_t*>& filter_overrides, bool& filter_curated_hits, std::string& curated_sort_by, nlohmann::json& override_metadata) const; static Option<bool> detect_new_fields(nlohmann::json& document, const DIRTY_VALUES& dirty_values, const tsl::htrie_map<char, field>& schema, const std::unordered_map<std::string, field>& dyn_fields, tsl::htrie_map<char, field>& nested_fields, const std::string& fallback_field_type, bool is_update, std::vector<field>& new_fields, bool enable_nested_fields, const spp::sparse_hash_map<std::string, reference_info_t>& reference_fields, tsl::htrie_set<char>& object_reference_helper_fields); static bool check_and_add_nested_field(tsl::htrie_map<char, field>& nested_fields, const field& nested_field); static bool facet_count_compare(const facet_count_t& a, const facet_count_t& b) { return std::tie(a.count, a.fhash) > std::tie(b.count, b.fhash); } static bool facet_count_str_compare(const facet_value_t& a, const facet_value_t& b) { size_t a_count = a.count; size_t b_count = b.count; size_t a_value_size = UINT64_MAX - a.value.size(); size_t b_value_size = UINT64_MAX - b.value.size(); return std::tie(a_count, a_value_size, a.value) > std::tie(b_count, b_value_size, b.value); } static Option<bool> parse_pinned_hits(const std::string& pinned_hits_str, std::map<size_t, std::vector<std::string>>& pinned_hits); static Option<drop_tokens_param_t> parse_drop_tokens_mode(const std::string& drop_tokens_mode); Index* init_index(); static std::vector<char> to_char_array(const std::vector<std::string>& strs); Option<bool> validate_and_standardize_sort_fields_with_lock(const std::vector<sort_by> & sort_fields, std::vector<sort_by>& sort_fields_std, bool is_wildcard_query,const bool is_vector_query, const std::string& query, bool is_group_by_query = false, const size_t remote_embedding_timeout_ms = 30000, const size_t remote_embedding_num_tries = 2) const; Option<bool> validate_and_standardize_sort_fields(const std::vector<sort_by> & sort_fields, std::vector<sort_by>& sort_fields_std, const bool is_wildcard_query, const bool is_vector_query, const std::string& query, bool is_group_by_query = false, const size_t remote_embedding_timeout_ms = 30000, const size_t remote_embedding_num_tries = 2, const bool is_reference_sort = false) const; Option<bool> persist_collection_meta(); Option<bool> batch_alter_data(const std::vector<field>& alter_fields, const std::vector<field>& del_fields, const std::string& this_fallback_field_type); Option<bool> validate_alter_payload(nlohmann::json& schema_changes, std::vector<field>& addition_fields, std::vector<field>& reindex_fields, std::vector<field>& del_fields, std::vector<field>& update_fields, std::string& fallback_field_type); void process_filter_overrides(std::vector<const override_t*>& filter_overrides, std::vector<std::string>& q_include_tokens, token_ordering token_order, filter_node_t*& filter_tree_root, std::vector<std::pair<uint32_t, uint32_t>>& included_ids, std::vector<uint32_t>& excluded_ids, nlohmann::json& override_metadata, bool enable_typos_for_numerical_tokens=true, bool enable_typos_for_alpha_numerical_tokens=true) const; void populate_text_match_info(nlohmann::json& info, uint64_t match_score, const text_match_type_t match_type, const size_t total_tokens) const; bool handle_highlight_text(std::string& text, bool normalise, const field &search_field, const bool is_arr_obj_ele, const std::vector<char>& symbols_to_index, const std::vector<char>& token_separators, highlight_t& highlight, StringUtils & string_utils, bool use_word_tokenizer, const size_t highlight_affix_num_tokens, const tsl::htrie_map<char, token_leaf>& qtoken_leaves, int last_valid_offset_index, const size_t prefix_token_num_chars, bool highlight_fully, const size_t snippet_threshold, bool is_infix_search, std::vector<std::string>& raw_query_tokens, size_t last_valid_offset, const std::string& highlight_start_tag, const std::string& highlight_end_tag, const uint8_t* index_symbols, const match_index_t& match_index) const; static Option<bool> extract_field_name(const std::string& field_name, const tsl::htrie_map<char, field>& search_schema, std::vector<std::string>& processed_search_fields, bool extract_only_string_fields, bool enable_nested_fields, const bool handle_wildcard = true, const bool& include_id = false); bool is_nested_array(const nlohmann::json& obj, std::vector<std::string> path_parts, size_t part_i) const; template<class T> static bool highlight_nested_field(const nlohmann::json& hdoc, nlohmann::json& hobj, std::vector<std::string>& path_parts, size_t path_index, bool is_arr_obj_ele, int array_index, T func); static Option<bool> resolve_field_type(field& new_field, nlohmann::detail::iter_impl<nlohmann::basic_json<>>& kv, nlohmann::json& document, const DIRTY_VALUES& dirty_values, const bool found_dynamic_field, const std::string& fallback_field_type, bool enable_nested_fields, std::vector<field>& new_fields); static uint64_t extract_bits(uint64_t value, unsigned lsb_offset, unsigned n); Option<bool> populate_include_exclude_fields(const spp::sparse_hash_set<std::string>& include_fields, const spp::sparse_hash_set<std::string>& exclude_fields, tsl::htrie_set<char>& include_fields_full, tsl::htrie_set<char>& exclude_fields_full) const; Option<std::string> get_referenced_in_field(const std::string& collection_name) const; void remove_embedding_field(const std::string& field_name); Option<bool> parse_and_validate_vector_query(const std::string& vector_query_str, vector_query_t& vector_query, const bool is_wildcard_query, const size_t remote_embedding_timeout_ms, const size_t remote_embedding_num_tries, size_t& per_page) const; public: enum {MAX_ARRAY_MATCHES = 5}; const size_t GROUP_LIMIT_MAX = 99; // Using a $ prefix so that these meta keys stay above record entries in a lexicographically ordered KV store static constexpr const char* COLLECTION_META_PREFIX = "$CM"; static constexpr const char* COLLECTION_NEXT_SEQ_PREFIX = "$CS"; static constexpr const char* COLLECTION_OVERRIDE_PREFIX = "$CO"; static constexpr const char* SEQ_ID_PREFIX = "$SI"; static constexpr const char* DOC_ID_PREFIX = "$DI"; static constexpr const char* COLLECTION_NAME_KEY = "name"; static constexpr const char* COLLECTION_ID_KEY = "id"; static constexpr const char* COLLECTION_SEARCH_FIELDS_KEY = "fields"; static constexpr const char* COLLECTION_DEFAULT_SORTING_FIELD_KEY = "default_sorting_field"; static constexpr const char* COLLECTION_CREATED = "created_at"; static constexpr const char* COLLECTION_NUM_MEMORY_SHARDS = "num_memory_shards"; static constexpr const char* COLLECTION_FALLBACK_FIELD_TYPE = "fallback_field_type"; static constexpr const char* COLLECTION_ENABLE_NESTED_FIELDS = "enable_nested_fields"; static constexpr const char* COLLECTION_SYMBOLS_TO_INDEX = "symbols_to_index"; static constexpr const char* COLLECTION_SEPARATORS = "token_separators"; static constexpr const char* COLLECTION_VOICE_QUERY_MODEL = "voice_query_model"; static constexpr const char* COLLECTION_METADATA = "metadata"; // methods Collection() = delete; Collection(const std::string& name, const uint32_t collection_id, const uint64_t created_at, const uint32_t next_seq_id, Store *store, const std::vector<field>& fields, const std::string& default_sorting_field, const float max_memory_ratio, const std::string& fallback_field_type, const std::vector<std::string>& symbols_to_index, const std::vector<std::string>& token_separators, const bool enable_nested_fields, std::shared_ptr<VQModel> vq_model = nullptr, spp::sparse_hash_map<std::string, std::string> referenced_in = spp::sparse_hash_map<std::string, std::string>(), const nlohmann::json& metadata = {}, spp::sparse_hash_map<std::string, std::set<reference_pair_t>> async_referenced_ins = spp::sparse_hash_map<std::string, std::set<reference_pair_t>>()); ~Collection(); static std::string get_next_seq_id_key(const std::string & collection_name); static std::string get_meta_key(const std::string & collection_name); static std::string get_override_key(const std::string & collection_name, const std::string & override_id); std::string get_seq_id_collection_prefix() const; std::string get_name() const; uint64_t get_created_at() const; uint32_t get_collection_id() const; uint32_t get_next_seq_id(); Option<uint32_t> doc_id_to_seq_id_with_lock(const std::string & doc_id) const; Option<uint32_t> doc_id_to_seq_id(const std::string & doc_id) const; std::vector<std::string> get_facet_fields(); std::vector<field> get_sort_fields(); std::vector<field> get_fields(); bool contains_field(const std::string&); std::unordered_map<std::string, field> get_dynamic_fields(); tsl::htrie_map<char, field> get_schema(); tsl::htrie_map<char, field> get_nested_fields(); tsl::htrie_map<char, field> get_embedding_fields(); tsl::htrie_map<char, field> get_embedding_fields_unsafe(); tsl::htrie_set<char> get_object_reference_helper_fields(); std::string get_default_sorting_field(); void update_metadata(const nlohmann::json& meta); Option<bool> update_apikey(const nlohmann::json& model_config, const std::string& field_name); Option<doc_seq_id_t> to_doc(const std::string& json_str, nlohmann::json& document, const index_operation_t& operation, const DIRTY_VALUES dirty_values, const std::string& id=""); static uint32_t get_seq_id_from_key(const std::string & key); Option<bool> get_document_from_store(const std::string & seq_id_key, nlohmann::json & document, bool raw_doc = false) const; Option<bool> get_document_from_store(const uint32_t& seq_id, nlohmann::json & document, bool raw_doc = false) const; Option<uint32_t> index_in_memory(nlohmann::json & document, uint32_t seq_id, const index_operation_t op, const DIRTY_VALUES& dirty_values); static void remove_flat_fields(nlohmann::json& document); static void remove_reference_helper_fields(nlohmann::json& document); Option<bool> prune_doc_with_lock(nlohmann::json& doc, const tsl::htrie_set<char>& include_names, const tsl::htrie_set<char>& exclude_names, const std::map<std::string, reference_filter_result_t>& reference_filter_results = {}, const uint32_t& seq_id = 0, const std::vector<ref_include_exclude_fields>& ref_include_exclude_fields_vec = {}); static Option<bool> prune_doc(nlohmann::json& doc, const tsl::htrie_set<char>& include_names, const tsl::htrie_set<char>& exclude_names, const std::string& parent_name = "", size_t depth = 0, const std::map<std::string, reference_filter_result_t>& reference_filter_results = {}, Collection *const collection = nullptr, const uint32_t& seq_id = 0, const std::vector<ref_include_exclude_fields>& ref_include_exclude_fields_vec = {}); const Index* _get_index() const; bool facet_value_to_string(const facet &a_facet, const facet_count_t &facet_count, nlohmann::json &document, std::string &value) const; static nlohmann::json get_parent_object(const nlohmann::json& parent, const nlohmann::json& child, const std::vector<std::string>& field_path, size_t field_index, const std::string& val); nlohmann::json get_facet_parent(const std::string& facet_field_name, const nlohmann::json& document, const std::string& val, bool is_array) const; static void populate_result_kvs(Topster *topster, std::vector<std::vector<KV *>> &result_kvs, const spp::sparse_hash_map<uint64_t, uint32_t>& groups_processed, const std::vector<sort_by>& sort_by_fields); void batch_index(std::vector<index_record>& index_records, std::vector<std::string>& json_out, size_t &num_indexed, const bool& return_doc, const bool& return_id, const size_t remote_embedding_batch_size = 200, const size_t remote_embedding_timeout_ms = 60000, const size_t remote_embedding_num_tries = 2); bool is_exceeding_memory_threshold() const; void parse_search_query(const std::string &query, std::vector<std::string>& q_include_tokens, std::vector<std::string>& q_include_tokens_non_stemmed, std::vector<std::vector<std::string>>& q_exclude_tokens, std::vector<std::vector<std::string>>& q_phrases, const std::string& locale, const bool already_segmented, const std::string& stopword_set="", std::shared_ptr<Stemmer> stemmer = nullptr) const; void process_tokens(std::vector<std::string>& tokens, std::vector<std::string>& q_include_tokens, std::vector<std::vector<std::string>>& q_exclude_tokens, std::vector<std::vector<std::string>>& q_phrases, bool& exclude_operator_prior, bool& phrase_search_op_prior, std::vector<std::string>& phrase, const std::string& stopwords_set, const bool& already_segmented, const std::string& locale, std::shared_ptr<Stemmer> stemmer) const; // PUBLIC OPERATIONS nlohmann::json get_summary_json() const; size_t batch_index_in_memory(std::vector<index_record>& index_records, const size_t remote_embedding_batch_size, const size_t remote_embedding_timeout_ms, const size_t remote_embedding_num_tries, const bool generate_embeddings); Option<nlohmann::json> add(const std::string & json_str, const index_operation_t& operation=CREATE, const std::string& id="", const DIRTY_VALUES& dirty_values=DIRTY_VALUES::COERCE_OR_REJECT); nlohmann::json add_many(std::vector<std::string>& json_lines, nlohmann::json& document, const index_operation_t& operation=CREATE, const std::string& id="", const DIRTY_VALUES& dirty_values=DIRTY_VALUES::COERCE_OR_REJECT, const bool& return_doc=false, const bool& return_id=false, const size_t remote_embedding_batch_size=200, const size_t remote_embedding_timeout_ms=60000, const size_t remote_embedding_num_tries=2); Option<nlohmann::json> update_matching_filter(const std::string& filter_query, const std::string & json_str, std::string& req_dirty_values, const int batch_size = 1000); Option<bool> populate_include_exclude_fields_lk(const spp::sparse_hash_set<std::string>& include_fields, const spp::sparse_hash_set<std::string>& exclude_fields, tsl::htrie_set<char>& include_fields_full, tsl::htrie_set<char>& exclude_fields_full) const; void do_housekeeping(); Option<nlohmann::json> search(std::string query, const std::vector<std::string> & search_fields, const std::string & filter_query, const std::vector<std::string> & facet_fields, const std::vector<sort_by> & sort_fields, const std::vector<uint32_t>& num_typos, size_t per_page = 10, size_t page = 1, token_ordering token_order = FREQUENCY, const std::vector<bool>& prefixes = {true}, size_t drop_tokens_threshold = Index::DROP_TOKENS_THRESHOLD, const spp::sparse_hash_set<std::string> & include_fields = spp::sparse_hash_set<std::string>(), const spp::sparse_hash_set<std::string> & exclude_fields = spp::sparse_hash_set<std::string>(), size_t max_facet_values=10, const std::string & simple_facet_query = "", const size_t snippet_threshold = 30, const size_t highlight_affix_num_tokens = 4, const std::string & highlight_full_fields = "", size_t typo_tokens_threshold = Index::TYPO_TOKENS_THRESHOLD, const std::string& pinned_hits_str="", const std::string& hidden_hits="", const std::vector<std::string>& group_by_fields={}, size_t group_limit = 3, const std::string& highlight_start_tag="<mark>", const std::string& highlight_end_tag="</mark>", std::vector<uint32_t> raw_query_by_weights={}, size_t limit_hits=1000000, bool prioritize_exact_match=true, bool pre_segmented_query=false, bool enable_overrides=true, const std::string& highlight_fields="", const bool exhaustive_search = false, size_t search_stop_millis = 6000*1000, size_t min_len_1typo = 4, size_t min_len_2typo = 7, enable_t split_join_tokens = fallback, size_t max_candidates = 4, const std::vector<enable_t>& infixes = {off}, const size_t max_extra_prefix = INT16_MAX, const size_t max_extra_suffix = INT16_MAX, const size_t facet_query_num_typos = 2, const bool filter_curated_hits_option = false, const bool prioritize_token_position = false, const std::string& vector_query_str = "", const bool enable_highlight_v1 = true, const uint64_t search_time_start_us = 0, const text_match_type_t match_type = max_score, const size_t facet_sample_percent = 100, const size_t facet_sample_threshold = 0, const size_t page_offset = 0, const std::string& facet_index_type = "exhaustive", const size_t remote_embedding_timeout_ms = 30000, const size_t remote_embedding_num_tries = 2, const std::string& stopwords_set="", const std::vector<std::string>& facet_return_parent = {}, const std::vector<ref_include_exclude_fields>& ref_include_exclude_fields_vec = {}, const std::string& drop_tokens_mode = "right_to_left", const bool prioritize_num_matching_fields = true, const bool group_missing_values = true, const bool converstaion = false, const std::string& conversation_model_id = "", std::string conversation_id = "", const std::string& override_tags_str = "", const std::string& voice_query = "", bool enable_typos_for_numerical_tokens = true, bool enable_synonyms = true, bool synonym_prefix = false, uint32_t synonym_num_typos = 0, bool enable_lazy_filter = false, bool enable_typos_for_alpha_numerical_tokens = true, const size_t& max_filter_by_candidates = DEFAULT_FILTER_BY_CANDIDATES, bool rerank_hybrid_matches = false, bool validate_field_names = true) const; Option<bool> get_filter_ids(const std::string & filter_query, filter_result_t& filter_result, const bool& should_timeout = true) const; Option<bool> get_reference_filter_ids(const std::string& filter_query, filter_result_t& filter_result, const std::string& reference_field_name) const; Option<nlohmann::json> get(const std::string & id) const; void cascade_remove_docs(const std::string& field_name, const uint32_t& ref_seq_id, const nlohmann::json& ref_doc, bool remove_from_store = true); Option<std::string> remove(const std::string & id, bool remove_from_store = true); Option<bool> remove_if_found(uint32_t seq_id, bool remove_from_store = true); size_t get_num_documents() const; DIRTY_VALUES parse_dirty_values_option(std::string& dirty_values) const; std::vector<char> get_symbols_to_index(); std::vector<char> get_token_separators(); std::string get_fallback_field_type(); bool get_enable_nested_fields(); std::shared_ptr<VQModel> get_vq_model(); Option<bool> parse_facet(const std::string& facet_field, std::vector<facet>& facets) const; // Override operations Option<uint32_t> add_override(const override_t & override, bool write_to_store = true); Option<uint32_t> remove_override(const std::string & id); Option<std::map<std::string, override_t*>> get_overrides(uint32_t limit=0, uint32_t offset=0); Option<override_t> get_override(const std::string& override_id); // synonym operations Option<std::map<uint32_t, synonym_t*>> get_synonyms(uint32_t limit=0, uint32_t offset=0); bool get_synonym(const std::string& id, synonym_t& synonym); Option<bool> add_synonym(const nlohmann::json& syn_json, bool write_to_store = true); Option<bool> remove_synonym(const std::string & id); void synonym_reduction(const std::vector<std::string>& tokens, const std::string& locale, std::vector<std::vector<std::string>>& results, bool synonym_prefix = false, uint32_t synonym_num_typos = 0) const; SynonymIndex* get_synonym_index(); spp::sparse_hash_map<std::string, reference_info_t> get_reference_fields(); spp::sparse_hash_map<std::string, std::set<reference_pair_t>> get_async_referenced_ins(); // highlight ops static void highlight_text(const std::string& highlight_start_tag, const std::string& highlight_end_tag, const std::string& text, const std::map<size_t, size_t>& token_offsets, size_t snippet_end_offset, std::vector<std::string>& matched_tokens, std::map<size_t, size_t>::iterator& offset_it, std::stringstream& highlighted_text, const uint8_t* index_symbols, size_t snippet_start_offset) ; void process_highlight_fields(const std::vector<search_field_t>& search_fields, const std::vector<std::string>& raw_search_fields, const tsl::htrie_set<char>& include_fields, const tsl::htrie_set<char>& exclude_fields, const std::vector<std::string>& highlight_field_names, const std::vector<std::string>& highlight_full_field_names, const std::vector<enable_t>& infixes, std::vector<std::string>& q_tokens, const tsl::htrie_map<char, token_leaf>& qtoken_set, std::vector<highlight_field_t>& highlight_items) const; static void copy_highlight_doc(std::vector<highlight_field_t>& hightlight_items, const bool nested_fields_enabled, const nlohmann::json& src, nlohmann::json& dst); Option<bool> alter(nlohmann::json& alter_payload); void process_search_field_weights(const std::vector<search_field_t>& search_fields, std::vector<uint32_t>& query_by_weights, std::vector<search_field_t>& weighted_search_fields) const; Option<bool> truncate_after_top_k(const std::string& field_name, size_t k); Option<bool> reference_populate_sort_mapping(int* sort_order, std::vector<size_t>& geopoint_indices, std::vector<sort_by>& sort_fields_std, std::array<spp::sparse_hash_map<uint32_t, int64_t, Hasher32>*, 3>& field_values) const; int64_t reference_string_sort_score(const std::string& field_name, const uint32_t& seq_id) const; bool is_referenced_in(const std::string& collection_name) const; void add_referenced_ins(const std::set<reference_info_t>& ref_infos); void add_referenced_in(const std::string& collection_name, const std::string& field_name, const bool& is_async, const std::string& referenced_field_name); Option<std::string> get_referenced_in_field_with_lock(const std::string& collection_name) const; Option<bool> get_related_ids_with_lock(const std::string& field_name, const uint32_t& seq_id, std::vector<uint32_t>& result) const; Option<bool> update_async_references_with_lock(const std::string& ref_coll_name, const std::string& filter, const std::set<std::string>& filter_values, const uint32_t ref_seq_id, const std::string& field_name); Option<uint32_t> get_sort_index_value_with_lock(const std::string& field_name, const uint32_t& seq_id) const; static void hide_credential(nlohmann::json& json, const std::string& credential_name); friend class filter_result_iterator_t; std::shared_mutex& get_lifecycle_mutex(); void expand_search_query(const std::string& raw_query, size_t offset, size_t total, const search_args* search_params, const std::vector<std::vector<KV*>>& result_group_kvs, const std::vector<std::string>& raw_search_fields, std::string& first_q) const; Option<bool> get_object_array_related_id(const std::string& ref_field_name, const uint32_t& seq_id, const uint32_t& object_index, uint32_t& result) const; Option<bool> get_related_ids(const std::string& ref_field_name, const uint32_t& seq_id, std::vector<uint32_t>& result) const; Option<int64_t> get_geo_distance_with_lock(const std::string& geo_field_name, const uint32_t& seq_id, const S2LatLng& reference_lat_lng, const bool& round_distance = false) const; }; template<class T> bool Collection::highlight_nested_field(const nlohmann::json& hdoc, nlohmann::json& hobj, std::vector<std::string>& path_parts, size_t path_index, bool is_arr_obj_ele, int array_index, T func) { if(path_index == path_parts.size()) { func(hobj, is_arr_obj_ele, array_index); return true; } const std::string& fragment = path_parts[path_index]; const auto& it = hobj.find(fragment); if(it != hobj.end()) { if(it.value().is_array()) { bool resolved = false; for(size_t i = 0; i < it.value().size(); i++) { auto& h_ele = it.value().at(i); is_arr_obj_ele = is_arr_obj_ele || h_ele.is_object(); resolved = highlight_nested_field(hdoc, h_ele, path_parts, path_index + 1, is_arr_obj_ele, i, func) || resolved; } return resolved; } else { return highlight_nested_field(hdoc, it.value(), path_parts, path_index + 1, is_arr_obj_ele, 0, func); } } { return false; } }
39,933
C++
.h
568
50.072183
171
0.554761
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,896
typesense_server_utils.h
typesense_typesense/include/typesense_server_utils.h
#pragma once #include "logger.h" #include <string> #include <iostream> #include <cmdline.h> #include "tsconfig.h" #include "store.h" #include "collection_manager.h" #include <csignal> #include <sys/types.h> #include <sys/stat.h> #include "http_server.h" extern HttpServer* server; void catch_interrupt(int sig); bool directory_exists(const std::string& dir_path); void init_cmdline_options(cmdline::parser& options, int argc, char **argv); int init_root_logger(Config& config, const std::string& server_version); int run_server(const Config& config, const std::string& version, void (*master_server_routes)());
633
C++
.h
19
31.157895
75
0.749588
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,897
num_tree.h
typesense_typesense/include/num_tree.h
#pragma once #include <map> #include "sparsepp.h" #include "sorted_array.h" #include "array_utils.h" #include "ids_t.h" #include "filter.h" class num_tree_t { private: std::map<int64_t, void*> int64map; [[nodiscard]] bool range_inclusive_contains(const int64_t& start, const int64_t& end, const uint32_t& id) const; [[nodiscard]] bool contains(const int64_t& value, const uint32_t& id) const { if (int64map.count(value) == 0) { return false; } auto ids = int64map.at(value); return ids_t::contains(ids, id); } public: ~num_tree_t(); void insert(int64_t value, uint32_t id, bool is_facet=false); void range_inclusive_search(int64_t start, int64_t end, uint32_t** ids, size_t& ids_len); void approx_range_inclusive_search_count(int64_t start, int64_t end, uint32_t& ids_len); void range_inclusive_contains(const int64_t& start, const int64_t& end, const uint32_t& context_ids_length, uint32_t* const& context_ids, size_t& result_ids_len, uint32_t*& result_ids) const; size_t get(int64_t value, std::vector<uint32_t>& geo_result_ids); void search(NUM_COMPARATOR comparator, int64_t value, uint32_t** ids, size_t& ids_len); std::vector<void*> search(const NUM_COMPARATOR& comparator, const int64_t& value, const int64_t& range_end_value = 0) const; uint32_t approx_search_count(NUM_COMPARATOR comparator, int64_t value); void remove(uint64_t value, uint32_t id); size_t size(); void seq_ids_outside_top_k(size_t k, std::vector<uint32_t>& seq_ids); void contains(const NUM_COMPARATOR& comparator, const int64_t& value, const uint32_t& context_ids_length, uint32_t* const& context_ids, size_t& result_ids_len, uint32_t*& result_ids) const; std::pair<int64_t, int64_t> get_min_max(const uint32_t* result_ids, size_t result_ids_len); class iterator_t { /// If true, `id_list_array` is initialized otherwise `id_list_iterator` is. bool is_compact_id_list = true; uint32_t index = 0; uint32_t id_list_array_len = 0; uint32_t* id_list_array = nullptr; id_list_t* id_list = nullptr; id_list_t::iterator_t id_list_iterator = id_list_t::iterator_t(nullptr, nullptr, nullptr, false); public: uint32_t seq_id = 0; bool is_valid = true; /// Holds the upper-bound of the number of seq ids this iterator would match. /// Useful in a scenario where we need to differentiate between iterator not matching any document v/s iterator /// reaching it's end. (is_valid would be false in both these cases) uint32_t approx_filter_ids_length = 0; explicit iterator_t(num_tree_t* num_tree, NUM_COMPARATOR comparator, int64_t value); ~iterator_t(); iterator_t& operator=(iterator_t&& obj) noexcept; /// Returns a tri-state: /// 0: id is not valid /// 1: id is valid /// -1: end of iterator [[nodiscard]] int is_id_valid(uint32_t id); /// Advances the iterator to get the next seq_id. The iterator may become invalid during this operation. void next(); /// Advances the iterator until the seq_id reaches or just overshoots id. The iterator may become invalid during /// this operation. void skip_to(uint32_t id); /// Returns to the initial state of the iterator. void reset(); }; };
3,684
C++
.h
74
40.378378
120
0.61962
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,898
posting_list.h
typesense_typesense/include/posting_list.h
#pragma once #include <map> #include <unordered_map> #include "sorted_array.h" #include "array.h" #include "match_score.h" #include "thread_local_vars.h" typedef uint32_t last_id_t; class filter_result_iterator_t; struct result_iter_state_t { const uint32_t* excluded_result_ids = nullptr; const size_t excluded_result_ids_size = 0; const uint32_t* filter_ids = nullptr; const size_t filter_ids_length = 0; size_t excluded_result_ids_index = 0; size_t filter_ids_index = 0; size_t num_keyword_matches = 0; filter_result_iterator_t* fit = nullptr; result_iter_state_t() = default; result_iter_state_t(const uint32_t* excluded_result_ids, size_t excluded_result_ids_size, const uint32_t* filter_ids, const size_t filter_ids_length) : excluded_result_ids(excluded_result_ids), excluded_result_ids_size(excluded_result_ids_size), filter_ids(filter_ids), filter_ids_length(filter_ids_length) {} result_iter_state_t(const uint32_t* excluded_result_ids, size_t excluded_result_ids_size, filter_result_iterator_t* fit) : excluded_result_ids(excluded_result_ids), excluded_result_ids_size(excluded_result_ids_size), fit(fit){} [[nodiscard]] bool is_filter_provided() const; [[nodiscard]] bool is_filter_valid() const; [[nodiscard]] uint32_t get_filter_id() const; }; /* Compressed chain of blocks that store the document IDs and offsets of a given token. Offsets of singular and multi-valued fields are encoded differently. */ class posting_list_t { public: // A block stores a list of Document IDs, Token Offsets and a Mapping of ID => Offset indices efficiently // Layout of *data: [ids...mappings..offsets] // IDs and Mappings are sorted integers, while offsets are not sorted struct block_t { sorted_array ids; sorted_array offset_index; array offsets; // link to next block block_t* next = nullptr; bool contains(uint32_t id); void remove_and_shift_offset_index(const uint32_t* indices_sorted, uint32_t num_indices); void insert_and_shift_offset_index(const uint32_t index, const uint32_t num_offsets); uint32_t upsert(uint32_t id, const std::vector<uint32_t>& offsets); uint32_t erase(uint32_t id); uint32_t size() { return ids.getLength(); } }; class iterator_t { private: const std::map<last_id_t, block_t*>* id_block_map; block_t* curr_block; uint32_t curr_index; block_t* end_block; bool auto_destroy; uint32_t field_id; public: // uncompressed data structures for performance uint32_t* ids = nullptr; uint32_t* offset_index = nullptr; uint32_t* offsets = nullptr; explicit iterator_t(const std::map<last_id_t, block_t*>* id_block_map, block_t* start, block_t* end, bool auto_destroy = true, uint32_t field_id = 0, bool reverse = false); ~iterator_t(); iterator_t(iterator_t&& rhs) noexcept; iterator_t& operator=(iterator_t&& rhs) noexcept; void reset_cache(); [[nodiscard]] bool valid() const; void next(); void skip_to(uint32_t id); void skip_to_rev(uint32_t id); void set_index(uint32_t index); [[nodiscard]] uint32_t id() const; [[nodiscard]] uint32_t offset() const; [[nodiscard]] uint32_t last_block_id() const; [[nodiscard]] uint32_t first_block_id() const; [[nodiscard]] inline uint32_t index() const; [[nodiscard]] inline block_t* block() const; [[nodiscard]] uint32_t get_field_id() const; posting_list_t::iterator_t clone() const; }; public: // maximum number of IDs (and associated offsets) to store in each block before another block is created const uint16_t BLOCK_MAX_ELEMENTS; uint32_t ids_length = 0; block_t root_block; // keeps track of the *last* ID in each block and is used for partial random access // e.g. 0..[9], 10..[19], 20..[29] // MUST be ordered std::map<last_id_t, block_t*> id_block_map; static bool at_end(const std::vector<posting_list_t::iterator_t>& its); static bool at_end2(const std::vector<posting_list_t::iterator_t>& its); static bool all_ended(const std::vector<posting_list_t::iterator_t>& its); static bool all_ended2(const std::vector<posting_list_t::iterator_t>& its); static bool equals(std::vector<posting_list_t::iterator_t>& its); static bool equals2(std::vector<posting_list_t::iterator_t>& its); static void advance_all(std::vector<posting_list_t::iterator_t>& its); static void advance_all2(std::vector<posting_list_t::iterator_t>& its); static void advance_non_largest(std::vector<posting_list_t::iterator_t>& its); static void advance_non_largest2(std::vector<posting_list_t::iterator_t>& its); static uint32_t advance_smallest(std::vector<posting_list_t::iterator_t>& its); static uint32_t advance_smallest2(std::vector<posting_list_t::iterator_t>& its); posting_list_t() = delete; explicit posting_list_t(uint16_t max_block_elements); ~posting_list_t(); static void split_block(block_t* src_block, block_t* dst_block); static void merge_adjacent_blocks(block_t* block1, block_t* block2, size_t num_block2_ids_to_move); void upsert(uint32_t id, const std::vector<uint32_t>& offsets); void erase(uint32_t id); void dump(); block_t* get_root(); size_t num_blocks() const; size_t num_ids() const; uint32_t first_id(); block_t* block_of(uint32_t id); bool contains(uint32_t id); bool contains_atleast_one(const uint32_t* target_ids, size_t target_ids_size); iterator_t new_iterator(block_t* start_block = nullptr, block_t* end_block = nullptr, uint32_t field_id = 0); iterator_t new_rev_iterator(); static void merge(const std::vector<posting_list_t*>& posting_lists, std::vector<uint32_t>& result_ids); static void intersect(const std::vector<posting_list_t*>& posting_lists, std::vector<uint32_t>& result_ids); static void intersect(std::vector<posting_list_t::iterator_t>& posting_list_iterators, bool& is_valid); template<class T> static bool block_intersect( std::vector<posting_list_t::iterator_t>& its, result_iter_state_t& istate, T func ); static bool take_id(result_iter_state_t& istate, uint32_t id); static void get_offsets(iterator_t& iter, std::vector<uint32_t>& positions); static bool get_offsets( const std::vector<iterator_t>& its, std::map<size_t, std::vector<token_positions_t>>& array_token_pos ); static bool is_single_token_verbatim_match(const posting_list_t::iterator_t& it, bool field_is_array); static bool is_single_token_prefix_match(const posting_list_t::iterator_t& it, bool field_is_array); static void get_prefix_matches(std::vector<iterator_t>& its, const bool field_is_array, const uint32_t* ids, const uint32_t num_ids, uint32_t*& prefix_ids, size_t& num_prefix_ids); static void get_exact_matches(std::vector<iterator_t>& its, bool field_is_array, const uint32_t* ids, const uint32_t num_ids, uint32_t*& exact_ids, size_t& num_exact_ids); static bool has_prefix_match(std::vector<posting_list_t::iterator_t>& posting_list_iterators, const bool field_is_array); static bool has_exact_match(std::vector<posting_list_t::iterator_t>& posting_list_iterators, const bool field_is_array); static void get_phrase_matches(std::vector<iterator_t>& its, bool field_is_array, const uint32_t* ids, const uint32_t num_ids, uint32_t*& phrase_ids, size_t& num_phrase_ids); static bool has_phrase_match(const std::vector<token_positions_t>& token_positions); static bool found_token_sequence(const std::vector<token_positions_t>& token_positions, const size_t token_index, const uint16_t target_pos); static void get_matching_array_indices(uint32_t id, std::vector<iterator_t>& its, std::vector<size_t>& indices); static size_t get_last_offset(const posting_list_t::iterator_t& it, bool field_is_array); }; template<class T> bool posting_list_t::block_intersect(std::vector<posting_list_t::iterator_t>& its, result_iter_state_t& istate, T func) { size_t num_processed = 0; switch (its.size()) { case 0: break; case 1: while(its[0].valid()) { num_processed++; if (num_processed % 65536 == 0 && (std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::system_clock::now().time_since_epoch()).count() - search_begin_us) > search_stop_us) { search_cutoff = true; break; } if(posting_list_t::take_id(istate, its[0].id())) { func(its[0].id(), its); } its[0].next(); } break; case 2: while(!at_end2(its)) { num_processed++; if (num_processed % 65536 == 0 && (std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::system_clock::now().time_since_epoch()).count() - search_begin_us) > search_stop_us) { search_cutoff = true; break; } if(equals2(its)) { if(posting_list_t::take_id(istate, its[0].id())) { func(its[0].id(), its); } advance_all2(its); } else { advance_non_largest2(its); } } break; default: while(!at_end(its)) { num_processed++; if (num_processed % 65536 == 0 && (std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::system_clock::now().time_since_epoch()).count() - search_begin_us) > search_stop_us) { search_cutoff = true; break; } if(equals(its)) { //LOG(INFO) << its[0].id(); if(posting_list_t::take_id(istate, its[0].id())) { func(its[0].id(), its); } advance_all(its); } else { advance_non_largest(its); } } } return false; }
11,285
C++
.h
223
38.704036
149
0.586659
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,899
stopwords_manager.h
typesense_typesense/include/stopwords_manager.h
#pragma once #include "sparsepp.h" #include "option.h" #include "json.hpp" #include "shared_mutex" #include "mutex" #include "store.h" struct stopword_struct_t { std::string id; spp::sparse_hash_set<std::string> stopwords; std::string locale; nlohmann::json to_json() const { nlohmann::json doc; doc["id"] = id; if(!locale.empty()) { doc["locale"] = locale; } for(const auto& stopword : stopwords) { doc["stopwords"].push_back(stopword); } return doc; } }; class StopwordsManager{ private: spp::sparse_hash_map<std::string, stopword_struct_t> stopword_configs; static std::string get_stopword_key(const std::string & stopword_name); mutable std::shared_mutex mutex; Store* store = nullptr; public: StopwordsManager() = default; ~StopwordsManager() { stopword_configs.clear(); } static constexpr const char* STOPWORD_PREFIX = "$SW"; static StopwordsManager& get_instance() { static StopwordsManager instance; return instance; } void init(Store* store); spp::sparse_hash_map<std::string, stopword_struct_t> get_stopwords() const; Option<bool> get_stopword(const std::string&, stopword_struct_t&) const; Option<bool> upsert_stopword(const std::string&, const nlohmann::json&, bool write_to_store=false); Option<bool> delete_stopword(const std::string&); void dispose(); bool stopword_exists(const std::string&); };
1,523
C++
.h
47
26.914894
103
0.663693
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,900
housekeeper.h
typesense_typesense/include/housekeeper.h
#pragma once #include <mutex> #include <atomic> #include <condition_variable> #include "http_data.h" class HouseKeeper { private: mutable std::mutex mutex; std::condition_variable cv; std::atomic<bool> quit = false; std::atomic<uint32_t> remove_expired_keys_interval_s = 3600; std::atomic<uint32_t> memory_req_min_age_s = 6; std::atomic<uint32_t> memory_usage_interval_s = 3; // used to track in-flight queries so they can be logged during a crash / rapid memory growth std::mutex ifq_mutex; struct req_metadata_t { std::shared_ptr<http_req> req; uint64_t active_memory = 0; bool already_logged = false; req_metadata_t(const std::shared_ptr<http_req>& req, uint64_t active_memory): req(req), active_memory(active_memory) { } }; std::map<uint64_t, req_metadata_t> in_flight_queries; std::atomic<uint64_t> active_memory_used = 0; HouseKeeper() {} ~HouseKeeper() {} public: static HouseKeeper &get_instance() { static HouseKeeper instance; return instance; } HouseKeeper(HouseKeeper const &) = delete; void operator=(HouseKeeper const &) = delete; void init(); uint64_t get_active_memory_used(); void add_req(const std::shared_ptr<http_req>& req); void remove_req(uint64_t req_id); std::string get_query_log(const std::shared_ptr<http_req>& req); void log_bad_queries(); void log_running_queries(); void run(); void stop(); };
1,526
C++
.h
44
29.090909
97
0.662329
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,901
threadpool.h
typesense_typesense/include/threadpool.h
// https://github.com/jhasse/ThreadPool #pragma once #include <functional> #include <future> #include <queue> #include "logger.h" class ThreadPool { public: explicit ThreadPool(size_t); template<class F, class... Args> decltype(auto) enqueue(F&& f, Args&&... args); void log_exhaustion(); void shutdown(); private: // need to keep track of threads so we can join them std::vector< std::thread > workers; // the task queue std::queue< std::packaged_task<void()> > tasks; // synchronization std::mutex queue_mutex; std::condition_variable condition; std::condition_variable condition_producers; bool stop; }; // the constructor just launches some amount of workers inline ThreadPool::ThreadPool(size_t threads) : stop(false) { for(size_t i = 0;i<threads;++i) workers.emplace_back( [this] { for(;;) { std::packaged_task<void()> task; { std::unique_lock<std::mutex> lock(this->queue_mutex); this->condition.wait(lock, [this]{ return this->stop || !this->tasks.empty(); }); if(this->stop) { return; } if(this->tasks.empty()) { continue; } task = std::move(this->tasks.front()); this->tasks.pop(); if (tasks.empty()) { condition_producers.notify_one(); // notify the destructor that the queue is empty } } task(); } } ); } // add new work item to the pool template<class F, class... Args> decltype(auto) ThreadPool::enqueue(F&& f, Args&&... args) { using return_type = std::invoke_result_t<F, Args...>; std::packaged_task<return_type()> task( std::bind(std::forward<F>(f), std::forward<Args>(args)...) ); std::future<return_type> res = task.get_future(); { std::unique_lock<std::mutex> lock(queue_mutex); // don't allow enqueueing after stopping the pool if(!stop) { tasks.emplace(std::move(task)); } } condition.notify_one(); return res; } inline void ThreadPool::shutdown() { { std::unique_lock<std::mutex> lock(queue_mutex); condition_producers.wait(lock, [this] { return tasks.empty(); }); stop = true; } condition.notify_all(); for (std::thread& worker : workers) { worker.join(); } } inline void ThreadPool::log_exhaustion() { std::unique_lock<std::mutex> lock(queue_mutex); if(tasks.size() >= workers.size()) { LOG(WARNING) << "Threadpool exhaustion detected, task_queue_len: " << tasks.size() << ", thread_pool_len: " << workers.size(); } }
3,152
C++
.h
93
23.139785
114
0.508207
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,903
array.h
typesense_typesense/include/array.h
#pragma once #include <stdio.h> #include <cstdlib> #include <for.h> #include <cstring> #include <limits> #include <iostream> #include "array_base.h" class array: public array_base { private: uint32_t inline unsorted_append_size_required(uint32_t value, uint32_t new_length) { uint32_t m = std::min(min, value); uint32_t M = std::max(max, value); uint32_t bnew = required_bits(M - m); return METADATA_OVERHEAD + 4 + for_compressed_size_bits(new_length, bnew); } public: void load(const uint32_t *sorted_array, uint32_t array_length, uint32_t m, uint32_t M); uint32_t at(uint32_t index); bool contains(uint32_t value); uint32_t indexOf(uint32_t value); bool append(uint32_t value); bool insert(size_t index, const uint32_t* values, size_t num_values); void remove_index(uint32_t start_index, uint32_t end_index); };
890
C++
.h
25
31.56
91
0.694282
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,904
conversation_model.h
typesense_typesense/include/conversation_model.h
#pragma once #include <string> #include <condition_variable> #include <mutex> #include <json.hpp> #include "option.h" struct async_conversation_t { std::string response; std::mutex mutex; std::condition_variable cv; }; class ConversationModel { public: virtual ~ConversationModel() {}; static Option<std::string> get_answer(const std::string& context, const std::string& prompt, const nlohmann::json& model_config); static Option<bool> validate_model(const nlohmann::json& model_config); static Option<std::string> get_standalone_question(const nlohmann::json& conversation_history, const std::string& question, const nlohmann::json& model_config); static Option<nlohmann::json> format_question(const std::string& message, const nlohmann::json& model_config); static Option<nlohmann::json> format_answer(const std::string& message, const nlohmann::json& model_config); static Option<size_t> get_minimum_required_bytes(const nlohmann::json& model_config); protected: static const inline std::string CONVERSATION_HISTORY = "\n\n<Conversation history>\n"; static const inline std::string QUESTION = "\n\n<Question>\n"; static const inline std::string STANDALONE_QUESTION_PROMPT = "\n\n<Standalone question>\n"; }; class OpenAIConversationModel : public ConversationModel { public: static Option<std::string> get_answer(const std::string& context, const std::string& prompt, const std::string& system_prompt, const nlohmann::json& model_config); static Option<bool> validate_model(const nlohmann::json& model_config); static Option<std::string> get_standalone_question(const nlohmann::json& conversation_history, const std::string& question, const nlohmann::json& model_config); static Option<nlohmann::json> format_question(const std::string& message); static Option<nlohmann::json> format_answer(const std::string& message); // max_bytes must be greater than or equal to the minimum required bytes static const size_t get_minimum_required_bytes() { return DATA_STR.size() + QUESTION_STR.size() + ANSWER_STR.size(); } static const inline std::string STANDALONE_QUESTION_PROMPT = R"( Rewrite the follow-up question on top of a human-assistant conversation history as a standalone question that encompasses all pertinent context. )"; // prevent instantiation OpenAIConversationModel() = delete; private: static constexpr char* OPENAI_LIST_MODELS = "https://api.openai.com/v1/models"; static constexpr char* OPENAI_CHAT_COMPLETION = "https://api.openai.com/v1/chat/completions"; static const inline std::string DATA_STR = "<Data>\n"; static const inline std::string QUESTION_STR = "\n\n<Question>\n"; static const inline std::string ANSWER_STR = "\n\n<Answer>"; }; class CFConversationModel : public ConversationModel { public: static Option<std::string> get_answer(const std::string& context, const std::string& prompt, const std::string& system_prompt, const nlohmann::json& model_config); static Option<bool> validate_model(const nlohmann::json& model_config); static Option<std::string> get_standalone_question(const nlohmann::json& conversation_history, const std::string& question, const nlohmann::json& model_config); static Option<nlohmann::json> format_question(const std::string& message); static Option<nlohmann::json> format_answer(const std::string& message); static Option<std::string> parse_stream_response(const std::string& response); static const inline std::string STANDALONE_QUESTION_PROMPT = R"( Rewrite the follow-up question on top of a human-assistant conversation history as a standalone question that encompasses all pertinent context.Use 1024 characters maximum. )"; static const inline std::string INFO_PROMPT = "You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and do not mention provided context directly, act like already knowing the context."; // prevent instantiation CFConversationModel() = delete; static const size_t get_minimum_required_bytes() { return CONTEXT_INFO.size() + SPLITTER_STR.size() + QUERY_STR.size() + ANSWER_STR.size(); } private: static const inline std::vector<std::string> CF_MODEL_NAMES{"mistral/mistral-7b-instruct-v0.1"}; static const std::string get_model_url(const std::string& model_name, const std::string& account_id); static const inline std::string CONTEXT_INFO = "Context information is below.\n"; static const inline std::string SPLITTER_STR = "---------------------\n"; static const inline std::string QUERY_STR = "Given the context information and not prior knowledge, answer the query. Context is JSON format, do not return data directly, answer like a human assistant.\nQuery: "; static const inline std::string ANSWER_STR = "\n\nAnswer:\n"; }; class vLLMConversationModel : public ConversationModel { public: static Option<std::string> get_answer(const std::string& context, const std::string& prompt, const std::string& system_prompt, const nlohmann::json& model_config); static Option<bool> validate_model(const nlohmann::json& model_config); static Option<std::string> get_standalone_question(const nlohmann::json& conversation_history, const std::string& question, const nlohmann::json& model_config); static Option<nlohmann::json> format_question(const std::string& message); static Option<nlohmann::json> format_answer(const std::string& message); static const inline std::string STANDALONE_QUESTION_PROMPT = R"( Rewrite the follow-up question on top of a human-assistant conversation history as a standalone question that encompasses all pertinent context. )"; // prevent instantiation vLLMConversationModel() = delete; // max_bytes must be greater than or equal to the minimum required bytes static const size_t get_minimum_required_bytes() { return DATA_STR.size() + QUESTION_STR.size() + ANSWER_STR.size(); } private: static const std::string get_list_models_url(const std::string& url); static const std::string get_chat_completion_url(const std::string& url); static const inline std::string DATA_STR = "<Data>\n"; static const inline std::string QUESTION_STR = "\n\n<Question>\n"; static const inline std::string ANSWER_STR = "\n\n<Answer>"; };
6,815
C++
.h
96
63.458333
349
0.709178
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,906
facet_index.h
typesense_typesense/include/facet_index.h
#pragma once #include "ids_t.h" #include "tsl/htrie_map.h" #include <unordered_set> #include <posting_list.h> #include <num_tree.h> #include <list> #include <field.h> struct facet_value_id_t { std::string facet_value; uint32_t facet_id = UINT32_MAX; bool operator==(const facet_value_id_t& other) const { return facet_value == other.facet_value; } // Hash function for the struct struct Hash { std::size_t operator()(const facet_value_id_t& value) const { return std::hash<std::string>{}(value.facet_value); } }; facet_value_id_t() = default; facet_value_id_t(const std::string& fvalue, const uint32_t fid): facet_value(fvalue), facet_id(fid) { } facet_value_id_t(const std::string& fvalue): facet_value(fvalue), facet_id(UINT32_MAX) { } }; struct docid_count_t { uint32_t doc_id; uint32_t count; }; class facet_index_t { public: struct facet_count_t { facet_count_t() = delete; ~facet_count_t () = default; facet_count_t(const std::string& sv, uint32_t facet_count, uint32_t this_facet_id) { facet_value = sv; count = facet_count; facet_id = this_facet_id; } facet_count_t& operator=(facet_count_t& obj) { facet_value = obj.facet_value; count = obj.count; facet_id = obj.facet_id; return *this; } std::string facet_value; uint32_t count; uint32_t facet_id; bool operator<(const facet_count_t& other) const { return count > other.count; } }; const static size_t MAX_FACET_VAL_LEN = 255; private: struct facet_id_seq_ids_t { void* seq_ids; uint32_t facet_id; std::multiset<facet_count_t>::iterator facet_count_it; facet_id_seq_ids_t() { seq_ids = nullptr; facet_id = UINT32_MAX; } ~facet_id_seq_ids_t() {}; }; struct facet_doc_ids_list_t { std::map<std::string, facet_id_seq_ids_t> fvalue_seq_ids; std::multiset<facet_count_t> counts; posting_list_t* seq_id_hashes = nullptr; spp::sparse_hash_map<uint32_t, int64_t> fhash_to_int64_map; bool has_value_index = true; bool has_hash_index = true; facet_doc_ids_list_t() { fvalue_seq_ids.clear(); counts.clear(); seq_id_hashes = new posting_list_t(256); } facet_doc_ids_list_t(const facet_doc_ids_list_t& other) = delete; ~facet_doc_ids_list_t() { for(auto it = fvalue_seq_ids.begin(); it != fvalue_seq_ids.end(); ++it) { if(it->second.seq_ids) { ids_t::destroy_list(it->second.seq_ids); } } fvalue_seq_ids.clear(); counts.clear(); delete seq_id_hashes; } }; // field -> facet_index std::unordered_map<std::string, facet_doc_ids_list_t> facet_field_map; // auto incrementing ID that is assigned to each unique facet value string std::atomic_uint32_t next_facet_id = 0; void get_stringified_value(const nlohmann::json& value, const field& afield, std::vector<std::string>& values); void get_stringified_values(const nlohmann::json& document, const field& afield, std::vector<std::string>& values); public: facet_index_t() = default; ~facet_index_t(); void insert(const std::string& field_name, std::unordered_map<facet_value_id_t, std::vector<uint32_t>, facet_value_id_t::Hash>& fvalue_to_seq_ids, std::unordered_map<uint32_t, std::vector<facet_value_id_t>>& seq_id_to_fvalues, bool is_string_field = false); void erase(const std::string& field_name); void remove(const nlohmann::json& doc, const field& afield, const uint32_t seq_id); bool contains(const std::string& field_name); size_t get_facet_count(const std::string& field_name); size_t intersect(facet& a_facet, const field& facet_field, bool has_facet_query, bool estimate_facets, size_t facet_sample_interval, const std::vector<std::vector<std::string>>& fvalue_searched_tokens, const std::vector<char>& symbols_to_index, const std::vector<char>& token_separators, const uint32_t* result_ids, size_t result_id_len, size_t max_facet_count, std::map<std::string, docid_count_t>& found, bool is_wildcard_no_filter_query, const std::string& sort_order = ""); size_t get_facet_indexes(const std::string& field, std::map<uint32_t, std::vector<uint32_t>>& seqid_countIndexes); void initialize(const std::string& field); void handle_index_change(const std::string& field_name, size_t total_num_docs, size_t facet_index_threshold, size_t facet_count); void check_for_high_cardinality(const std::string& field_name, size_t total_num_docs); bool has_hash_index(const std::string& field_name); bool has_value_index(const std::string& field_name); posting_list_t* get_facet_hash_index(const std::string& field_name); //get fhash=>int64 map for stats const spp::sparse_hash_map<uint32_t, int64_t>& get_fhash_int64_map(const std::string& field_name); static void update_count_nodes(std::list<facet_count_t>& count_list, std::map<uint32_t, std::list<facet_count_t>::iterator>& count_map, uint32_t old_count, uint32_t new_count, std::list<facet_count_t>::iterator& curr); bool facet_value_exists(const std::string& field_name, const std::string& fvalue); size_t facet_val_num_ids(const std::string& field_name, const std::string& fvalue); size_t facet_node_count(const std::string& field_name, const std::string& fvalue); };
6,101
C++
.h
136
35.110294
106
0.601764
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,907
ids_t.h
typesense_typesense/include/ids_t.h
#pragma once #include <cstdint> #include <vector> #include "id_list.h" #include "threadpool.h" #define IS_COMPACT_IDS(x) (((uintptr_t)(x) & 1)) #define SET_COMPACT_IDS(x) ((void*)((uintptr_t)(x) | 1)) #define RAW_IDS_PTR(x) ((void*)((uintptr_t)(x) & ~1)) #define COMPACT_IDS_PTR(x) ((compact_id_list_t*)((uintptr_t)(x) & ~1)) struct compact_id_list_t { // structured to get 4 byte alignment for `ids` uint8_t length = 0; uint16_t capacity = 0; // format: id1, id2,... uint32_t ids[]; static compact_id_list_t* create(uint32_t num_ids, const std::vector<uint32_t>& ids); static compact_id_list_t* create(uint32_t num_ids, const uint32_t* ids); [[nodiscard]] id_list_t* to_full_ids_list() const; bool contains(uint32_t id); int64_t upsert(uint32_t id); void erase(uint32_t id); uint32_t first_id(); uint32_t last_id(); [[nodiscard]] uint32_t num_ids() const; size_t intersect_count(const uint32_t* res_ids, size_t res_ids_len); }; class ids_t { public: static constexpr size_t COMPACT_LIST_THRESHOLD_LENGTH = 64; static constexpr size_t MAX_BLOCK_ELEMENTS = 256; struct block_intersector_t { std::vector<id_list_t*> id_lists; std::vector<id_list_t*> expanded_id_lists; id_list_t::result_iter_state_t& iter_state; ThreadPool* thread_pool; size_t parallelize_min_ids; block_intersector_t(const std::vector<void*>& raw_id_lists, id_list_t::result_iter_state_t& iter_state, ThreadPool* thread_pool, size_t parallelize_min_ids = 1): iter_state(iter_state), thread_pool(thread_pool), parallelize_min_ids(parallelize_min_ids) { to_expanded_id_lists(raw_id_lists, id_lists, expanded_id_lists); if(id_lists.size() > 1) { std::sort(this->id_lists.begin(), this->id_lists.end(), [](id_list_t* a, id_list_t* b) { return a->num_blocks() < b->num_blocks(); }); } } ~block_intersector_t() { for(auto expanded_id_list: expanded_id_lists) { delete expanded_id_list; } } template<class T> bool intersect(T func, size_t concurrency=4); void split_lists(size_t concurrency, std::vector<std::vector<id_list_t::iterator_t>>& partial_its_vec); }; static void upsert(void*& obj, uint32_t id); static void erase(void*& obj, uint32_t id); static void destroy_list(void*& obj); static uint32_t num_ids(const void* obj); static uint32_t first_id(const void* obj); static bool contains(const void* obj, uint32_t id); static void merge(const std::vector<void*>& id_lists, std::vector<uint32_t>& result_ids); static void intersect(const std::vector<void*>& id_lists, std::vector<uint32_t>& result_ids); static uint32_t* uncompress(void*& obj); static void uncompress(void*& obj, std::vector<uint32_t>& ids); static size_t intersect_count(void*& obj, const uint32_t* result_ids, size_t result_ids_len, bool estimate_facets = false, size_t facet_sample_mod_value = 1); static void to_expanded_id_lists(const std::vector<void*>& raw_id_lists, std::vector<id_list_t*>& id_lists, std::vector<id_list_t*>& expanded_id_lists); static void* create(const std::vector<uint32_t>& ids); }; template<class T> bool ids_t::block_intersector_t::intersect(T func, size_t concurrency) { // Split id lists into N chunks and intersect them in-parallel // 1. Sort id lists by number of blocks // 2. Iterate on the id list with least number of blocks on N-block windows // 3. On each window, pick the last block's last ID and identify blocks from other lists containing that ID // 4. Construct N groups of iterators this way (the last block must overlap on both sides of the window) if(id_lists.empty()) { return true; } if(id_lists[0]->num_ids() < parallelize_min_ids) { std::vector<id_list_t::iterator_t> its; its.reserve(id_lists.size()); for(const auto& id_list: id_lists) { its.push_back(id_list->new_iterator()); } id_list_t::block_intersect<T>(its, iter_state, func); return true; } std::vector<std::vector<id_list_t::iterator_t>> partial_its_vec(concurrency); split_lists(concurrency, partial_its_vec); size_t num_processed = 0; std::mutex m_process; std::condition_variable cv_process; size_t num_non_empty = 0; for(size_t i = 0; i < partial_its_vec.size(); i++) { auto& partial_its = partial_its_vec[i]; if(partial_its.empty()) { continue; } num_non_empty++; thread_pool->enqueue([this, i, &func, &partial_its, &num_processed, &m_process, &cv_process]() { auto iter_state_copy = iter_state; iter_state_copy.index = i; id_list_t::block_intersect<T>(partial_its, iter_state_copy, func); std::unique_lock<std::mutex> lock(m_process); num_processed++; cv_process.notify_one(); }); } std::unique_lock<std::mutex> lock_process(m_process); cv_process.wait(lock_process, [&](){ return num_processed == num_non_empty; }); return true; }
5,449
C++
.h
118
37.838983
111
0.614497
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,908
file_utils.h
typesense_typesense/include/file_utils.h
#pragma once bool directory_exists(const std::string & dir_path); bool create_directory(const std::string& dir_path); bool file_exists(const std::string & file_path); // tries to hard link first bool copy_dir(const std::string& from_path, const std::string& to_path); bool mv_dir(const std::string& from_path, const std::string& to_path); bool rename_path(const std::string& from_path, const std::string& to_path); bool delete_path(const std::string& path, bool recursive = true); bool dir_enum_count(const std::string & path);
535
C++
.h
10
51.8
75
0.750965
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,909
stackprinter.h
typesense_typesense/include/stackprinter.h
#include <string> #include <unistd.h> #include <execinfo.h> #include <regex> // Currently used only for Mac. Using backward.hpp for Linux. class StackPrinter { public: static std::string getexepath() { char result[PATH_MAX]; ssize_t count = readlink("/proc/self/exe", result, PATH_MAX); return std::string(result, (count > 0) ? count : 0); } static std::string sh(const std::string& cmd) { std::array<char, 128> buffer; std::string result; std::shared_ptr<FILE> pipe(popen(cmd.c_str(), "r"), pclose); if (!pipe) throw std::runtime_error("popen() failed!"); size_t bt_num = 0; std::string optional_space; #if __linux__ optional_space = " "; #endif while (!feof(pipe.get())) { if (fgets(buffer.data(), 128, pipe.get()) != nullptr) { if(bt_num++ % 2 == 1) { result += optional_space + buffer.data(); } else { result += buffer.data(); } } } return result; } static void bt_sighandler(int sig) { void *bt[1024]; char **bt_syms; size_t bt_size; bt_size = backtrace(bt, 1024); bt_syms = backtrace_symbols(bt, bt_size); LOG(ERROR) << "Typesense crashed..."; std::regex linux_address_re("\\[(.+)\\]"); std::string addrs; for (size_t i = 1; i < bt_size; i++) { std::string sym = bt_syms[i]; LOG(ERROR) << sym; #if __linux__ std::smatch matches; if (std::regex_search(sym, matches, linux_address_re)) { std::string addr = matches[1]; addrs += " " + addr; } #elif __APPLE__ std::vector<std::string> sym_parts; StringUtils::split(sym, sym_parts, " "); addrs += " " + (sym_parts.size() > 2 ? sym_parts[2] : ""); #endif } #if __linux__ LOG(ERROR) << "Generating detailed stack trace..."; std::string command = std::string("addr2line -e ") + getexepath() + " -f -C " + addrs; LOG(ERROR) << sh(command); #elif __APPLE__ LOG(ERROR) << "Generating detailed stack trace..."; std::string command = std::string("atos -p ") + std::to_string(getpid()) + " " + addrs; LOG(ERROR) << sh(command); #endif exit(-1); } };
2,546
C++
.h
69
26.42029
99
0.490459
typesense/typesense
20,571
633
548
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,917
main.cpp
trojan-gfw_trojan/src/main.cpp
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <iostream> #include <boost/asio/signal_set.hpp> #include <boost/program_options.hpp> #include <boost/version.hpp> #include <openssl/opensslv.h> #ifdef ENABLE_MYSQL #include <mysql.h> #endif // ENABLE_MYSQL #include "core/service.h" #include "core/version.h" using namespace std; using namespace boost::asio; namespace po = boost::program_options; #ifndef DEFAULT_CONFIG #define DEFAULT_CONFIG "config.json" #endif // DEFAULT_CONFIG void signal_async_wait(signal_set &sig, Service &service, bool &restart) { sig.async_wait([&](const boost::system::error_code error, int signum) { if (error) { return; } Log::log_with_date_time("got signal: " + to_string(signum), Log::WARN); switch (signum) { case SIGINT: case SIGTERM: service.stop(); break; #ifndef _WIN32 case SIGHUP: restart = true; service.stop(); break; case SIGUSR1: service.reload_cert(); signal_async_wait(sig, service, restart); break; #endif // _WIN32 } }); } int main(int argc, const char *argv[]) { try { Log::log("Welcome to trojan " + Version::get_version(), Log::FATAL); string config_file; string log_file; string keylog_file; bool test; po::options_description desc("options"); desc.add_options() ("config,c", po::value<string>(&config_file)->default_value(DEFAULT_CONFIG)->value_name("CONFIG"), "specify config file") ("help,h", "print help message") ("keylog,k", po::value<string>(&keylog_file)->value_name("KEYLOG"), "specify keylog file location (OpenSSL >= 1.1.1)") ("log,l", po::value<string>(&log_file)->value_name("LOG"), "specify log file location") ("test,t", po::bool_switch(&test), "test config file") ("version,v", "print version and build info") ; po::positional_options_description pd; pd.add("config", 1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(pd).run(), vm); po::notify(vm); if (vm.count("help")) { Log::log(string("usage: ") + argv[0] + " [-htv] [-l LOG] [-k KEYLOG] [[-c] CONFIG]", Log::FATAL); cerr << desc; exit(EXIT_SUCCESS); } if (vm.count("version")) { Log::log(string("Boost ") + BOOST_LIB_VERSION + ", " + OpenSSL_version(OPENSSL_VERSION), Log::FATAL); #ifdef ENABLE_MYSQL Log::log(string(" [Enabled] MySQL Support (") + mysql_get_client_info() + ')', Log::FATAL); #else // ENABLE_MYSQL Log::log("[Disabled] MySQL Support", Log::FATAL); #endif // ENABLE_MYSQL #ifdef TCP_FASTOPEN Log::log(" [Enabled] TCP_FASTOPEN Support", Log::FATAL); #else // TCP_FASTOPEN Log::log("[Disabled] TCP_FASTOPEN Support", Log::FATAL); #endif // TCP_FASTOPEN #ifdef TCP_FASTOPEN_CONNECT Log::log(" [Enabled] TCP_FASTOPEN_CONNECT Support", Log::FATAL); #else // TCP_FASTOPEN_CONNECT Log::log("[Disabled] TCP_FASTOPEN_CONNECT Support", Log::FATAL); #endif // TCP_FASTOPEN_CONNECT #if ENABLE_SSL_KEYLOG Log::log(" [Enabled] SSL KeyLog Support", Log::FATAL); #else // ENABLE_SSL_KEYLOG Log::log("[Disabled] SSL KeyLog Support", Log::FATAL); #endif // ENABLE_SSL_KEYLOG #ifdef ENABLE_NAT Log::log(" [Enabled] NAT Support", Log::FATAL); #else // ENABLE_NAT Log::log("[Disabled] NAT Support", Log::FATAL); #endif // ENABLE_NAT #ifdef ENABLE_TLS13_CIPHERSUITES Log::log(" [Enabled] TLS1.3 Ciphersuites Support", Log::FATAL); #else // ENABLE_TLS13_CIPHERSUITES Log::log("[Disabled] TLS1.3 Ciphersuites Support", Log::FATAL); #endif // ENABLE_TLS13_CIPHERSUITES #ifdef ENABLE_REUSE_PORT Log::log(" [Enabled] TCP Port Reuse Support", Log::FATAL); #else // ENABLE_REUSE_PORT Log::log("[Disabled] TCP Port Reuse Support", Log::FATAL); #endif // ENABLE_REUSE_PORT Log::log("OpenSSL Information", Log::FATAL); if (OpenSSL_version_num() != OPENSSL_VERSION_NUMBER) { Log::log(string("\tCompile-time Version: ") + OPENSSL_VERSION_TEXT, Log::FATAL); } Log::log(string("\tBuild Flags: ") + OpenSSL_version(OPENSSL_CFLAGS), Log::FATAL); exit(EXIT_SUCCESS); } if (vm.count("log")) { Log::redirect(log_file); } if (vm.count("keylog")) { Log::redirect_keylog(keylog_file); } bool restart; Config config; do { restart = false; if (config.sip003()) { Log::log_with_date_time("SIP003 is loaded", Log::WARN); } else { config.load(config_file); } Service service(config, test); if (test) { Log::log("The config file looks good.", Log::OFF); exit(EXIT_SUCCESS); } signal_set sig(service.service()); sig.add(SIGINT); sig.add(SIGTERM); #ifndef _WIN32 sig.add(SIGHUP); sig.add(SIGUSR1); #endif // _WIN32 signal_async_wait(sig, service, restart); service.run(); if (restart) { Log::log_with_date_time("trojan service restarting. . . ", Log::WARN); } } while (restart); Log::reset(); exit(EXIT_SUCCESS); } catch (const exception &e) { Log::log_with_date_time(string("fatal: ") + e.what(), Log::FATAL); Log::log_with_date_time("exiting. . . ", Log::FATAL); exit(EXIT_FAILURE); } }
6,669
C++
.cpp
170
31.352941
133
0.595381
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,918
clientsession.cpp
trojan-gfw_trojan/src/session/clientsession.cpp
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "clientsession.h" #include "proto/trojanrequest.h" #include "proto/udppacket.h" #include "ssl/sslsession.h" using namespace std; using namespace boost::asio::ip; using namespace boost::asio::ssl; ClientSession::ClientSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context) : Session(config, io_context), status(HANDSHAKE), first_packet_recv(false), in_socket(io_context), out_socket(io_context, ssl_context) {} tcp::socket& ClientSession::accept_socket() { return in_socket; } void ClientSession::start() { boost::system::error_code ec; start_time = time(nullptr); in_endpoint = in_socket.remote_endpoint(ec); if (ec) { destroy(); return; } auto ssl = out_socket.native_handle(); if (!config.ssl.sni.empty()) { SSL_set_tlsext_host_name(ssl, config.ssl.sni.c_str()); } if (config.ssl.reuse_session) { SSL_SESSION *session = SSLSession::get_session(); if (session) { SSL_set_session(ssl, session); } } in_async_read(); } void ClientSession::in_async_read() { auto self = shared_from_this(); in_socket.async_read_some(boost::asio::buffer(in_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error == boost::asio::error::operation_aborted) { return; } if (error) { destroy(); return; } in_recv(string((const char*)in_read_buf, length)); }); } void ClientSession::in_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared<string>(data); boost::asio::async_write(in_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } in_sent(); }); } void ClientSession::out_async_read() { auto self = shared_from_this(); out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error) { destroy(); return; } out_recv(string((const char*)out_read_buf, length)); }); } void ClientSession::out_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared<string>(data); boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } out_sent(); }); } void ClientSession::udp_async_read() { auto self = shared_from_this(); udp_socket.async_receive_from(boost::asio::buffer(udp_read_buf, MAX_LENGTH), udp_recv_endpoint, [this, self](const boost::system::error_code error, size_t length) { if (error == boost::asio::error::operation_aborted) { return; } if (error) { destroy(); return; } udp_recv(string((const char*)udp_read_buf, length), udp_recv_endpoint); }); } void ClientSession::udp_async_write(const string &data, const udp::endpoint &endpoint) { auto self = shared_from_this(); auto data_copy = make_shared<string>(data); udp_socket.async_send_to(boost::asio::buffer(*data_copy), endpoint, [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } udp_sent(); }); } void ClientSession::in_recv(const string &data) { switch (status) { case HANDSHAKE: { if (data.length() < 2 || data[0] != 5 || data.length() != (unsigned int)(unsigned char)data[1] + 2) { Log::log_with_endpoint(in_endpoint, "unknown protocol", Log::ERROR); destroy(); return; } bool has_method = false; for (int i = 2; i < data[1] + 2; ++i) { if (data[i] == 0) { has_method = true; break; } } if (!has_method) { Log::log_with_endpoint(in_endpoint, "unsupported auth method", Log::ERROR); in_async_write(string("\x05\xff", 2)); status = INVALID; return; } in_async_write(string("\x05\x00", 2)); break; } case REQUEST: { if (data.length() < 7 || data[0] != 5 || data[2] != 0) { Log::log_with_endpoint(in_endpoint, "bad request", Log::ERROR); destroy(); return; } out_write_buf = config.password.cbegin()->first + "\r\n" + data[1] + data.substr(3) + "\r\n"; TrojanRequest req; if (req.parse(out_write_buf) == -1) { Log::log_with_endpoint(in_endpoint, "unsupported command", Log::ERROR); in_async_write(string("\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00", 10)); status = INVALID; return; } is_udp = req.command == TrojanRequest::UDP_ASSOCIATE; if (is_udp) { udp::endpoint bindpoint(in_socket.local_endpoint().address(), 0); boost::system::error_code ec; udp_socket.open(bindpoint.protocol(), ec); if (ec) { destroy(); return; } udp_socket.bind(bindpoint); Log::log_with_endpoint(in_endpoint, "requested UDP associate to " + req.address.address + ':' + to_string(req.address.port) + ", open UDP socket " + udp_socket.local_endpoint().address().to_string() + ':' + to_string(udp_socket.local_endpoint().port()) + " for relay", Log::INFO); in_async_write(string("\x05\x00\x00", 3) + SOCKS5Address::generate(udp_socket.local_endpoint())); } else { Log::log_with_endpoint(in_endpoint, "requested connection to " + req.address.address + ':' + to_string(req.address.port), Log::INFO); in_async_write(string("\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00", 10)); } break; } case CONNECT: { sent_len += data.length(); first_packet_recv = true; out_write_buf += data; break; } case FORWARD: { sent_len += data.length(); out_async_write(data); break; } case UDP_FORWARD: { Log::log_with_endpoint(in_endpoint, "unexpected data from TCP port", Log::ERROR); destroy(); break; } default: break; } } void ClientSession::in_sent() { switch (status) { case HANDSHAKE: { status = REQUEST; in_async_read(); break; } case REQUEST: { status = CONNECT; in_async_read(); if (is_udp) { udp_async_read(); } auto self = shared_from_this(); resolver.async_resolve(config.remote_addr, to_string(config.remote_port), [this, self](const boost::system::error_code error, const tcp::resolver::results_type& results) { if (error || results.empty()) { Log::log_with_endpoint(in_endpoint, "cannot resolve remote server hostname " + config.remote_addr + ": " + error.message(), Log::ERROR); destroy(); return; } auto iterator = results.begin(); Log::log_with_endpoint(in_endpoint, config.remote_addr + " is resolved to " + iterator->endpoint().address().to_string(), Log::ALL); boost::system::error_code ec; out_socket.next_layer().open(iterator->endpoint().protocol(), ec); if (ec) { destroy(); return; } if (config.tcp.no_delay) { out_socket.next_layer().set_option(tcp::no_delay(true)); } if (config.tcp.keep_alive) { out_socket.next_layer().set_option(boost::asio::socket_base::keep_alive(true)); } #ifdef TCP_FASTOPEN_CONNECT if (config.tcp.fast_open) { using fastopen_connect = boost::asio::detail::socket_option::boolean<IPPROTO_TCP, TCP_FASTOPEN_CONNECT>; boost::system::error_code ec; out_socket.next_layer().set_option(fastopen_connect(true), ec); } #endif // TCP_FASTOPEN_CONNECT out_socket.next_layer().async_connect(*iterator, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot establish connection to remote server " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } out_socket.async_handshake(stream_base::client, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "SSL handshake failed with " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } Log::log_with_endpoint(in_endpoint, "tunnel established"); if (config.ssl.reuse_session) { auto ssl = out_socket.native_handle(); if (!SSL_session_reused(ssl)) { Log::log_with_endpoint(in_endpoint, "SSL session not reused"); } else { Log::log_with_endpoint(in_endpoint, "SSL session reused"); } } boost::system::error_code ec; if (is_udp) { if (!first_packet_recv) { udp_socket.cancel(ec); } status = UDP_FORWARD; } else { if (!first_packet_recv) { in_socket.cancel(ec); } status = FORWARD; } out_async_read(); out_async_write(out_write_buf); }); }); }); break; } case FORWARD: { out_async_read(); break; } case INVALID: { destroy(); break; } default: break; } } void ClientSession::out_recv(const string &data) { if (status == FORWARD) { recv_len += data.length(); in_async_write(data); } else if (status == UDP_FORWARD) { udp_data_buf += data; udp_sent(); } } void ClientSession::out_sent() { if (status == FORWARD) { in_async_read(); } else if (status == UDP_FORWARD) { udp_async_read(); } } void ClientSession::udp_recv(const string &data, const udp::endpoint&) { if (data.length() == 0) { return; } if (data.length() < 3 || data[0] || data[1] || data[2]) { Log::log_with_endpoint(in_endpoint, "bad UDP packet", Log::ERROR); destroy(); return; } SOCKS5Address address; size_t address_len; bool is_addr_valid = address.parse(data.substr(3), address_len); if (!is_addr_valid) { Log::log_with_endpoint(in_endpoint, "bad UDP packet", Log::ERROR); destroy(); return; } size_t length = data.length() - 3 - address_len; Log::log_with_endpoint(in_endpoint, "sent a UDP packet of length " + to_string(length) + " bytes to " + address.address + ':' + to_string(address.port)); string packet = data.substr(3, address_len) + char(uint8_t(length >> 8)) + char(uint8_t(length & 0xFF)) + "\r\n" + data.substr(address_len + 3); sent_len += length; if (status == CONNECT) { first_packet_recv = true; out_write_buf += packet; } else if (status == UDP_FORWARD) { out_async_write(packet); } } void ClientSession::udp_sent() { if (status == UDP_FORWARD) { UDPPacket packet; size_t packet_len; bool is_packet_valid = packet.parse(udp_data_buf, packet_len); if (!is_packet_valid) { if (udp_data_buf.length() > MAX_LENGTH) { Log::log_with_endpoint(in_endpoint, "UDP packet too long", Log::ERROR); destroy(); return; } out_async_read(); return; } Log::log_with_endpoint(in_endpoint, "received a UDP packet of length " + to_string(packet.length) + " bytes from " + packet.address.address + ':' + to_string(packet.address.port)); SOCKS5Address address; size_t address_len; bool is_addr_valid = address.parse(udp_data_buf, address_len); if (!is_addr_valid) { Log::log_with_endpoint(in_endpoint, "udp_sent: invalid UDP packet address", Log::ERROR); destroy(); return; } string reply = string("\x00\x00\x00", 3) + udp_data_buf.substr(0, address_len) + packet.payload; udp_data_buf = udp_data_buf.substr(packet_len); recv_len += packet.length; udp_async_write(reply, udp_recv_endpoint); } } void ClientSession::destroy() { if (status == DESTROY) { return; } status = DESTROY; Log::log_with_endpoint(in_endpoint, "disconnected, " + to_string(recv_len) + " bytes received, " + to_string(sent_len) + " bytes sent, lasted for " + to_string(time(nullptr) - start_time) + " seconds", Log::INFO); boost::system::error_code ec; resolver.cancel(); if (in_socket.is_open()) { in_socket.cancel(ec); in_socket.shutdown(tcp::socket::shutdown_both, ec); in_socket.close(ec); } if (udp_socket.is_open()) { udp_socket.cancel(ec); udp_socket.close(ec); } if (out_socket.next_layer().is_open()) { auto self = shared_from_this(); auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) { if (error == boost::asio::error::operation_aborted) { return; } boost::system::error_code ec; ssl_shutdown_timer.cancel(); out_socket.next_layer().cancel(ec); out_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec); out_socket.next_layer().close(ec); }; out_socket.next_layer().cancel(ec); out_socket.async_shutdown(ssl_shutdown_cb); ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT)); ssl_shutdown_timer.async_wait(ssl_shutdown_cb); } }
16,158
C++
.cpp
398
29.773869
296
0.541193
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,919
udpforwardsession.cpp
trojan-gfw_trojan/src/session/udpforwardsession.cpp
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "udpforwardsession.h" #include <stdexcept> #include <utility> #include "ssl/sslsession.h" #include "proto/trojanrequest.h" #include "proto/udppacket.h" using namespace std; using namespace boost::asio::ip; using namespace boost::asio::ssl; UDPForwardSession::UDPForwardSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context, const udp::endpoint &endpoint, UDPWrite in_write) : Session(config, io_context), status(CONNECT), in_write(move(in_write)), out_socket(io_context, ssl_context), gc_timer(io_context) { udp_recv_endpoint = endpoint; in_endpoint = tcp::endpoint(endpoint.address(), endpoint.port()); } tcp::socket& UDPForwardSession::accept_socket() { throw logic_error("accept_socket does not exist in UDPForwardSession"); } void UDPForwardSession::start() { timer_async_wait(); start_time = time(nullptr); auto ssl = out_socket.native_handle(); if (!config.ssl.sni.empty()) { SSL_set_tlsext_host_name(ssl, config.ssl.sni.c_str()); } if (config.ssl.reuse_session) { SSL_SESSION *session = SSLSession::get_session(); if (session) { SSL_set_session(ssl, session); } } out_write_buf = TrojanRequest::generate(config.password.cbegin()->first, config.target_addr, config.target_port, false); Log::log_with_endpoint(in_endpoint, "forwarding UDP packets to " + config.target_addr + ':' + to_string(config.target_port) + " via " + config.remote_addr + ':' + to_string(config.remote_port), Log::INFO); auto self = shared_from_this(); resolver.async_resolve(config.remote_addr, to_string(config.remote_port), [this, self](const boost::system::error_code error, const tcp::resolver::results_type& results) { if (error || results.empty()) { Log::log_with_endpoint(in_endpoint, "cannot resolve remote server hostname " + config.remote_addr + ": " + error.message(), Log::ERROR); destroy(); return; } auto iterator = results.begin(); Log::log_with_endpoint(in_endpoint, config.remote_addr + " is resolved to " + iterator->endpoint().address().to_string(), Log::ALL); boost::system::error_code ec; out_socket.next_layer().open(iterator->endpoint().protocol(), ec); if (ec) { destroy(); return; } if (config.tcp.no_delay) { out_socket.next_layer().set_option(tcp::no_delay(true)); } if (config.tcp.keep_alive) { out_socket.next_layer().set_option(boost::asio::socket_base::keep_alive(true)); } #ifdef TCP_FASTOPEN_CONNECT if (config.tcp.fast_open) { using fastopen_connect = boost::asio::detail::socket_option::boolean<IPPROTO_TCP, TCP_FASTOPEN_CONNECT>; boost::system::error_code ec; out_socket.next_layer().set_option(fastopen_connect(true), ec); } #endif // TCP_FASTOPEN_CONNECT out_socket.next_layer().async_connect(*iterator, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot establish connection to remote server " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } out_socket.async_handshake(stream_base::client, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "SSL handshake failed with " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } Log::log_with_endpoint(in_endpoint, "tunnel established"); if (config.ssl.reuse_session) { auto ssl = out_socket.native_handle(); if (!SSL_session_reused(ssl)) { Log::log_with_endpoint(in_endpoint, "SSL session not reused"); } else { Log::log_with_endpoint(in_endpoint, "SSL session reused"); } } status = FORWARDING; out_async_read(); out_async_write(out_write_buf); out_write_buf.clear(); }); }); }); } bool UDPForwardSession::process(const udp::endpoint &endpoint, const string &data) { if (endpoint != udp_recv_endpoint) { return false; } in_recv(data); return true; } void UDPForwardSession::out_async_read() { auto self = shared_from_this(); out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error) { destroy(); return; } out_recv(string((const char*)out_read_buf, length)); }); } void UDPForwardSession::out_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared<string>(data); boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } out_sent(); }); } void UDPForwardSession::timer_async_wait() { gc_timer.expires_after(chrono::seconds(config.udp_timeout)); auto self = shared_from_this(); gc_timer.async_wait([this, self](const boost::system::error_code error) { if (!error) { Log::log_with_endpoint(in_endpoint, "UDP session timeout"); destroy(); } }); } void UDPForwardSession::in_recv(const string &data) { if (status == DESTROY) { return; } gc_timer.cancel(); timer_async_wait(); string packet = UDPPacket::generate(config.target_addr, config.target_port, data); size_t length = data.length(); Log::log_with_endpoint(in_endpoint, "sent a UDP packet of length " + to_string(length) + " bytes to " + config.target_addr + ':' + to_string(config.target_port)); sent_len += length; if (status == FORWARD) { status = FORWARDING; out_async_write(packet); } else { out_write_buf += packet; } } void UDPForwardSession::out_recv(const string &data) { if (status == FORWARD || status == FORWARDING) { gc_timer.cancel(); timer_async_wait(); udp_data_buf += data; for (;;) { UDPPacket packet; size_t packet_len; bool is_packet_valid = packet.parse(udp_data_buf, packet_len); if (!is_packet_valid) { if (udp_data_buf.length() > MAX_LENGTH) { Log::log_with_endpoint(in_endpoint, "UDP packet too long", Log::ERROR); destroy(); return; } break; } Log::log_with_endpoint(in_endpoint, "received a UDP packet of length " + to_string(packet.length) + " bytes from " + packet.address.address + ':' + to_string(packet.address.port)); udp_data_buf = udp_data_buf.substr(packet_len); recv_len += packet.length; in_write(udp_recv_endpoint, packet.payload); } out_async_read(); } } void UDPForwardSession::out_sent() { if (status == FORWARDING) { if (out_write_buf.length() == 0) { status = FORWARD; } else { out_async_write(out_write_buf); out_write_buf.clear(); } } } void UDPForwardSession::destroy() { if (status == DESTROY) { return; } status = DESTROY; Log::log_with_endpoint(in_endpoint, "disconnected, " + to_string(recv_len) + " bytes received, " + to_string(sent_len) + " bytes sent, lasted for " + to_string(time(nullptr) - start_time) + " seconds", Log::INFO); resolver.cancel(); gc_timer.cancel(); if (out_socket.next_layer().is_open()) { auto self = shared_from_this(); auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) { if (error == boost::asio::error::operation_aborted) { return; } boost::system::error_code ec; ssl_shutdown_timer.cancel(); out_socket.next_layer().cancel(ec); out_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec); out_socket.next_layer().close(ec); }; boost::system::error_code ec; out_socket.next_layer().cancel(ec); out_socket.async_shutdown(ssl_shutdown_cb); ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT)); ssl_shutdown_timer.async_wait(ssl_shutdown_cb); } }
9,686
C++
.cpp
229
34.078603
217
0.607941
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,920
session.cpp
trojan-gfw_trojan/src/session/session.cpp
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "session.h" Session::Session(const Config &config, boost::asio::io_context &io_context) : config(config), recv_len(0), sent_len(0), resolver(io_context), udp_socket(io_context), ssl_shutdown_timer(io_context) {} Session::~Session() = default;
1,461
C++
.cpp
26
39.423077
111
0.550279
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,921
natsession.cpp
trojan-gfw_trojan/src/session/natsession.cpp
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "natsession.h" #include "proto/trojanrequest.h" #include "ssl/sslsession.h" using namespace std; using namespace boost::asio::ip; using namespace boost::asio::ssl; // These 2 definitions are respectively from linux/netfilter_ipv4.h and // linux/netfilter_ipv6/ip6_tables.h. Including them will 1) cause linux-headers // to be one of trojan's dependencies, which is not good, and 2) prevent trojan // from even compiling. #ifndef SO_ORIGINAL_DST #define SO_ORIGINAL_DST 80 #endif // SO_ORIGINAL_DST #ifndef IP6T_SO_ORIGINAL_DST #define IP6T_SO_ORIGINAL_DST 80 #endif // IP6T_SO_ORIGINAL_DST NATSession::NATSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context) : Session(config, io_context), status(CONNECT), first_packet_recv(false), in_socket(io_context), out_socket(io_context, ssl_context) {} tcp::socket& NATSession::accept_socket() { return in_socket; } pair<string, uint16_t> NATSession::get_target_endpoint() { #ifdef ENABLE_NAT int fd = in_socket.native_handle(); // Taken from https://github.com/shadowsocks/shadowsocks-libev/blob/v3.3.1/src/redir.c. sockaddr_storage destaddr; memset(&destaddr, 0, sizeof(sockaddr_storage)); socklen_t socklen = sizeof(destaddr); int error = getsockopt(fd, SOL_IPV6, IP6T_SO_ORIGINAL_DST, &destaddr, &socklen); if (error) { error = getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, &destaddr, &socklen); if (error) { return make_pair("", 0); } } char ipstr[INET6_ADDRSTRLEN]; uint16_t port; if (destaddr.ss_family == AF_INET) { auto *sa = (sockaddr_in*) &destaddr; inet_ntop(AF_INET, &(sa->sin_addr), ipstr, INET_ADDRSTRLEN); port = ntohs(sa->sin_port); } else { auto *sa = (sockaddr_in6*) &destaddr; inet_ntop(AF_INET6, &(sa->sin6_addr), ipstr, INET6_ADDRSTRLEN); port = ntohs(sa->sin6_port); } return make_pair(ipstr, port); #else // ENABLE_NAT return make_pair("", 0); #endif // ENABLE_NAT } void NATSession::start() { boost::system::error_code ec; start_time = time(nullptr); in_endpoint = in_socket.remote_endpoint(ec); if (ec) { destroy(); return; } auto ssl = out_socket.native_handle(); if (!config.ssl.sni.empty()) { SSL_set_tlsext_host_name(ssl, config.ssl.sni.c_str()); } if (config.ssl.reuse_session) { SSL_SESSION *session = SSLSession::get_session(); if (session) { SSL_set_session(ssl, session); } } auto target_endpoint = get_target_endpoint(); string &target_addr = target_endpoint.first; uint16_t target_port = target_endpoint.second; if (target_port == 0) { destroy(); return; } out_write_buf = TrojanRequest::generate(config.password.cbegin()->first, target_addr, target_port, true); in_async_read(); Log::log_with_endpoint(in_endpoint, "forwarding to " + target_addr + ':' + to_string(target_port) + " via " + config.remote_addr + ':' + to_string(config.remote_port), Log::INFO); auto self = shared_from_this(); resolver.async_resolve(config.remote_addr, to_string(config.remote_port), [this, self](const boost::system::error_code error, const tcp::resolver::results_type& results) { if (error || results.empty()) { Log::log_with_endpoint(in_endpoint, "cannot resolve remote server hostname " + config.remote_addr + ": " + error.message(), Log::ERROR); destroy(); return; } auto iterator = results.begin(); Log::log_with_endpoint(in_endpoint, config.remote_addr + " is resolved to " + iterator->endpoint().address().to_string(), Log::ALL); boost::system::error_code ec; out_socket.next_layer().open(iterator->endpoint().protocol(), ec); if (ec) { destroy(); return; } if (config.tcp.no_delay) { out_socket.next_layer().set_option(tcp::no_delay(true)); } if (config.tcp.keep_alive) { out_socket.next_layer().set_option(boost::asio::socket_base::keep_alive(true)); } #ifdef TCP_FASTOPEN_CONNECT if (config.tcp.fast_open) { using fastopen_connect = boost::asio::detail::socket_option::boolean<IPPROTO_TCP, TCP_FASTOPEN_CONNECT>; boost::system::error_code ec; out_socket.next_layer().set_option(fastopen_connect(true), ec); } #endif // TCP_FASTOPEN_CONNECT out_socket.next_layer().async_connect(*iterator, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot establish connection to remote server " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } out_socket.async_handshake(stream_base::client, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "SSL handshake failed with " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } Log::log_with_endpoint(in_endpoint, "tunnel established"); if (config.ssl.reuse_session) { auto ssl = out_socket.native_handle(); if (!SSL_session_reused(ssl)) { Log::log_with_endpoint(in_endpoint, "SSL session not reused"); } else { Log::log_with_endpoint(in_endpoint, "SSL session reused"); } } boost::system::error_code ec; if (!first_packet_recv) { in_socket.cancel(ec); } status = FORWARD; out_async_read(); out_async_write(out_write_buf); }); }); }); } void NATSession::in_async_read() { auto self = shared_from_this(); in_socket.async_read_some(boost::asio::buffer(in_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error == boost::asio::error::operation_aborted) { return; } if (error) { destroy(); return; } in_recv(string((const char*)in_read_buf, length)); }); } void NATSession::in_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared<string>(data); boost::asio::async_write(in_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } in_sent(); }); } void NATSession::out_async_read() { auto self = shared_from_this(); out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error) { destroy(); return; } out_recv(string((const char*)out_read_buf, length)); }); } void NATSession::out_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared<string>(data); boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } out_sent(); }); } void NATSession::in_recv(const string &data) { if (status == CONNECT) { sent_len += data.length(); first_packet_recv = true; out_write_buf += data; } else if (status == FORWARD) { sent_len += data.length(); out_async_write(data); } } void NATSession::in_sent() { if (status == FORWARD) { out_async_read(); } } void NATSession::out_recv(const string &data) { if (status == FORWARD) { recv_len += data.length(); in_async_write(data); } } void NATSession::out_sent() { if (status == FORWARD) { in_async_read(); } } void NATSession::destroy() { if (status == DESTROY) { return; } status = DESTROY; Log::log_with_endpoint(in_endpoint, "disconnected, " + to_string(recv_len) + " bytes received, " + to_string(sent_len) + " bytes sent, lasted for " + to_string(time(nullptr) - start_time) + " seconds", Log::INFO); boost::system::error_code ec; resolver.cancel(); if (in_socket.is_open()) { in_socket.cancel(ec); in_socket.shutdown(tcp::socket::shutdown_both, ec); in_socket.close(ec); } if (out_socket.next_layer().is_open()) { auto self = shared_from_this(); auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) { if (error == boost::asio::error::operation_aborted) { return; } boost::system::error_code ec; ssl_shutdown_timer.cancel(); out_socket.next_layer().cancel(ec); out_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec); out_socket.next_layer().close(ec); }; out_socket.next_layer().cancel(ec); out_socket.async_shutdown(ssl_shutdown_cb); ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT)); ssl_shutdown_timer.async_wait(ssl_shutdown_cb); } }
10,441
C++
.cpp
263
32.235741
217
0.609564
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,922
serversession.cpp
trojan-gfw_trojan/src/session/serversession.cpp
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "serversession.h" #include "proto/trojanrequest.h" #include "proto/udppacket.h" using namespace std; using namespace boost::asio::ip; using namespace boost::asio::ssl; ServerSession::ServerSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context, Authenticator *auth, const string &plain_http_response) : Session(config, io_context), status(HANDSHAKE), in_socket(io_context, ssl_context), out_socket(io_context), udp_resolver(io_context), auth(auth), plain_http_response(plain_http_response) {} tcp::socket& ServerSession::accept_socket() { return (tcp::socket&)in_socket.next_layer(); } void ServerSession::start() { boost::system::error_code ec; start_time = time(nullptr); in_endpoint = in_socket.next_layer().remote_endpoint(ec); if (ec) { destroy(); return; } auto self = shared_from_this(); in_socket.async_handshake(stream_base::server, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "SSL handshake failed: " + error.message(), Log::ERROR); if (error.message() == "http request" && !plain_http_response.empty()) { recv_len += plain_http_response.length(); boost::asio::async_write(accept_socket(), boost::asio::buffer(plain_http_response), [this, self](const boost::system::error_code, size_t) { destroy(); }); return; } destroy(); return; } in_async_read(); }); } void ServerSession::in_async_read() { auto self = shared_from_this(); in_socket.async_read_some(boost::asio::buffer(in_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error) { destroy(); return; } in_recv(string((const char*)in_read_buf, length)); }); } void ServerSession::in_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared<string>(data); boost::asio::async_write(in_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } in_sent(); }); } void ServerSession::out_async_read() { auto self = shared_from_this(); out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error) { destroy(); return; } out_recv(string((const char*)out_read_buf, length)); }); } void ServerSession::out_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared<string>(data); boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } out_sent(); }); } void ServerSession::udp_async_read() { auto self = shared_from_this(); udp_socket.async_receive_from(boost::asio::buffer(udp_read_buf, MAX_LENGTH), udp_recv_endpoint, [this, self](const boost::system::error_code error, size_t length) { if (error) { destroy(); return; } udp_recv(string((const char*)udp_read_buf, length), udp_recv_endpoint); }); } void ServerSession::udp_async_write(const string &data, const udp::endpoint &endpoint) { auto self = shared_from_this(); auto data_copy = make_shared<string>(data); udp_socket.async_send_to(boost::asio::buffer(*data_copy), endpoint, [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } udp_sent(); }); } void ServerSession::in_recv(const string &data) { if (status == HANDSHAKE) { TrojanRequest req; bool valid = req.parse(data) != -1; if (valid) { auto password_iterator = config.password.find(req.password); if (password_iterator == config.password.end()) { valid = false; if (auth && auth->auth(req.password)) { valid = true; auth_password = req.password; Log::log_with_endpoint(in_endpoint, "authenticated by authenticator (" + req.password.substr(0, 7) + ')', Log::INFO); } } else { Log::log_with_endpoint(in_endpoint, "authenticated as " + password_iterator->second, Log::INFO); } if (!valid) { Log::log_with_endpoint(in_endpoint, "valid trojan request structure but possibly incorrect password (" + req.password + ')', Log::WARN); } } string query_addr = valid ? req.address.address : config.remote_addr; string query_port = to_string([&]() { if (valid) { return req.address.port; } const unsigned char *alpn_out; unsigned int alpn_len; SSL_get0_alpn_selected(in_socket.native_handle(), &alpn_out, &alpn_len); if (alpn_out == nullptr) { return config.remote_port; } auto it = config.ssl.alpn_port_override.find(string(alpn_out, alpn_out + alpn_len)); return it == config.ssl.alpn_port_override.end() ? config.remote_port : it->second; }()); if (valid) { out_write_buf = req.payload; if (req.command == TrojanRequest::UDP_ASSOCIATE) { Log::log_with_endpoint(in_endpoint, "requested UDP associate to " + req.address.address + ':' + to_string(req.address.port), Log::INFO); status = UDP_FORWARD; udp_data_buf = out_write_buf; udp_sent(); return; } else { Log::log_with_endpoint(in_endpoint, "requested connection to " + req.address.address + ':' + to_string(req.address.port), Log::INFO); } } else { Log::log_with_endpoint(in_endpoint, "not trojan request, connecting to " + query_addr + ':' + query_port, Log::WARN); out_write_buf = data; } sent_len += out_write_buf.length(); auto self = shared_from_this(); resolver.async_resolve(query_addr, query_port, [this, self, query_addr, query_port](const boost::system::error_code error, const tcp::resolver::results_type& results) { if (error || results.empty()) { Log::log_with_endpoint(in_endpoint, "cannot resolve remote server hostname " + query_addr + ": " + error.message(), Log::ERROR); destroy(); return; } auto iterator = results.begin(); if (config.tcp.prefer_ipv4) { for (auto it = results.begin(); it != results.end(); ++it) { const auto &addr = it->endpoint().address(); if (addr.is_v4()) { iterator = it; break; } } } Log::log_with_endpoint(in_endpoint, query_addr + " is resolved to " + iterator->endpoint().address().to_string(), Log::ALL); boost::system::error_code ec; out_socket.open(iterator->endpoint().protocol(), ec); if (ec) { destroy(); return; } if (config.tcp.no_delay) { out_socket.set_option(tcp::no_delay(true)); } if (config.tcp.keep_alive) { out_socket.set_option(boost::asio::socket_base::keep_alive(true)); } #ifdef TCP_FASTOPEN_CONNECT if (config.tcp.fast_open) { using fastopen_connect = boost::asio::detail::socket_option::boolean<IPPROTO_TCP, TCP_FASTOPEN_CONNECT>; boost::system::error_code ec; out_socket.set_option(fastopen_connect(true), ec); } #endif // TCP_FASTOPEN_CONNECT out_socket.async_connect(*iterator, [this, self, query_addr, query_port](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot establish connection to remote server " + query_addr + ':' + query_port + ": " + error.message(), Log::ERROR); destroy(); return; } Log::log_with_endpoint(in_endpoint, "tunnel established"); status = FORWARD; out_async_read(); if (!out_write_buf.empty()) { out_async_write(out_write_buf); } else { in_async_read(); } }); }); } else if (status == FORWARD) { sent_len += data.length(); out_async_write(data); } else if (status == UDP_FORWARD) { udp_data_buf += data; udp_sent(); } } void ServerSession::in_sent() { if (status == FORWARD) { out_async_read(); } else if (status == UDP_FORWARD) { udp_async_read(); } } void ServerSession::out_recv(const string &data) { if (status == FORWARD) { recv_len += data.length(); in_async_write(data); } } void ServerSession::out_sent() { if (status == FORWARD) { in_async_read(); } } void ServerSession::udp_recv(const string &data, const udp::endpoint &endpoint) { if (status == UDP_FORWARD) { size_t length = data.length(); Log::log_with_endpoint(in_endpoint, "received a UDP packet of length " + to_string(length) + " bytes from " + endpoint.address().to_string() + ':' + to_string(endpoint.port())); recv_len += length; in_async_write(UDPPacket::generate(endpoint, data)); } } void ServerSession::udp_sent() { if (status == UDP_FORWARD) { UDPPacket packet; size_t packet_len; bool is_packet_valid = packet.parse(udp_data_buf, packet_len); if (!is_packet_valid) { if (udp_data_buf.length() > MAX_LENGTH) { Log::log_with_endpoint(in_endpoint, "UDP packet too long", Log::ERROR); destroy(); return; } in_async_read(); return; } Log::log_with_endpoint(in_endpoint, "sent a UDP packet of length " + to_string(packet.length) + " bytes to " + packet.address.address + ':' + to_string(packet.address.port)); udp_data_buf = udp_data_buf.substr(packet_len); string query_addr = packet.address.address; auto self = shared_from_this(); udp_resolver.async_resolve(query_addr, to_string(packet.address.port), [this, self, packet, query_addr](const boost::system::error_code error, const udp::resolver::results_type& results) { if (error || results.empty()) { Log::log_with_endpoint(in_endpoint, "cannot resolve remote server hostname " + query_addr + ": " + error.message(), Log::ERROR); destroy(); return; } auto iterator = results.begin(); if (config.tcp.prefer_ipv4) { for (auto it = results.begin(); it != results.end(); ++it) { const auto &addr = it->endpoint().address(); if (addr.is_v4()) { iterator = it; break; } } } Log::log_with_endpoint(in_endpoint, query_addr + " is resolved to " + iterator->endpoint().address().to_string(), Log::ALL); if (!udp_socket.is_open()) { auto protocol = iterator->endpoint().protocol(); boost::system::error_code ec; udp_socket.open(protocol, ec); if (ec) { destroy(); return; } udp_socket.bind(udp::endpoint(protocol, 0)); udp_async_read(); } sent_len += packet.length; udp_async_write(packet.payload, *iterator); }); } } void ServerSession::destroy() { if (status == DESTROY) { return; } status = DESTROY; Log::log_with_endpoint(in_endpoint, "disconnected, " + to_string(recv_len) + " bytes received, " + to_string(sent_len) + " bytes sent, lasted for " + to_string(time(nullptr) - start_time) + " seconds", Log::INFO); if (auth && !auth_password.empty()) { auth->record(auth_password, recv_len, sent_len); } boost::system::error_code ec; resolver.cancel(); udp_resolver.cancel(); if (out_socket.is_open()) { out_socket.cancel(ec); out_socket.shutdown(tcp::socket::shutdown_both, ec); out_socket.close(ec); } if (udp_socket.is_open()) { udp_socket.cancel(ec); udp_socket.close(ec); } if (in_socket.next_layer().is_open()) { auto self = shared_from_this(); auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) { if (error == boost::asio::error::operation_aborted) { return; } boost::system::error_code ec; ssl_shutdown_timer.cancel(); in_socket.next_layer().cancel(ec); in_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec); in_socket.next_layer().close(ec); }; in_socket.next_layer().cancel(ec); in_socket.async_shutdown(ssl_shutdown_cb); ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT)); ssl_shutdown_timer.async_wait(ssl_shutdown_cb); } }
14,750
C++
.cpp
350
32.257143
217
0.567336
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,923
forwardsession.cpp
trojan-gfw_trojan/src/session/forwardsession.cpp
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "forwardsession.h" #include "proto/trojanrequest.h" #include "ssl/sslsession.h" using namespace std; using namespace boost::asio::ip; using namespace boost::asio::ssl; ForwardSession::ForwardSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context) : Session(config, io_context), status(CONNECT), first_packet_recv(false), in_socket(io_context), out_socket(io_context, ssl_context) {} tcp::socket& ForwardSession::accept_socket() { return in_socket; } void ForwardSession::start() { boost::system::error_code ec; start_time = time(nullptr); in_endpoint = in_socket.remote_endpoint(ec); if (ec) { destroy(); return; } auto ssl = out_socket.native_handle(); if (!config.ssl.sni.empty()) { SSL_set_tlsext_host_name(ssl, config.ssl.sni.c_str()); } if (config.ssl.reuse_session) { SSL_SESSION *session = SSLSession::get_session(); if (session) { SSL_set_session(ssl, session); } } out_write_buf = TrojanRequest::generate(config.password.cbegin()->first, config.target_addr, config.target_port, true); in_async_read(); Log::log_with_endpoint(in_endpoint, "forwarding to " + config.target_addr + ':' + to_string(config.target_port) + " via " + config.remote_addr + ':' + to_string(config.remote_port), Log::INFO); auto self = shared_from_this(); resolver.async_resolve(config.remote_addr, to_string(config.remote_port), [this, self](const boost::system::error_code error, const tcp::resolver::results_type& results) { if (error || results.empty()) { Log::log_with_endpoint(in_endpoint, "cannot resolve remote server hostname " + config.remote_addr + ": " + error.message(), Log::ERROR); destroy(); return; } auto iterator = results.begin(); Log::log_with_endpoint(in_endpoint, config.remote_addr + " is resolved to " + iterator->endpoint().address().to_string(), Log::ALL); boost::system::error_code ec; out_socket.next_layer().open(iterator->endpoint().protocol(), ec); if (ec) { destroy(); return; } if (config.tcp.no_delay) { out_socket.next_layer().set_option(tcp::no_delay(true)); } if (config.tcp.keep_alive) { out_socket.next_layer().set_option(boost::asio::socket_base::keep_alive(true)); } #ifdef TCP_FASTOPEN_CONNECT if (config.tcp.fast_open) { using fastopen_connect = boost::asio::detail::socket_option::boolean<IPPROTO_TCP, TCP_FASTOPEN_CONNECT>; boost::system::error_code ec; out_socket.next_layer().set_option(fastopen_connect(true), ec); } #endif // TCP_FASTOPEN_CONNECT out_socket.next_layer().async_connect(*iterator, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot establish connection to remote server " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } out_socket.async_handshake(stream_base::client, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "SSL handshake failed with " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } Log::log_with_endpoint(in_endpoint, "tunnel established"); if (config.ssl.reuse_session) { auto ssl = out_socket.native_handle(); if (!SSL_session_reused(ssl)) { Log::log_with_endpoint(in_endpoint, "SSL session not reused"); } else { Log::log_with_endpoint(in_endpoint, "SSL session reused"); } } boost::system::error_code ec; if (!first_packet_recv) { in_socket.cancel(ec); } status = FORWARD; out_async_read(); out_async_write(out_write_buf); }); }); }); } void ForwardSession::in_async_read() { auto self = shared_from_this(); in_socket.async_read_some(boost::asio::buffer(in_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error == boost::asio::error::operation_aborted) { return; } if (error) { destroy(); return; } in_recv(string((const char*)in_read_buf, length)); }); } void ForwardSession::in_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared<string>(data); boost::asio::async_write(in_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } in_sent(); }); } void ForwardSession::out_async_read() { auto self = shared_from_this(); out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error) { destroy(); return; } out_recv(string((const char*)out_read_buf, length)); }); } void ForwardSession::out_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared<string>(data); boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } out_sent(); }); } void ForwardSession::in_recv(const string &data) { if (status == CONNECT) { sent_len += data.length(); first_packet_recv = true; out_write_buf += data; } else if (status == FORWARD) { sent_len += data.length(); out_async_write(data); } } void ForwardSession::in_sent() { if (status == FORWARD) { out_async_read(); } } void ForwardSession::out_recv(const string &data) { if (status == FORWARD) { recv_len += data.length(); in_async_write(data); } } void ForwardSession::out_sent() { if (status == FORWARD) { in_async_read(); } } void ForwardSession::destroy() { if (status == DESTROY) { return; } status = DESTROY; Log::log_with_endpoint(in_endpoint, "disconnected, " + to_string(recv_len) + " bytes received, " + to_string(sent_len) + " bytes sent, lasted for " + to_string(time(nullptr) - start_time) + " seconds", Log::INFO); boost::system::error_code ec; resolver.cancel(); if (in_socket.is_open()) { in_socket.cancel(ec); in_socket.shutdown(tcp::socket::shutdown_both, ec); in_socket.close(ec); } if (out_socket.next_layer().is_open()) { auto self = shared_from_this(); auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) { if (error == boost::asio::error::operation_aborted) { return; } boost::system::error_code ec; ssl_shutdown_timer.cancel(); out_socket.next_layer().cancel(ec); out_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec); out_socket.next_layer().close(ec); }; out_socket.next_layer().cancel(ec); out_socket.async_shutdown(ssl_shutdown_cb); ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT)); ssl_shutdown_timer.async_wait(ssl_shutdown_cb); } }
8,765
C++
.cpp
216
32.550926
217
0.602156
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,926
version.cpp
trojan-gfw_trojan/src/core/version.cpp
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "version.h" using namespace std; const string Version::version("1.16.0"); string Version::get_version() { return version; }
956
C++
.cpp
24
37.833333
72
0.756728
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,928
service.cpp
trojan-gfw_trojan/src/core/service.cpp
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "service.h" #include <cstring> #include <cerrno> #include <stdexcept> #include <fstream> #ifdef _WIN32 #include <wincrypt.h> #include <tchar.h> #endif // _WIN32 #ifdef __APPLE__ #include <Security/Security.h> #endif // __APPLE__ #include <openssl/opensslv.h> #include "session/serversession.h" #include "session/clientsession.h" #include "session/forwardsession.h" #include "session/natsession.h" #include "ssl/ssldefaults.h" #include "ssl/sslsession.h" using namespace std; using namespace boost::asio::ip; using namespace boost::asio::ssl; #ifdef ENABLE_REUSE_PORT typedef boost::asio::detail::socket_option::boolean<SOL_SOCKET, SO_REUSEPORT> reuse_port; #endif // ENABLE_REUSE_PORT Service::Service(Config &config, bool test) : config(config), socket_acceptor(io_context), ssl_context(context::sslv23), auth(nullptr), udp_socket(io_context) { #ifndef ENABLE_NAT if (config.run_type == Config::NAT) { throw runtime_error("NAT is not supported"); } #endif // ENABLE_NAT if (!test) { tcp::resolver resolver(io_context); tcp::endpoint listen_endpoint = *resolver.resolve(config.local_addr, to_string(config.local_port)).begin(); socket_acceptor.open(listen_endpoint.protocol()); socket_acceptor.set_option(tcp::acceptor::reuse_address(true)); if (config.tcp.reuse_port) { #ifdef ENABLE_REUSE_PORT socket_acceptor.set_option(reuse_port(true)); #else // ENABLE_REUSE_PORT Log::log_with_date_time("SO_REUSEPORT is not supported", Log::WARN); #endif // ENABLE_REUSE_PORT } socket_acceptor.bind(listen_endpoint); socket_acceptor.listen(); if (config.run_type == Config::FORWARD) { auto udp_bind_endpoint = udp::endpoint(listen_endpoint.address(), listen_endpoint.port()); udp_socket.open(udp_bind_endpoint.protocol()); udp_socket.bind(udp_bind_endpoint); } } Log::level = config.log_level; auto native_context = ssl_context.native_handle(); ssl_context.set_options(context::default_workarounds | context::no_sslv2 | context::no_sslv3 | context::single_dh_use); if (!config.ssl.curves.empty()) { SSL_CTX_set1_curves_list(native_context, config.ssl.curves.c_str()); } if (config.run_type == Config::SERVER) { ssl_context.use_certificate_chain_file(config.ssl.cert); ssl_context.set_password_callback([this](size_t, context_base::password_purpose) { return this->config.ssl.key_password; }); ssl_context.use_private_key_file(config.ssl.key, context::pem); if (config.ssl.prefer_server_cipher) { SSL_CTX_set_options(native_context, SSL_OP_CIPHER_SERVER_PREFERENCE); } if (!config.ssl.alpn.empty()) { SSL_CTX_set_alpn_select_cb(native_context, [](SSL*, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *config) -> int { if (SSL_select_next_proto((unsigned char**)out, outlen, (unsigned char*)(((Config*)config)->ssl.alpn.c_str()), ((Config*)config)->ssl.alpn.length(), in, inlen) != OPENSSL_NPN_NEGOTIATED) { return SSL_TLSEXT_ERR_NOACK; } return SSL_TLSEXT_ERR_OK; }, &config); } if (config.ssl.reuse_session) { SSL_CTX_set_timeout(native_context, config.ssl.session_timeout); if (!config.ssl.session_ticket) { SSL_CTX_set_options(native_context, SSL_OP_NO_TICKET); } } else { SSL_CTX_set_session_cache_mode(native_context, SSL_SESS_CACHE_OFF); SSL_CTX_set_options(native_context, SSL_OP_NO_TICKET); } if (!config.ssl.plain_http_response.empty()) { ifstream ifs(config.ssl.plain_http_response, ios::binary); if (!ifs.is_open()) { throw runtime_error(config.ssl.plain_http_response + ": " + strerror(errno)); } plain_http_response = string(istreambuf_iterator<char>(ifs), istreambuf_iterator<char>()); } if (config.ssl.dhparam.empty()) { ssl_context.use_tmp_dh(boost::asio::const_buffer(SSLDefaults::g_dh2048_sz, SSLDefaults::g_dh2048_sz_size)); } else { ssl_context.use_tmp_dh_file(config.ssl.dhparam); } if (config.mysql.enabled) { #ifdef ENABLE_MYSQL auth = new Authenticator(config); #else // ENABLE_MYSQL Log::log_with_date_time("MySQL is not supported", Log::WARN); #endif // ENABLE_MYSQL } } else { if (config.ssl.sni.empty()) { config.ssl.sni = config.remote_addr; } if (config.ssl.verify) { ssl_context.set_verify_mode(verify_peer); if (config.ssl.cert.empty()) { ssl_context.set_default_verify_paths(); #ifdef _WIN32 HCERTSTORE h_store = CertOpenSystemStore(0, _T("ROOT")); if (h_store) { X509_STORE *store = SSL_CTX_get_cert_store(native_context); PCCERT_CONTEXT p_context = NULL; while ((p_context = CertEnumCertificatesInStore(h_store, p_context))) { const unsigned char *encoded_cert = p_context->pbCertEncoded; X509 *x509 = d2i_X509(NULL, &encoded_cert, p_context->cbCertEncoded); if (x509) { X509_STORE_add_cert(store, x509); X509_free(x509); } } CertCloseStore(h_store, 0); } #endif // _WIN32 #ifdef __APPLE__ SecKeychainSearchRef pSecKeychainSearch = NULL; SecKeychainRef pSecKeychain; OSStatus status = noErr; X509 *cert = NULL; // Leopard and above store location status = SecKeychainOpen ("/System/Library/Keychains/SystemRootCertificates.keychain", &pSecKeychain); if (status == noErr) { X509_STORE *store = SSL_CTX_get_cert_store(native_context); status = SecKeychainSearchCreateFromAttributes (pSecKeychain, kSecCertificateItemClass, NULL, &pSecKeychainSearch); for (;;) { SecKeychainItemRef pSecKeychainItem = nil; status = SecKeychainSearchCopyNext (pSecKeychainSearch, &pSecKeychainItem); if (status == errSecItemNotFound) { break; } if (status == noErr) { void *_pCertData; UInt32 _pCertLength; status = SecKeychainItemCopyAttributesAndData (pSecKeychainItem, NULL, NULL, NULL, &_pCertLength, &_pCertData); if (status == noErr && _pCertData != NULL) { unsigned char *ptr; ptr = (unsigned char *)_pCertData; /*required because d2i_X509 is modifying pointer */ cert = d2i_X509 (NULL, (const unsigned char **) &ptr, _pCertLength); if (cert == NULL) { continue; } if (!X509_STORE_add_cert (store, cert)) { X509_free (cert); continue; } X509_free (cert); status = SecKeychainItemFreeAttributesAndData (NULL, _pCertData); } } if (pSecKeychainItem != NULL) { CFRelease (pSecKeychainItem); } } CFRelease (pSecKeychainSearch); CFRelease (pSecKeychain); } #endif // __APPLE__ } else { ssl_context.load_verify_file(config.ssl.cert); } if (config.ssl.verify_hostname) { #if BOOST_VERSION >= 107300 ssl_context.set_verify_callback(host_name_verification(config.ssl.sni)); #else ssl_context.set_verify_callback(rfc2818_verification(config.ssl.sni)); #endif } X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new(); X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_PARTIAL_CHAIN); SSL_CTX_set1_param(native_context, param); X509_VERIFY_PARAM_free(param); } else { ssl_context.set_verify_mode(verify_none); } if (!config.ssl.alpn.empty()) { SSL_CTX_set_alpn_protos(native_context, (unsigned char*)(config.ssl.alpn.c_str()), config.ssl.alpn.length()); } if (config.ssl.reuse_session) { SSL_CTX_set_session_cache_mode(native_context, SSL_SESS_CACHE_CLIENT); SSLSession::set_callback(native_context); if (!config.ssl.session_ticket) { SSL_CTX_set_options(native_context, SSL_OP_NO_TICKET); } } else { SSL_CTX_set_options(native_context, SSL_OP_NO_TICKET); } } if (!config.ssl.cipher.empty()) { SSL_CTX_set_cipher_list(native_context, config.ssl.cipher.c_str()); } if (!config.ssl.cipher_tls13.empty()) { #ifdef ENABLE_TLS13_CIPHERSUITES SSL_CTX_set_ciphersuites(native_context, config.ssl.cipher_tls13.c_str()); #else // ENABLE_TLS13_CIPHERSUITES Log::log_with_date_time("TLS1.3 ciphersuites are not supported", Log::WARN); #endif // ENABLE_TLS13_CIPHERSUITES } if (!test) { if (config.tcp.no_delay) { socket_acceptor.set_option(tcp::no_delay(true)); } if (config.tcp.keep_alive) { socket_acceptor.set_option(boost::asio::socket_base::keep_alive(true)); } if (config.tcp.fast_open) { #ifdef TCP_FASTOPEN using fastopen = boost::asio::detail::socket_option::integer<IPPROTO_TCP, TCP_FASTOPEN>; boost::system::error_code ec; socket_acceptor.set_option(fastopen(config.tcp.fast_open_qlen), ec); #else // TCP_FASTOPEN Log::log_with_date_time("TCP_FASTOPEN is not supported", Log::WARN); #endif // TCP_FASTOPEN #ifndef TCP_FASTOPEN_CONNECT Log::log_with_date_time("TCP_FASTOPEN_CONNECT is not supported", Log::WARN); #endif // TCP_FASTOPEN_CONNECT } } if (Log::keylog) { #ifdef ENABLE_SSL_KEYLOG SSL_CTX_set_keylog_callback(native_context, [](const SSL*, const char *line) { fprintf(Log::keylog, "%s\n", line); fflush(Log::keylog); }); #else // ENABLE_SSL_KEYLOG Log::log_with_date_time("SSL KeyLog is not supported", Log::WARN); #endif // ENABLE_SSL_KEYLOG } } void Service::run() { async_accept(); if (config.run_type == Config::FORWARD) { udp_async_read(); } tcp::endpoint local_endpoint = socket_acceptor.local_endpoint(); string rt; if (config.run_type == Config::SERVER) { rt = "server"; } else if (config.run_type == Config::FORWARD) { rt = "forward"; } else if (config.run_type == Config::NAT) { rt = "nat"; } else { rt = "client"; } Log::log_with_date_time(string("trojan service (") + rt + ") started at " + local_endpoint.address().to_string() + ':' + to_string(local_endpoint.port()), Log::WARN); io_context.run(); Log::log_with_date_time("trojan service stopped", Log::WARN); } void Service::stop() { boost::system::error_code ec; socket_acceptor.cancel(ec); if (udp_socket.is_open()) { udp_socket.cancel(ec); udp_socket.close(ec); } io_context.stop(); } void Service::async_accept() { shared_ptr<Session>session(nullptr); if (config.run_type == Config::SERVER) { session = make_shared<ServerSession>(config, io_context, ssl_context, auth, plain_http_response); } else if (config.run_type == Config::FORWARD) { session = make_shared<ForwardSession>(config, io_context, ssl_context); } else if (config.run_type == Config::NAT) { session = make_shared<NATSession>(config, io_context, ssl_context); } else { session = make_shared<ClientSession>(config, io_context, ssl_context); } socket_acceptor.async_accept(session->accept_socket(), [this, session](const boost::system::error_code error) { if (error == boost::asio::error::operation_aborted) { // got cancel signal, stop calling myself return; } if (!error) { boost::system::error_code ec; auto endpoint = session->accept_socket().remote_endpoint(ec); if (!ec) { Log::log_with_endpoint(endpoint, "incoming connection"); session->start(); } } async_accept(); }); } void Service::udp_async_read() { udp_socket.async_receive_from(boost::asio::buffer(udp_read_buf, MAX_LENGTH), udp_recv_endpoint, [this](const boost::system::error_code error, size_t length) { if (error == boost::asio::error::operation_aborted) { // got cancel signal, stop calling myself return; } if (error) { stop(); throw runtime_error(error.message()); } string data((const char *)udp_read_buf, length); for (auto it = udp_sessions.begin(); it != udp_sessions.end();) { auto next = ++it; --it; if (it->expired()) { udp_sessions.erase(it); } else if (it->lock()->process(udp_recv_endpoint, data)) { udp_async_read(); return; } it = next; } Log::log_with_endpoint(tcp::endpoint(udp_recv_endpoint.address(), udp_recv_endpoint.port()), "new UDP session"); auto session = make_shared<UDPForwardSession>(config, io_context, ssl_context, udp_recv_endpoint, [this](const udp::endpoint &endpoint, const string &data) { boost::system::error_code ec; udp_socket.send_to(boost::asio::buffer(data), endpoint, 0, ec); if (ec == boost::asio::error::no_permission) { Log::log_with_endpoint(tcp::endpoint(endpoint.address(), endpoint.port()), "dropped a UDP packet due to firewall policy or rate limit"); } else if (ec) { throw runtime_error(ec.message()); } }); udp_sessions.emplace_back(session); session->start(); session->process(udp_recv_endpoint, data); udp_async_read(); }); } boost::asio::io_context &Service::service() { return io_context; } void Service::reload_cert() { if (config.run_type == Config::SERVER) { Log::log_with_date_time("reloading certificate and private key. . . ", Log::WARN); ssl_context.use_certificate_chain_file(config.ssl.cert); ssl_context.use_private_key_file(config.ssl.key, context::pem); boost::system::error_code ec; socket_acceptor.cancel(ec); async_accept(); Log::log_with_date_time("certificate and private key reloaded", Log::WARN); } else { Log::log_with_date_time("cannot reload certificate and private key: wrong run_type", Log::ERROR); } } Service::~Service() { if (auth) { delete auth; auth = nullptr; } }
16,496
C++
.cpp
379
33.358839
204
0.586445
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,929
ssldefaults.cpp
trojan-gfw_trojan/src/ssl/ssldefaults.cpp
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ssldefaults.h" const char SSLDefaults::g_dh2048_sz[] = "-----BEGIN DH PARAMETERS-----\n" "MIIBCAKCAQEA///////////JD9qiIWjCNMTGYouA3BzRKQJOCIpnzHQCC76mOxOb\n" "IlFKCHmONATd75UZs806QxswKwpt8l8UN0/hNW1tUcJF5IW1dmJefsb0TELppjft\n" "awv/XLb0Brft7jhr+1qJn6WunyQRfEsf5kkoZlHs5Fs9wgB8uKFjvwWY2kg2HFXT\n" "mmkWP6j9JM9fg2VdI9yjrZYcYvNWIIVSu57VKQdwlpZtZww1Tkq8mATxdGwIyhgh\n" "fDKQXkYuNs474553LBgOhgObJ4Oi7Aeij7XFXfBvTFLJ3ivL9pVYFxg5lUl86pVq\n" "5RXSJhiY+gUQFXKOWoqsqmj//////////wIBAg==\n" "-----END DH PARAMETERS-----"; const size_t SSLDefaults::g_dh2048_sz_size = sizeof(g_dh2048_sz);
1,437
C++
.cpp
29
46.758621
72
0.765125
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,930
sslsession.cpp
trojan-gfw_trojan/src/ssl/sslsession.cpp
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "sslsession.h" using namespace std; list<SSL_SESSION*>SSLSession::sessions; int SSLSession::new_session_cb(SSL*, SSL_SESSION *session) { sessions.push_front(session); return 0; } void SSLSession::remove_session_cb(SSL_CTX*, SSL_SESSION *session) { sessions.remove(session); } SSL_SESSION *SSLSession::get_session() { if (sessions.empty()) { return nullptr; } return sessions.front(); } void SSLSession::set_callback(SSL_CTX *context) { SSL_CTX_sess_set_new_cb(context, new_session_cb); SSL_CTX_sess_set_remove_cb(context, remove_session_cb); }
1,415
C++
.cpp
38
34.578947
72
0.741794
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,931
socks5address.cpp
trojan-gfw_trojan/src/proto/socks5address.cpp
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "socks5address.h" #include <cstdio> using namespace std; using namespace boost::asio::ip; bool SOCKS5Address::parse(const string &data, size_t &address_len) { if (data.length() == 0 || (data[0] != IPv4 && data[0] != DOMAINNAME && data[0] != IPv6)) { return false; } address_type = static_cast<AddressType>(data[0]); switch (address_type) { case IPv4: { if (data.length() > 4 + 2) { address = to_string(uint8_t(data[1])) + '.' + to_string(uint8_t(data[2])) + '.' + to_string(uint8_t(data[3])) + '.' + to_string(uint8_t(data[4])); port = (uint8_t(data[5]) << 8) | uint8_t(data[6]); address_len = 1 + 4 + 2; return true; } break; } case DOMAINNAME: { uint8_t domain_len = data[1]; if (domain_len == 0) { // invalid domain len break; } if (data.length() > (unsigned int)(1 + domain_len + 2)) { address = data.substr(2, domain_len); port = (uint8_t(data[domain_len + 2]) << 8) | uint8_t(data[domain_len + 3]); address_len = 1 + 1 + domain_len + 2; return true; } break; } case IPv6: { if (data.length() > 16 + 2) { char t[40]; sprintf(t, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x", uint8_t(data[1]), uint8_t(data[2]), uint8_t(data[3]), uint8_t(data[4]), uint8_t(data[5]), uint8_t(data[6]), uint8_t(data[7]), uint8_t(data[8]), uint8_t(data[9]), uint8_t(data[10]), uint8_t(data[11]), uint8_t(data[12]), uint8_t(data[13]), uint8_t(data[14]), uint8_t(data[15]), uint8_t(data[16])); address = t; port = (uint8_t(data[17]) << 8) | uint8_t(data[18]); address_len = 1 + 16 + 2; return true; } break; } } return false; } string SOCKS5Address::generate(const udp::endpoint &endpoint) { if (endpoint.address().is_unspecified()) { return string("\x01\x00\x00\x00\x00\x00\x00", 7); } string ret; if (endpoint.address().is_v4()) { ret += '\x01'; auto ip = endpoint.address().to_v4().to_bytes(); for (int i = 0; i < 4; ++i) { ret += char(ip[i]); } } if (endpoint.address().is_v6()) { ret += '\x04'; auto ip = endpoint.address().to_v6().to_bytes(); for (int i = 0; i < 16; ++i) { ret += char(ip[i]); } } ret += char(uint8_t(endpoint.port() >> 8)); ret += char(uint8_t(endpoint.port() & 0xFF)); return ret; }
3,737
C++
.cpp
95
29.810526
101
0.524869
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,932
udppacket.cpp
trojan-gfw_trojan/src/proto/udppacket.cpp
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "udppacket.h" using namespace std; using namespace boost::asio::ip; bool UDPPacket::parse(const string &data, size_t &udp_packet_len) { if (data.length() <= 0) { return false; } size_t address_len; bool is_addr_valid = address.parse(data, address_len); if (!is_addr_valid || data.length() < address_len + 2) { return false; } length = (uint8_t(data[address_len]) << 8) | uint8_t(data[address_len + 1]); if (data.length() < address_len + 4 + length || data.substr(address_len + 2, 2) != "\r\n") { return false; } payload = data.substr(address_len + 4, length); udp_packet_len = address_len + 4 + length; return true; } string UDPPacket::generate(const udp::endpoint &endpoint, const string &payload) { string ret = SOCKS5Address::generate(endpoint); ret += char(uint8_t(payload.length() >> 8)); ret += char(uint8_t(payload.length() & 0xFF)); ret += "\r\n"; ret += payload; return ret; } string UDPPacket::generate(const string &domainname, uint16_t port, const string &payload) { string ret = "\x03"; ret += char(uint8_t(domainname.length())); ret += domainname; ret += char(uint8_t(port >> 8)); ret += char(uint8_t(port & 0xFF)); ret += char(uint8_t(payload.length() >> 8)); ret += char(uint8_t(payload.length() & 0xFF)); ret += "\r\n"; ret += payload; return ret; }
2,232
C++
.cpp
58
34.775862
96
0.670968
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,933
trojanrequest.cpp
trojan-gfw_trojan/src/proto/trojanrequest.cpp
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "trojanrequest.h" using namespace std; int TrojanRequest::parse(const string &data) { size_t first = data.find("\r\n"); if (first == string::npos) { return -1; } password = data.substr(0, first); payload = data.substr(first + 2); if (payload.length() == 0 || (payload[0] != CONNECT && payload[0] != UDP_ASSOCIATE)) { return -1; } command = static_cast<Command>(payload[0]); size_t address_len; bool is_addr_valid = address.parse(payload.substr(1), address_len); if (!is_addr_valid || payload.length() < address_len + 3 || payload.substr(address_len + 1, 2) != "\r\n") { return -1; } payload = payload.substr(address_len + 3); return data.length(); } string TrojanRequest::generate(const string &password, const string &domainname, uint16_t port, bool tcp) { string ret = password + "\r\n"; if (tcp) { ret += '\x01'; } else { ret += '\x03'; } ret += '\x03'; ret += char(uint8_t(domainname.length())); ret += domainname; ret += char(uint8_t(port >> 8)); ret += char(uint8_t(port & 0xFF)); ret += "\r\n"; return ret; }
1,984
C++
.cpp
54
32.777778
111
0.659574
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,934
serversession.h
trojan-gfw_trojan/src/session/serversession.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _SERVERSESSION_H_ #define _SERVERSESSION_H_ #include "session.h" #include <boost/asio/ssl.hpp> #include "core/authenticator.h" class ServerSession : public Session { private: enum Status { HANDSHAKE, FORWARD, UDP_FORWARD, DESTROY } status; boost::asio::ssl::stream<boost::asio::ip::tcp::socket>in_socket; boost::asio::ip::tcp::socket out_socket; boost::asio::ip::udp::resolver udp_resolver; Authenticator *auth; std::string auth_password; const std::string &plain_http_response; void destroy(); void in_async_read(); void in_async_write(const std::string &data); void in_recv(const std::string &data); void in_sent(); void out_async_read(); void out_async_write(const std::string &data); void out_recv(const std::string &data); void out_sent(); void udp_async_read(); void udp_async_write(const std::string &data, const boost::asio::ip::udp::endpoint &endpoint); void udp_recv(const std::string &data, const boost::asio::ip::udp::endpoint &endpoint); void udp_sent(); public: ServerSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context, Authenticator *auth, const std::string &plain_http_response); boost::asio::ip::tcp::socket& accept_socket() override; void start() override; }; #endif // _SERVERSESSION_H_
2,217
C++
.h
56
35.928571
178
0.713027
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,935
natsession.h
trojan-gfw_trojan/src/session/natsession.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _NATSESSION_H_ #define _NATSESSION_H_ #include "session.h" #include <boost/asio/ssl.hpp> class NATSession : public Session { private: enum Status { CONNECT, FORWARD, DESTROY } status; bool first_packet_recv; boost::asio::ip::tcp::socket in_socket; boost::asio::ssl::stream<boost::asio::ip::tcp::socket>out_socket; void destroy(); void in_async_read(); void in_async_write(const std::string &data); void in_recv(const std::string &data); void in_sent(); void out_async_read(); void out_async_write(const std::string &data); void out_recv(const std::string &data); void out_sent(); std::pair<std::string, uint16_t> get_target_endpoint(); public: NATSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context); boost::asio::ip::tcp::socket& accept_socket() override; void start() override; }; #endif // _NATSESSION_H_
1,786
C++
.h
48
33.770833
114
0.711649
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,936
clientsession.h
trojan-gfw_trojan/src/session/clientsession.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _CLIENTSESSION_H_ #define _CLIENTSESSION_H_ #include "session.h" #include <boost/asio/ssl.hpp> class ClientSession : public Session { private: enum Status { HANDSHAKE, REQUEST, CONNECT, FORWARD, UDP_FORWARD, INVALID, DESTROY } status; bool is_udp{}; bool first_packet_recv; boost::asio::ip::tcp::socket in_socket; boost::asio::ssl::stream<boost::asio::ip::tcp::socket>out_socket; void destroy(); void in_async_read(); void in_async_write(const std::string &data); void in_recv(const std::string &data); void in_sent(); void out_async_read(); void out_async_write(const std::string &data); void out_recv(const std::string &data); void out_sent(); void udp_async_read(); void udp_async_write(const std::string &data, const boost::asio::ip::udp::endpoint &endpoint); void udp_recv(const std::string &data, const boost::asio::ip::udp::endpoint &endpoint); void udp_sent(); public: ClientSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context); boost::asio::ip::tcp::socket& accept_socket() override; void start() override; }; #endif // _CLIENTSESSION_H_
2,073
C++
.h
56
33.071429
117
0.701441
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,937
session.h
trojan-gfw_trojan/src/session/session.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _SESSION_H_ #define _SESSION_H_ #include <ctime> #include <memory> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/udp.hpp> #include <boost/asio/steady_timer.hpp> #include "core/config.h" class Session : public std::enable_shared_from_this<Session> { protected: enum { MAX_LENGTH = 8192, SSL_SHUTDOWN_TIMEOUT = 30 }; const Config &config; uint8_t in_read_buf[MAX_LENGTH]{}; uint8_t out_read_buf[MAX_LENGTH]{}; uint8_t udp_read_buf[MAX_LENGTH]{}; uint64_t recv_len; uint64_t sent_len; time_t start_time{}; std::string out_write_buf; std::string udp_data_buf; boost::asio::ip::tcp::resolver resolver; boost::asio::ip::tcp::endpoint in_endpoint; boost::asio::ip::udp::socket udp_socket; boost::asio::ip::udp::endpoint udp_recv_endpoint; boost::asio::steady_timer ssl_shutdown_timer; public: Session(const Config &config, boost::asio::io_context &io_context); virtual boost::asio::ip::tcp::socket& accept_socket() = 0; virtual void start() = 0; virtual ~Session(); }; #endif // _SESSION_H_
1,923
C++
.h
53
33.075472
72
0.712755
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,938
forwardsession.h
trojan-gfw_trojan/src/session/forwardsession.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _FORWARDSESSION_H_ #define _FORWARDSESSION_H_ #include "session.h" #include <boost/asio/ssl.hpp> class ForwardSession : public Session { private: enum Status { CONNECT, FORWARD, DESTROY } status; bool first_packet_recv; boost::asio::ip::tcp::socket in_socket; boost::asio::ssl::stream<boost::asio::ip::tcp::socket>out_socket; void destroy(); void in_async_read(); void in_async_write(const std::string &data); void in_recv(const std::string &data); void in_sent(); void out_async_read(); void out_async_write(const std::string &data); void out_recv(const std::string &data); void out_sent(); public: ForwardSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context); boost::asio::ip::tcp::socket& accept_socket() override; void start() override; }; #endif // _FORWARDSESSION_H_
1,746
C++
.h
47
33.744681
118
0.716224
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,939
udpforwardsession.h
trojan-gfw_trojan/src/session/udpforwardsession.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _UDPFORWARDSESSION_H_ #define _UDPFORWARDSESSION_H_ #include "session.h" #include <boost/asio/ssl.hpp> #include <boost/asio/steady_timer.hpp> class UDPForwardSession : public Session { public: typedef std::function<void(const boost::asio::ip::udp::endpoint&, const std::string&)> UDPWrite; private: enum Status { CONNECT, FORWARD, FORWARDING, DESTROY } status; UDPWrite in_write; boost::asio::ssl::stream<boost::asio::ip::tcp::socket>out_socket; boost::asio::steady_timer gc_timer; void destroy(); void in_recv(const std::string &data); void out_async_read(); void out_async_write(const std::string &data); void out_recv(const std::string &data); void out_sent(); void timer_async_wait(); public: UDPForwardSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context, const boost::asio::ip::udp::endpoint &endpoint, UDPWrite in_write); boost::asio::ip::tcp::socket& accept_socket() override; void start() override; bool process(const boost::asio::ip::udp::endpoint &endpoint, const std::string &data); }; #endif // _UDPFORWARDSESSION_H_
2,011
C++
.h
50
36.8
188
0.722534
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,941
authenticator.h
trojan-gfw_trojan/src/core/authenticator.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _AUTHENTICATOR_H_ #define _AUTHENTICATOR_H_ #ifdef ENABLE_MYSQL #include <mysql.h> #endif // ENABLE_MYSQL #include "config.h" class Authenticator { private: #ifdef ENABLE_MYSQL MYSQL con{}; #endif // ENABLE_MYSQL enum { PASSWORD_LENGTH=56 }; static bool is_valid_password(const std::string &password); public: explicit Authenticator(const Config &config); bool auth(const std::string &password); void record(const std::string &password, uint64_t download, uint64_t upload); ~Authenticator(); }; #endif // _AUTHENTICATOR_H_
1,391
C++
.h
40
32.25
81
0.744618
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,942
service.h
trojan-gfw_trojan/src/core/service.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _SERVICE_H_ #define _SERVICE_H_ #include <list> #include <boost/version.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ssl.hpp> #include <boost/asio/ip/udp.hpp> #include "authenticator.h" #include "session/udpforwardsession.h" class Service { private: enum { MAX_LENGTH = 8192 }; const Config &config; boost::asio::io_context io_context; boost::asio::ip::tcp::acceptor socket_acceptor; boost::asio::ssl::context ssl_context; Authenticator *auth; std::string plain_http_response; boost::asio::ip::udp::socket udp_socket; std::list<std::weak_ptr<UDPForwardSession> > udp_sessions; uint8_t udp_read_buf[MAX_LENGTH]{}; boost::asio::ip::udp::endpoint udp_recv_endpoint; void async_accept(); void udp_async_read(); public: explicit Service(Config &config, bool test = false); void run(); void stop(); boost::asio::io_context &service(); void reload_cert(); ~Service(); }; #endif // _SERVICE_H_
1,820
C++
.h
53
31.283019
72
0.719796
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,943
log.h
trojan-gfw_trojan/src/core/log.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _LOG_H_ #define _LOG_H_ #include <cstdio> #include <string> #include <boost/asio/ip/tcp.hpp> #ifdef ERROR // windows.h #undef ERROR #endif // ERROR class Log { public: enum Level { ALL = 0, INFO = 1, WARN = 2, ERROR = 3, FATAL = 4, OFF = 5 }; typedef std::function<void(const std::string &, Level)> LogCallback; static Level level; static FILE *keylog; static void log(const std::string &message, Level level = ALL); static void log_with_date_time(const std::string &message, Level level = ALL); static void log_with_endpoint(const boost::asio::ip::tcp::endpoint &endpoint, const std::string &message, Level level = ALL); static void redirect(const std::string &filename); static void redirect_keylog(const std::string &filename); static void set_callback(LogCallback cb); static void reset(); private: static FILE *output_stream; static LogCallback log_callback; }; #endif // _LOG_H_
1,818
C++
.h
51
32.176471
129
0.710556
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,944
config.h
trojan-gfw_trojan/src/core/config.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _CONFIG_H_ #define _CONFIG_H_ #include <cstdint> #include <map> #include <boost/property_tree/ptree.hpp> #include "log.h" class Config { public: enum RunType { SERVER, CLIENT, FORWARD, NAT } run_type; std::string local_addr; uint16_t local_port; std::string remote_addr; uint16_t remote_port; std::string target_addr; uint16_t target_port; std::map<std::string, std::string> password; int udp_timeout; Log::Level log_level; class SSLConfig { public: bool verify; bool verify_hostname; std::string cert; std::string key; std::string key_password; std::string cipher; std::string cipher_tls13; bool prefer_server_cipher; std::string sni; std::string alpn; std::map<std::string, uint16_t> alpn_port_override; bool reuse_session; bool session_ticket; long session_timeout; std::string plain_http_response; std::string curves; std::string dhparam; } ssl; class TCPConfig { public: bool prefer_ipv4; bool no_delay; bool keep_alive; bool reuse_port; bool fast_open; int fast_open_qlen; } tcp; class MySQLConfig { public: bool enabled; std::string server_addr; uint16_t server_port; std::string database; std::string username; std::string password; std::string key; std::string cert; std::string ca; } mysql; void load(const std::string &filename); void populate(const std::string &JSON); bool sip003(); static std::string SHA224(const std::string &message); private: void populate(const boost::property_tree::ptree &tree); }; #endif // _CONFIG_H_
2,656
C++
.h
90
23.966667
72
0.656909
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,945
ssldefaults.h
trojan-gfw_trojan/src/ssl/ssldefaults.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _SSLDEFAULTS_H_ #define _SSLDEFAULTS_H_ #include <cstddef> class SSLDefaults { public: static const char g_dh2048_sz[]; static const size_t g_dh2048_sz_size; }; #endif // _SSLDEFAULTS_H_
1,023
C++
.h
27
35.814815
72
0.754032
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,946
sslsession.h
trojan-gfw_trojan/src/ssl/sslsession.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _SSLSESSION_H_ #define _SSLSESSION_H_ #include <list> #include <openssl/ssl.h> class SSLSession { private: static std::list<SSL_SESSION*>sessions; static int new_session_cb(SSL*, SSL_SESSION *session); static void remove_session_cb(SSL_CTX*, SSL_SESSION *session); public: static SSL_SESSION *get_session(); static void set_callback(SSL_CTX *context); }; #endif // _SSLSESSION_H_
1,228
C++
.h
32
36.09375
72
0.749161
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,947
socks5address.h
trojan-gfw_trojan/src/proto/socks5address.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _SOCKS5ADDRESS_H_ #define _SOCKS5ADDRESS_H_ #include <cstdint> #include <string> #include <boost/asio/ip/udp.hpp> class SOCKS5Address { public: enum AddressType { IPv4 = 1, DOMAINNAME = 3, IPv6 = 4 } address_type; std::string address; uint16_t port; bool parse(const std::string &data, size_t &address_len); static std::string generate(const boost::asio::ip::udp::endpoint &endpoint); }; #endif // _SOCKS5ADDRESS_H_
1,292
C++
.h
36
32.972222
80
0.730032
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,948
trojanrequest.h
trojan-gfw_trojan/src/proto/trojanrequest.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _TROJANREQUEST_H_ #define _TROJANREQUEST_H_ #include "socks5address.h" class TrojanRequest { public: std::string password; enum Command { CONNECT = 1, UDP_ASSOCIATE = 3 } command; SOCKS5Address address; std::string payload; int parse(const std::string &data); static std::string generate(const std::string &password, const std::string &domainname, uint16_t port, bool tcp); }; #endif // _TROJANREQUEST_H_
1,277
C++
.h
34
34.647059
117
0.738499
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,949
udppacket.h
trojan-gfw_trojan/src/proto/udppacket.h
/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _UDPPACKET_H_ #define _UDPPACKET_H_ #include "socks5address.h" class UDPPacket { public: SOCKS5Address address; uint16_t length; std::string payload; bool parse(const std::string &data, size_t &udp_packet_len); static std::string generate(const boost::asio::ip::udp::endpoint &endpoint, const std::string &payload); static std::string generate(const std::string &domainname, uint16_t port, const std::string &payload); }; #endif // _UDPPACKET_H_
1,298
C++
.h
31
39.419355
108
0.748219
trojan-gfw/trojan
18,846
3,016
86
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,950
sunshinesvc.cpp
LizardByte_Sunshine/tools/sunshinesvc.cpp
/** * @file tools/sunshinesvc.cpp * @brief Handles launching Sunshine.exe into user sessions as SYSTEM */ #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <wtsapi32.h> #include <string> // PROC_THREAD_ATTRIBUTE_JOB_LIST is currently missing from MinGW headers #ifndef PROC_THREAD_ATTRIBUTE_JOB_LIST #define PROC_THREAD_ATTRIBUTE_JOB_LIST ProcThreadAttributeValue(13, FALSE, TRUE, FALSE) #endif SERVICE_STATUS_HANDLE service_status_handle; SERVICE_STATUS service_status; HANDLE stop_event; HANDLE session_change_event; #define SERVICE_NAME "SunshineService" DWORD WINAPI HandlerEx(DWORD dwControl, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext) { switch (dwControl) { case SERVICE_CONTROL_INTERROGATE: return NO_ERROR; case SERVICE_CONTROL_SESSIONCHANGE: // If a new session connects to the console, restart Sunshine // to allow it to spawn inside the new console session. if (dwEventType == WTS_CONSOLE_CONNECT) { SetEvent(session_change_event); } return NO_ERROR; case SERVICE_CONTROL_PRESHUTDOWN: // The system is shutting down case SERVICE_CONTROL_STOP: // Let SCM know we're stopping in up to 30 seconds service_status.dwCurrentState = SERVICE_STOP_PENDING; service_status.dwControlsAccepted = 0; service_status.dwWaitHint = 30 * 1000; SetServiceStatus(service_status_handle, &service_status); // Trigger ServiceMain() to start cleanup SetEvent(stop_event); return NO_ERROR; default: return ERROR_CALL_NOT_IMPLEMENTED; } } HANDLE CreateJobObjectForChildProcess() { HANDLE job_handle = CreateJobObjectW(NULL, NULL); if (!job_handle) { return NULL; } JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_limit_info = {}; // Kill Sunshine.exe when the final job object handle is closed (which will happen if we terminate unexpectedly). // This ensures we don't leave an orphaned Sunshine.exe running with an inherited handle to our log file. job_limit_info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; // Allow Sunshine.exe to use CREATE_BREAKAWAY_FROM_JOB when spawning processes to ensure they can to live beyond // the lifetime of SunshineSvc.exe. This avoids unexpected user data loss if we crash or are killed. job_limit_info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_BREAKAWAY_OK; if (!SetInformationJobObject(job_handle, JobObjectExtendedLimitInformation, &job_limit_info, sizeof(job_limit_info))) { CloseHandle(job_handle); return NULL; } return job_handle; } LPPROC_THREAD_ATTRIBUTE_LIST AllocateProcThreadAttributeList(DWORD attribute_count) { SIZE_T size; InitializeProcThreadAttributeList(NULL, attribute_count, 0, &size); auto list = (LPPROC_THREAD_ATTRIBUTE_LIST) HeapAlloc(GetProcessHeap(), 0, size); if (list == NULL) { return NULL; } if (!InitializeProcThreadAttributeList(list, attribute_count, 0, &size)) { HeapFree(GetProcessHeap(), 0, list); return NULL; } return list; } HANDLE DuplicateTokenForSession(DWORD console_session_id) { HANDLE current_token; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &current_token)) { return NULL; } // Duplicate our own LocalSystem token HANDLE new_token; if (!DuplicateTokenEx(current_token, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation, TokenPrimary, &new_token)) { CloseHandle(current_token); return NULL; } CloseHandle(current_token); // Change the duplicated token to the console session ID if (!SetTokenInformation(new_token, TokenSessionId, &console_session_id, sizeof(console_session_id))) { CloseHandle(new_token); return NULL; } return new_token; } HANDLE OpenLogFileHandle() { WCHAR log_file_name[MAX_PATH]; // Create sunshine.log in the Temp folder (usually %SYSTEMROOT%\Temp) GetTempPathW(_countof(log_file_name), log_file_name); wcscat_s(log_file_name, L"sunshine.log"); // The file handle must be inheritable for our child process to use it SECURITY_ATTRIBUTES security_attributes = { sizeof(security_attributes), NULL, TRUE }; // Overwrite the old sunshine.log return CreateFileW(log_file_name, GENERIC_WRITE, FILE_SHARE_READ, &security_attributes, CREATE_ALWAYS, 0, NULL); } bool RunTerminationHelper(HANDLE console_token, DWORD pid) { WCHAR module_path[MAX_PATH]; GetModuleFileNameW(NULL, module_path, _countof(module_path)); std::wstring command; command += L'"'; command += module_path; command += L'"'; command += L" --terminate " + std::to_wstring(pid); STARTUPINFOW startup_info = {}; startup_info.cb = sizeof(startup_info); startup_info.lpDesktop = (LPWSTR) L"winsta0\\default"; // Execute ourselves as a detached process in the user session with the --terminate argument. // This will allow us to attach to Sunshine's console and send it a Ctrl-C event. PROCESS_INFORMATION process_info; if (!CreateProcessAsUserW(console_token, module_path, (LPWSTR) command.c_str(), NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT | DETACHED_PROCESS, NULL, NULL, &startup_info, &process_info)) { return false; } // Wait for the termination helper to complete WaitForSingleObject(process_info.hProcess, INFINITE); // Check the exit status of the helper process DWORD exit_code; GetExitCodeProcess(process_info.hProcess, &exit_code); // Cleanup handles CloseHandle(process_info.hProcess); CloseHandle(process_info.hThread); // If the helper process returned 0, it succeeded return exit_code == 0; } VOID WINAPI ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) { service_status_handle = RegisterServiceCtrlHandlerEx(SERVICE_NAME, HandlerEx, NULL); if (service_status_handle == NULL) { // Nothing we can really do here but terminate ourselves ExitProcess(GetLastError()); return; } // Tell SCM we're starting service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; service_status.dwServiceSpecificExitCode = 0; service_status.dwWin32ExitCode = NO_ERROR; service_status.dwWaitHint = 0; service_status.dwControlsAccepted = 0; service_status.dwCheckPoint = 0; service_status.dwCurrentState = SERVICE_START_PENDING; SetServiceStatus(service_status_handle, &service_status); // Create a manual-reset stop event stop_event = CreateEventA(NULL, TRUE, FALSE, NULL); if (stop_event == NULL) { // Tell SCM we failed to start service_status.dwWin32ExitCode = GetLastError(); service_status.dwCurrentState = SERVICE_STOPPED; SetServiceStatus(service_status_handle, &service_status); return; } // Create an auto-reset session change event session_change_event = CreateEventA(NULL, FALSE, FALSE, NULL); if (session_change_event == NULL) { // Tell SCM we failed to start service_status.dwWin32ExitCode = GetLastError(); service_status.dwCurrentState = SERVICE_STOPPED; SetServiceStatus(service_status_handle, &service_status); return; } auto log_file_handle = OpenLogFileHandle(); if (log_file_handle == INVALID_HANDLE_VALUE) { // Tell SCM we failed to start service_status.dwWin32ExitCode = GetLastError(); service_status.dwCurrentState = SERVICE_STOPPED; SetServiceStatus(service_status_handle, &service_status); return; } // We can use a single STARTUPINFOEXW for all the processes that we launch STARTUPINFOEXW startup_info = {}; startup_info.StartupInfo.cb = sizeof(startup_info); startup_info.StartupInfo.lpDesktop = (LPWSTR) L"winsta0\\default"; startup_info.StartupInfo.dwFlags = STARTF_USESTDHANDLES; startup_info.StartupInfo.hStdInput = NULL; startup_info.StartupInfo.hStdOutput = log_file_handle; startup_info.StartupInfo.hStdError = log_file_handle; // Allocate an attribute list with space for 2 entries startup_info.lpAttributeList = AllocateProcThreadAttributeList(2); if (startup_info.lpAttributeList == NULL) { // Tell SCM we failed to start service_status.dwWin32ExitCode = GetLastError(); service_status.dwCurrentState = SERVICE_STOPPED; SetServiceStatus(service_status_handle, &service_status); return; } // Only allow Sunshine.exe to inherit the log file handle, not all inheritable handles UpdateProcThreadAttribute(startup_info.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, &log_file_handle, sizeof(log_file_handle), NULL, NULL); // Tell SCM we're running (and stoppable now) service_status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PRESHUTDOWN | SERVICE_ACCEPT_SESSIONCHANGE; service_status.dwCurrentState = SERVICE_RUNNING; SetServiceStatus(service_status_handle, &service_status); // Loop every 3 seconds until the stop event is set or Sunshine.exe is running while (WaitForSingleObject(stop_event, 3000) != WAIT_OBJECT_0) { auto console_session_id = WTSGetActiveConsoleSessionId(); if (console_session_id == 0xFFFFFFFF) { // No console session yet continue; } auto console_token = DuplicateTokenForSession(console_session_id); if (console_token == NULL) { continue; } // Job objects cannot span sessions, so we must create one for each process auto job_handle = CreateJobObjectForChildProcess(); if (job_handle == NULL) { CloseHandle(console_token); continue; } // Start Sunshine.exe inside our job object UpdateProcThreadAttribute(startup_info.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_JOB_LIST, &job_handle, sizeof(job_handle), NULL, NULL); PROCESS_INFORMATION process_info; if (!CreateProcessAsUserW(console_token, L"Sunshine.exe", NULL, NULL, NULL, TRUE, CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT, NULL, NULL, (LPSTARTUPINFOW) &startup_info, &process_info)) { CloseHandle(console_token); CloseHandle(job_handle); continue; } bool still_running; do { // Wait for the stop event to be set, Sunshine.exe to terminate, or the console session to change const HANDLE wait_objects[] = { stop_event, process_info.hProcess, session_change_event }; switch (WaitForMultipleObjects(_countof(wait_objects), wait_objects, FALSE, INFINITE)) { case WAIT_OBJECT_0 + 2: if (WTSGetActiveConsoleSessionId() == console_session_id) { // The active console session didn't actually change. Let Sunshine keep running. still_running = true; continue; } // Fall-through to terminate Sunshine.exe and start it again. case WAIT_OBJECT_0: // The service is shutting down, so try to gracefully terminate Sunshine.exe. // If it doesn't terminate in 20 seconds, we will forcefully terminate it. if (!RunTerminationHelper(console_token, process_info.dwProcessId) || WaitForSingleObject(process_info.hProcess, 20000) != WAIT_OBJECT_0) { // If it won't terminate gracefully, kill it now TerminateProcess(process_info.hProcess, ERROR_PROCESS_ABORTED); } still_running = false; break; case WAIT_OBJECT_0 + 1: { // Sunshine terminated itself. DWORD exit_code; if (GetExitCodeProcess(process_info.hProcess, &exit_code) && exit_code == ERROR_SHUTDOWN_IN_PROGRESS) { // Sunshine is asking for us to shut down, so gracefully stop ourselves. SetEvent(stop_event); } still_running = false; break; } } } while (still_running); CloseHandle(process_info.hThread); CloseHandle(process_info.hProcess); CloseHandle(console_token); CloseHandle(job_handle); } // Let SCM know we've stopped service_status.dwCurrentState = SERVICE_STOPPED; SetServiceStatus(service_status_handle, &service_status); } // This will run in a child process in the user session int DoGracefulTermination(DWORD pid) { // Attach to Sunshine's console if (!AttachConsole(pid)) { return GetLastError(); } // Disable our own Ctrl-C handling SetConsoleCtrlHandler(NULL, TRUE); // Send a Ctrl-C event to Sunshine if (!GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0)) { return GetLastError(); } return 0; } int main(int argc, char *argv[]) { static const SERVICE_TABLE_ENTRY service_table[] = { { (LPSTR) SERVICE_NAME, ServiceMain }, { NULL, NULL } }; // Check if this is a reinvocation of ourselves to send Ctrl-C to Sunshine.exe if (argc == 3 && strcmp(argv[1], "--terminate") == 0) { return DoGracefulTermination(atol(argv[2])); } // By default, services have their current directory set to %SYSTEMROOT%\System32. // We want to use the directory where Sunshine.exe is located instead of system32. // This requires stripping off 2 path components: the file name and the last folder WCHAR module_path[MAX_PATH]; GetModuleFileNameW(NULL, module_path, _countof(module_path)); for (auto i = 0; i < 2; i++) { auto last_sep = wcsrchr(module_path, '\\'); if (last_sep) { *last_sep = 0; } } SetCurrentDirectoryW(module_path); // Trigger our ServiceMain() return StartServiceCtrlDispatcher(service_table); }
13,457
C++
.cpp
349
33.684814
121
0.717133
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,951
audio.cpp
LizardByte_Sunshine/tools/audio.cpp
/** * @file tools/audio.cpp * @brief Handles collecting audio device information from Windows. */ #define INITGUID #include <audioclient.h> #include <mmdeviceapi.h> #include <roapi.h> #include <codecvt> #include <locale> #include <synchapi.h> #include <iostream> #include "src/utility.h" DEFINE_PROPERTYKEY(PKEY_Device_DeviceDesc, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 2); // DEVPROP_TYPE_STRING DEFINE_PROPERTYKEY(PKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 14); // DEVPROP_TYPE_STRING DEFINE_PROPERTYKEY(PKEY_DeviceInterface_FriendlyName, 0x026e516e, 0xb814, 0x414b, 0x83, 0xcd, 0x85, 0x6d, 0x6f, 0xef, 0x48, 0x22, 2); using namespace std::literals; int device_state_filter = DEVICE_STATE_ACTIVE; namespace audio { template <class T> void Release(T *p) { p->Release(); } template <class T> void co_task_free(T *p) { CoTaskMemFree((LPVOID) p); } using device_enum_t = util::safe_ptr<IMMDeviceEnumerator, Release<IMMDeviceEnumerator>>; using collection_t = util::safe_ptr<IMMDeviceCollection, Release<IMMDeviceCollection>>; using prop_t = util::safe_ptr<IPropertyStore, Release<IPropertyStore>>; using device_t = util::safe_ptr<IMMDevice, Release<IMMDevice>>; using audio_client_t = util::safe_ptr<IAudioClient, Release<IAudioClient>>; using audio_capture_t = util::safe_ptr<IAudioCaptureClient, Release<IAudioCaptureClient>>; using wave_format_t = util::safe_ptr<WAVEFORMATEX, co_task_free<WAVEFORMATEX>>; using wstring_t = util::safe_ptr<WCHAR, co_task_free<WCHAR>>; using handle_t = util::safe_ptr_v2<void, BOOL, CloseHandle>; static std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> converter; class prop_var_t { public: prop_var_t() { PropVariantInit(&prop); } ~prop_var_t() { PropVariantClear(&prop); } PROPVARIANT prop; }; const wchar_t * no_null(const wchar_t *str) { return str ? str : L"Unknown"; } struct format_t { std::string_view name; int channels; int channel_mask; } formats[] { { "Mono"sv, 1, SPEAKER_FRONT_CENTER }, { "Stereo"sv, 2, SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT }, { "Quadraphonic"sv, 4, SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT }, { "Surround 5.1 (Side)"sv, 6, SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT }, { "Surround 5.1 (Back)"sv, 6, SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT }, { "Surround 7.1"sv, 8, SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT } }; void set_wave_format(audio::wave_format_t &wave_format, const format_t &format) { wave_format->nChannels = format.channels; wave_format->nBlockAlign = wave_format->nChannels * wave_format->wBitsPerSample / 8; wave_format->nAvgBytesPerSec = wave_format->nSamplesPerSec * wave_format->nBlockAlign; if (wave_format->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { ((PWAVEFORMATEXTENSIBLE) wave_format.get())->dwChannelMask = format.channel_mask; } } audio_client_t make_audio_client(device_t &device, const format_t &format) { audio_client_t audio_client; auto status = device->Activate( IID_IAudioClient, CLSCTX_ALL, nullptr, (void **) &audio_client); if (FAILED(status)) { std::cout << "Couldn't activate Device: [0x"sv << util::hex(status).to_string_view() << ']' << std::endl; return nullptr; } wave_format_t wave_format; status = audio_client->GetMixFormat(&wave_format); if (FAILED(status)) { std::cout << "Couldn't acquire Wave Format [0x"sv << util::hex(status).to_string_view() << ']' << std::endl; return nullptr; } set_wave_format(wave_format, format); status = audio_client->Initialize( AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_EVENTCALLBACK, 0, 0, wave_format.get(), nullptr); if (status) { return nullptr; } return audio_client; } void print_device(device_t &device) { audio::wstring_t wstring; DWORD device_state; device->GetState(&device_state); device->GetId(&wstring); audio::prop_t prop; device->OpenPropertyStore(STGM_READ, &prop); prop_var_t adapter_friendly_name; prop_var_t device_friendly_name; prop_var_t device_desc; prop->GetValue(PKEY_Device_FriendlyName, &device_friendly_name.prop); prop->GetValue(PKEY_DeviceInterface_FriendlyName, &adapter_friendly_name.prop); prop->GetValue(PKEY_Device_DeviceDesc, &device_desc.prop); if (!(device_state & device_state_filter)) { return; } std::wstring device_state_string = L"Unknown"s; switch (device_state) { case DEVICE_STATE_ACTIVE: device_state_string = L"Active"s; break; case DEVICE_STATE_DISABLED: device_state_string = L"Disabled"s; break; case DEVICE_STATE_UNPLUGGED: device_state_string = L"Unplugged"s; break; case DEVICE_STATE_NOTPRESENT: device_state_string = L"Not present"s; break; } std::wstring current_format = L"Unknown"s; for (const auto &format : formats) { // This will fail for any format that's not the mix format for this device, // so we can take the first match as the current format to display. auto audio_client = make_audio_client(device, format); if (audio_client) { current_format = converter.from_bytes(format.name.data()); break; } } std::wcout << L"===== Device ====="sv << std::endl << L"Device ID : "sv << wstring.get() << std::endl << L"Device name : "sv << no_null((LPWSTR) device_friendly_name.prop.pszVal) << std::endl << L"Adapter name : "sv << no_null((LPWSTR) adapter_friendly_name.prop.pszVal) << std::endl << L"Device description : "sv << no_null((LPWSTR) device_desc.prop.pszVal) << std::endl << L"Device state : "sv << device_state_string << std::endl << L"Current format : "sv << current_format << std::endl << std::endl; } } // namespace audio void print_help() { std::cout << "==== Help ===="sv << std::endl << "Usage:"sv << std::endl << " audio-info [Active|Disabled|Unplugged|Not-Present]" << std::endl; } int main(int argc, char *argv[]) { CoInitializeEx(nullptr, COINIT_MULTITHREADED | COINIT_SPEED_OVER_MEMORY); auto fg = util::fail_guard([]() { CoUninitialize(); }); if (argc > 1) { device_state_filter = 0; } for (auto x = 1; x < argc; ++x) { for (auto p = argv[x]; *p != '\0'; ++p) { if (*p == ' ') { *p = '-'; continue; } *p = std::tolower(*p); } if (argv[x] == "active"sv) { device_state_filter |= DEVICE_STATE_ACTIVE; } else if (argv[x] == "disabled"sv) { device_state_filter |= DEVICE_STATE_DISABLED; } else if (argv[x] == "unplugged"sv) { device_state_filter |= DEVICE_STATE_UNPLUGGED; } else if (argv[x] == "not-present"sv) { device_state_filter |= DEVICE_STATE_NOTPRESENT; } else { print_help(); return 2; } } HRESULT status; audio::device_enum_t device_enum; status = CoCreateInstance( CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **) &device_enum); if (FAILED(status)) { std::cout << "Couldn't create Device Enumerator: [0x"sv << util::hex(status).to_string_view() << ']' << std::endl; return -1; } audio::collection_t collection; status = device_enum->EnumAudioEndpoints(eRender, device_state_filter, &collection); if (FAILED(status)) { std::cout << "Couldn't enumerate: [0x"sv << util::hex(status).to_string_view() << ']' << std::endl; return -1; } UINT count; collection->GetCount(&count); std::cout << "====== Found "sv << count << " audio devices ======"sv << std::endl; for (auto x = 0; x < count; ++x) { audio::device_t device; collection->Item(x, &device); audio::print_device(device); } return 0; }
8,687
C++
.cpp
258
28.368217
149
0.638677
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,952
dxgi.cpp
LizardByte_Sunshine/tools/dxgi.cpp
/** * @file tools/dxgi.cpp * @brief Displays information about connected displays and GPUs */ #define WINVER 0x0A00 #include <d3dcommon.h> #include <dxgi.h> #include <iostream> #include "src/utility.h" using namespace std::literals; namespace dxgi { template <class T> void Release(T *dxgi) { dxgi->Release(); } using factory1_t = util::safe_ptr<IDXGIFactory1, Release<IDXGIFactory1>>; using adapter_t = util::safe_ptr<IDXGIAdapter1, Release<IDXGIAdapter1>>; using output_t = util::safe_ptr<IDXGIOutput, Release<IDXGIOutput>>; } // namespace dxgi int main(int argc, char *argv[]) { HRESULT status; // Set ourselves as per-monitor DPI aware for accurate resolution values on High DPI systems SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); dxgi::factory1_t::pointer factory_p {}; status = CreateDXGIFactory1(IID_IDXGIFactory1, (void **) &factory_p); dxgi::factory1_t factory { factory_p }; if (FAILED(status)) { std::cout << "Failed to create DXGIFactory1 [0x"sv << util::hex(status).to_string_view() << ']' << std::endl; return -1; } dxgi::adapter_t::pointer adapter_p {}; for (int x = 0; factory->EnumAdapters1(x, &adapter_p) != DXGI_ERROR_NOT_FOUND; ++x) { dxgi::adapter_t adapter { adapter_p }; DXGI_ADAPTER_DESC1 adapter_desc; adapter->GetDesc1(&adapter_desc); std::cout << "====== ADAPTER ====="sv << std::endl; std::wcout << L"Device Name : "sv << adapter_desc.Description << std::endl; std::cout << "Device Vendor ID : 0x"sv << util::hex(adapter_desc.VendorId).to_string_view() << std::endl << "Device Device ID : 0x"sv << util::hex(adapter_desc.DeviceId).to_string_view() << std::endl << "Device Video Mem : "sv << adapter_desc.DedicatedVideoMemory / 1048576 << " MiB"sv << std::endl << "Device Sys Mem : "sv << adapter_desc.DedicatedSystemMemory / 1048576 << " MiB"sv << std::endl << "Share Sys Mem : "sv << adapter_desc.SharedSystemMemory / 1048576 << " MiB"sv << std::endl << std::endl << " ====== OUTPUT ======"sv << std::endl; dxgi::output_t::pointer output_p {}; for (int y = 0; adapter->EnumOutputs(y, &output_p) != DXGI_ERROR_NOT_FOUND; ++y) { dxgi::output_t output { output_p }; DXGI_OUTPUT_DESC desc; output->GetDesc(&desc); auto width = desc.DesktopCoordinates.right - desc.DesktopCoordinates.left; auto height = desc.DesktopCoordinates.bottom - desc.DesktopCoordinates.top; std::wcout << L" Output Name : "sv << desc.DeviceName << std::endl; std::cout << " AttachedToDesktop : "sv << (desc.AttachedToDesktop ? "yes"sv : "no"sv) << std::endl << " Resolution : "sv << width << 'x' << height << std::endl << std::endl; } } return 0; }
2,848
C++
.cpp
66
38.621212
113
0.641359
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,953
ddprobe.cpp
LizardByte_Sunshine/tools/ddprobe.cpp
/** * @file tools/ddprobe.cpp * @brief Handles probing for DXGI duplication support. */ #include <d3d11.h> #include <dxgi1_2.h> #include <codecvt> #include <iostream> #include <locale> #include <string> #include <wrl.h> #include "src/utility.h" using Microsoft::WRL::ComPtr; using namespace std::literals; namespace dxgi { template <class T> void Release(T *dxgi) { dxgi->Release(); } using factory1_t = util::safe_ptr<IDXGIFactory1, Release<IDXGIFactory1>>; using adapter_t = util::safe_ptr<IDXGIAdapter1, Release<IDXGIAdapter1>>; using output_t = util::safe_ptr<IDXGIOutput, Release<IDXGIOutput>>; using output1_t = util::safe_ptr<IDXGIOutput1, Release<IDXGIOutput1>>; using device_t = util::safe_ptr<ID3D11Device, Release<ID3D11Device>>; using dup_t = util::safe_ptr<IDXGIOutputDuplication, Release<IDXGIOutputDuplication>>; } // namespace dxgi LSTATUS set_gpu_preference(int preference) { // The GPU preferences key uses app path as the value name. WCHAR executable_path[MAX_PATH]; GetModuleFileNameW(NULL, executable_path, ARRAYSIZE(executable_path)); WCHAR value_data[128]; swprintf_s(value_data, L"GpuPreference=%d;", preference); auto status = RegSetKeyValueW(HKEY_CURRENT_USER, L"Software\\Microsoft\\DirectX\\UserGpuPreferences", executable_path, REG_SZ, value_data, (wcslen(value_data) + 1) * sizeof(WCHAR)); if (status != ERROR_SUCCESS) { std::cout << "Failed to set GPU preference: "sv << status << std::endl; return status; } return ERROR_SUCCESS; } void syncThreadDesktop() { auto hDesk = OpenInputDesktop(DF_ALLOWOTHERACCOUNTHOOK, FALSE, GENERIC_ALL); if (!hDesk) { auto err = GetLastError(); std::cout << "Failed to Open Input Desktop [0x"sv << util::hex(err).to_string_view() << ']' << std::endl; return; } if (!SetThreadDesktop(hDesk)) { auto err = GetLastError(); std::cout << "Failed to sync desktop to thread [0x"sv << util::hex(err).to_string_view() << ']' << std::endl; } CloseDesktop(hDesk); } /** * @brief Determines if a given frame is valid by checking if it contains any non-dark pixels. * * This function analyzes the provided frame to determine if it contains any pixels that exceed a specified darkness threshold. * It iterates over all pixels in the frame, comparing each pixel's RGB values to the defined darkness threshold. * If any pixel's RGB values exceed this threshold, the function concludes that the frame is valid (i.e., not entirely dark) and returns `true`. * If all pixels are below or equal to the threshold, indicating a completely dark frame, the function returns `false`. * @param mappedResource A reference to a `D3D11_MAPPED_SUBRESOURCE` structure containing the mapped subresource data of the frame to be analyzed. * @param frameDesc A reference to a `D3D11_TEXTURE2D_DESC` structure describing the texture properties, including width and height. * @param darknessThreshold A floating-point value representing the threshold above which a pixel's RGB values are considered dark. The value ranges from 0.0f to 1.0f, with a default value of 0.1f. * @return Returns `true` if the frame contains any non-dark pixels, indicating it is valid; otherwise, returns `false`. */ bool is_valid_frame(const D3D11_MAPPED_SUBRESOURCE &mappedResource, const D3D11_TEXTURE2D_DESC &frameDesc, float darknessThreshold = 0.1f) { const auto *pixels = static_cast<const uint8_t *>(mappedResource.pData); const int bytesPerPixel = 4; // (8 bits per channel, excluding alpha). Factoring HDR is not needed because it doesn't cause black levels to raise enough to be a concern. const int stride = mappedResource.RowPitch; const int width = frameDesc.Width; const int height = frameDesc.Height; // Convert the darkness threshold to an integer value for comparison const auto threshold = static_cast<int>(darknessThreshold * 255); // Iterate over each pixel in the frame for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { const uint8_t *pixel = pixels + y * stride + x * bytesPerPixel; // Check if any RGB channel exceeds the darkness threshold if (pixel[0] > threshold || pixel[1] > threshold || pixel[2] > threshold) { // Frame is not dark return true; } } } // Frame is entirely dark return false; } /** * @brief Captures and verifies the contents of up to 10 consecutive frames from a DXGI output duplication. * * This function attempts to acquire and analyze up to 10 frames from a DXGI output duplication object (`dup`). * It checks if each frame is non-empty (not entirely dark) by using the `is_valid_frame` function. * If any non-empty frame is found, the function returns `S_OK`. * If all 10 frames are empty, it returns `E_FAIL`, suggesting potential issues with the capture process. * If any error occurs during the frame acquisition or analysis process, the corresponding `HRESULT` error code is returned. * * @param dup A reference to the DXGI output duplication object (`dxgi::dup_t&`) used to acquire frames. * @param device A ComPtr to the ID3D11Device interface representing the device associated with the Direct3D context. * @return Returns `S_OK` if a non-empty frame is captured successfully, `E_FAIL` if all frames are empty, or an error code if any failure occurs during the process. */ HRESULT test_frame_capture(dxgi::dup_t &dup, ComPtr<ID3D11Device> device) { for (int i = 0; i < 10; ++i) { std::cout << "Attempting to acquire frame " << (i + 1) << " of 10..." << std::endl; ComPtr<IDXGIResource> frameResource; DXGI_OUTDUPL_FRAME_INFO frameInfo; ComPtr<ID3D11DeviceContext> context; ComPtr<ID3D11Texture2D> stagingTexture; HRESULT status = dup->AcquireNextFrame(500, &frameInfo, &frameResource); device->GetImmediateContext(&context); if (FAILED(status)) { std::cout << "Error: Failed to acquire next frame [0x"sv << util::hex(status).to_string_view() << ']' << std::endl; return status; } auto cleanup = util::fail_guard([&dup]() { dup->ReleaseFrame(); }); std::cout << "Frame acquired successfully." << std::endl; ComPtr<ID3D11Texture2D> frameTexture; status = frameResource->QueryInterface(IID_PPV_ARGS(&frameTexture)); if (FAILED(status)) { std::cout << "Error: Failed to query texture interface from frame resource [0x"sv << util::hex(status).to_string_view() << ']' << std::endl; return status; } D3D11_TEXTURE2D_DESC frameDesc; frameTexture->GetDesc(&frameDesc); frameDesc.Usage = D3D11_USAGE_STAGING; frameDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; frameDesc.BindFlags = 0; frameDesc.MiscFlags = 0; status = device->CreateTexture2D(&frameDesc, nullptr, &stagingTexture); if (FAILED(status)) { std::cout << "Error: Failed to create staging texture [0x"sv << util::hex(status).to_string_view() << ']' << std::endl; return status; } context->CopyResource(stagingTexture.Get(), frameTexture.Get()); D3D11_MAPPED_SUBRESOURCE mappedResource; status = context->Map(stagingTexture.Get(), 0, D3D11_MAP_READ, 0, &mappedResource); if (FAILED(status)) { std::cout << "Error: Failed to map the staging texture for inspection [0x"sv << util::hex(status).to_string_view() << ']' << std::endl; return status; } auto contextCleanup = util::fail_guard([&context, &stagingTexture]() { context->Unmap(stagingTexture.Get(), 0); }); if (is_valid_frame(mappedResource, frameDesc)) { std::cout << "Frame " << (i + 1) << " is non-empty (contains visible content)." << std::endl; return S_OK; } std::cout << "Frame " << (i + 1) << " is empty (no visible content)." << std::endl; } // All frames were empty, indicating potential capture issues. return E_FAIL; } HRESULT test_dxgi_duplication(dxgi::adapter_t &adapter, dxgi::output_t &output, bool verify_frame_capture) { D3D_FEATURE_LEVEL featureLevels[] { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1 }; dxgi::device_t device; auto status = D3D11CreateDevice( adapter.get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr, D3D11_CREATE_DEVICE_VIDEO_SUPPORT, featureLevels, sizeof(featureLevels) / sizeof(D3D_FEATURE_LEVEL), D3D11_SDK_VERSION, &device, nullptr, nullptr); if (FAILED(status)) { std::cout << "Failed to create D3D11 device for DD test [0x"sv << util::hex(status).to_string_view() << ']' << std::endl; return status; } dxgi::output1_t output1; status = output->QueryInterface(IID_IDXGIOutput1, (void **) &output1); if (FAILED(status)) { std::cout << "Failed to query IDXGIOutput1 from the output"sv << std::endl; return status; } // Ensure we can duplicate the current display syncThreadDesktop(); // Attempt to duplicate the output dxgi::dup_t dup; ComPtr<ID3D11Device> device_ptr(device.get()); HRESULT result = output1->DuplicateOutput(device_ptr.Get(), &dup); if (FAILED(result)) { std::cout << "Failed to duplicate output [0x"sv << util::hex(result).to_string_view() << "]" << std::endl; return result; } // To prevent false negatives, we'll make it optional to test for frame capture. if (verify_frame_capture) { HRESULT captureResult = test_frame_capture(dup, device_ptr.Get()); if (FAILED(captureResult)) { std::cout << "Frame capture test failed [0x"sv << util::hex(captureResult).to_string_view() << "]" << std::endl; return captureResult; } } return S_OK; } int main(int argc, char *argv[]) { HRESULT status; // Usage message if (argc < 2 || argc > 4) { std::cout << "Usage: ddprobe.exe [GPU preference value] [display name] [--verify-frame-capture]"sv << std::endl; return -1; } std::wstring display_name; bool verify_frame_capture = false; // Parse GPU preference value (required) int gpu_preference = atoi(argv[1]); // Parse optional arguments for (int i = 2; i < argc; ++i) { std::string arg = argv[i]; if (arg == "--verify-frame-capture") { verify_frame_capture = true; } else { // Assume any other argument is the display name std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> converter; display_name = converter.from_bytes(arg); } } // We must set the GPU preference before making any DXGI/D3D calls status = set_gpu_preference(gpu_preference); if (status != ERROR_SUCCESS) { return status; } // Remove the GPU preference when we're done auto reset_gpu = util::fail_guard([]() { WCHAR tool_path[MAX_PATH]; GetModuleFileNameW(NULL, tool_path, ARRAYSIZE(tool_path)); RegDeleteKeyValueW(HKEY_CURRENT_USER, L"Software\\Microsoft\\DirectX\\UserGpuPreferences", tool_path); }); dxgi::factory1_t factory; status = CreateDXGIFactory1(IID_IDXGIFactory1, (void **) &factory); if (FAILED(status)) { std::cout << "Failed to create DXGIFactory1 [0x"sv << util::hex(status).to_string_view() << ']' << std::endl; return status; } dxgi::adapter_t::pointer adapter_p {}; for (int x = 0; factory->EnumAdapters1(x, &adapter_p) != DXGI_ERROR_NOT_FOUND; ++x) { dxgi::adapter_t adapter { adapter_p }; dxgi::output_t::pointer output_p {}; for (int y = 0; adapter->EnumOutputs(y, &output_p) != DXGI_ERROR_NOT_FOUND; ++y) { dxgi::output_t output { output_p }; DXGI_OUTPUT_DESC desc; output->GetDesc(&desc); // If a display name was specified and this one doesn't match, skip it if (!display_name.empty() && desc.DeviceName != display_name) { continue; } // If this display is not part of the desktop, we definitely can't capture it if (!desc.AttachedToDesktop) { continue; } // We found the matching output. Test it and return the result. return test_dxgi_duplication(adapter, output, verify_frame_capture); } } return 0; }
12,134
C++
.cpp
279
39.336918
198
0.694153
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,954
tests_main.cpp
LizardByte_Sunshine/tests/tests_main.cpp
/** * @file tests/tests_main.cpp * @brief Entry point definition. */ #include "tests_common.h" #include "tests_environment.h" #include "tests_events.h" int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); testing::AddGlobalTestEnvironment(new SunshineEnvironment); testing::UnitTest::GetInstance()->listeners().Append(new SunshineEventListener); return RUN_ALL_TESTS(); }
403
C++
.cpp
14
26.928571
82
0.757732
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,955
test_network.cpp
LizardByte_Sunshine/tests/unit/test_network.cpp
/** * @file tests/unit/test_network.cpp * @brief Test src/network.* */ #include <src/network.h> #include "../tests_common.h" struct MdnsInstanceNameTest: testing::TestWithParam<std::tuple<std::string, std::string>> {}; TEST_P(MdnsInstanceNameTest, Run) { auto [input, expected] = GetParam(); ASSERT_EQ(net::mdns_instance_name(input), expected); } INSTANTIATE_TEST_SUITE_P( MdnsInstanceNameTests, MdnsInstanceNameTest, testing::Values( std::make_tuple("shortname-123", "shortname-123"), std::make_tuple("space 123", "space-123"), std::make_tuple("hostname.domain.test", "hostname"), std::make_tuple("&", "Sunshine"), std::make_tuple("", "Sunshine"), std::make_tuple("ğŸ˜", "Sunshine"), std::make_tuple(std::string(128, 'a'), std::string(63, 'a'))));
795
C++
.cpp
22
33.045455
93
0.682292
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,956
test_audio.cpp
LizardByte_Sunshine/tests/unit/test_audio.cpp
/** * @file tests/unit/test_audio.cpp * @brief Test src/audio.*. */ #include <src/audio.h> #include "../tests_common.h" using namespace audio; struct AudioTest: PlatformTestSuite, testing::WithParamInterface<std::tuple<std::basic_string_view<char>, config_t>> { void SetUp() override { m_config = std::get<1>(GetParam()); m_mail = std::make_shared<safe::mail_raw_t>(); } config_t m_config; safe::mail_t m_mail; }; constexpr std::bitset<config_t::MAX_FLAGS> config_flags(int flag = -1) { std::bitset<3> result = std::bitset<config_t::MAX_FLAGS>(); if (flag >= 0) { result.set(flag); } return result; } INSTANTIATE_TEST_SUITE_P( Configurations, AudioTest, testing::Values( std::make_tuple("HIGH_STEREO", config_t { 5, 2, 0x3, { 0 }, config_flags(config_t::HIGH_QUALITY) }), std::make_tuple("SURROUND51", config_t { 5, 6, 0x3F, { 0 }, config_flags() }), std::make_tuple("SURROUND71", config_t { 5, 8, 0x63F, { 0 }, config_flags() }), std::make_tuple("SURROUND51_CUSTOM", config_t { 5, 6, 0x3F, { 6, 4, 2, { 0, 1, 4, 5, 2, 3 } }, config_flags(config_t::CUSTOM_SURROUND_PARAMS) })), [](const auto &info) { return std::string(std::get<0>(info.param)); }); TEST_P(AudioTest, TestEncode) { std::thread timer([&] { // Terminate the audio capture after 5 seconds. std::this_thread::sleep_for(5s); auto shutdown_event = m_mail->event<bool>(mail::shutdown); auto audio_packets = m_mail->queue<packet_t>(mail::audio_packets); shutdown_event->raise(true); audio_packets->stop(); }); std::thread capture([&] { auto packets = m_mail->queue<packet_t>(mail::audio_packets); auto shutdown_event = m_mail->event<bool>(mail::shutdown); while (auto packet = packets->pop()) { if (shutdown_event->peek()) { break; } auto packet_data = packet->second; if (packet_data.size() == 0) { FAIL() << "Empty packet data"; } } }); audio::capture(m_mail, m_config, nullptr); timer.join(); capture.join(); }
2,038
C++
.cpp
59
30.745763
150
0.635211
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,957
test_mouse.cpp
LizardByte_Sunshine/tests/unit/test_mouse.cpp
/** * @file tests/unit/test_mouse.cpp * @brief Test src/input.*. */ #include <src/input.h> #include "../tests_common.h" struct MouseHIDTest: PlatformTestSuite, testing::WithParamInterface<util::point_t> { void SetUp() override { #ifdef _WIN32 // TODO: Windows tests are failing, `get_mouse_loc` seems broken and `platf::abs_mouse` too // the alternative `platf::abs_mouse` method seem to work better during tests, // but I'm not sure about real work GTEST_SKIP() << "TODO Windows"; #elif __linux__ // TODO: Inputtino waiting https://github.com/games-on-whales/inputtino/issues/6 is resolved. GTEST_SKIP() << "TODO Inputtino"; #endif } void TearDown() override { std::this_thread::sleep_for(std::chrono::milliseconds(200)); } }; INSTANTIATE_TEST_SUITE_P( MouseInputs, MouseHIDTest, testing::Values( util::point_t { 40, 40 }, util::point_t { 70, 150 })); // todo: add tests for hitting screen edges TEST_P(MouseHIDTest, MoveInputTest) { util::point_t mouse_delta = GetParam(); BOOST_LOG(tests) << "MoveInputTest:: got param: " << mouse_delta; platf::input_t input = platf::input(); BOOST_LOG(tests) << "MoveInputTest:: init input"; BOOST_LOG(tests) << "MoveInputTest:: get current mouse loc"; auto old_loc = platf::get_mouse_loc(input); BOOST_LOG(tests) << "MoveInputTest:: got current mouse loc: " << old_loc; BOOST_LOG(tests) << "MoveInputTest:: move: " << mouse_delta; platf::move_mouse(input, mouse_delta.x, mouse_delta.y); std::this_thread::sleep_for(std::chrono::milliseconds(200)); BOOST_LOG(tests) << "MoveInputTest:: moved: " << mouse_delta; BOOST_LOG(tests) << "MoveInputTest:: get updated mouse loc"; auto new_loc = platf::get_mouse_loc(input); BOOST_LOG(tests) << "MoveInputTest:: got updated mouse loc: " << new_loc; bool has_input_moved = old_loc.x != new_loc.x && old_loc.y != new_loc.y; if (!has_input_moved) { BOOST_LOG(tests) << "MoveInputTest:: haven't moved"; } else { BOOST_LOG(tests) << "MoveInputTest:: moved"; } EXPECT_TRUE(has_input_moved); // Verify we moved as much as we requested EXPECT_EQ(new_loc.x - old_loc.x, mouse_delta.x); EXPECT_EQ(new_loc.y - old_loc.y, mouse_delta.y); } TEST_P(MouseHIDTest, AbsMoveInputTest) { util::point_t mouse_pos = GetParam(); BOOST_LOG(tests) << "AbsMoveInputTest:: got param: " << mouse_pos; platf::input_t input = platf::input(); BOOST_LOG(tests) << "AbsMoveInputTest:: init input"; BOOST_LOG(tests) << "AbsMoveInputTest:: get current mouse loc"; auto old_loc = platf::get_mouse_loc(input); BOOST_LOG(tests) << "AbsMoveInputTest:: got current mouse loc: " << old_loc; #ifdef _WIN32 platf::touch_port_t abs_port { 0, 0, 65535, 65535 }; #elif __linux__ platf::touch_port_t abs_port { 0, 0, 19200, 12000 }; #else platf::touch_port_t abs_port {}; #endif BOOST_LOG(tests) << "AbsMoveInputTest:: move: " << mouse_pos; platf::abs_mouse(input, abs_port, mouse_pos.x, mouse_pos.y); std::this_thread::sleep_for(std::chrono::milliseconds(200)); BOOST_LOG(tests) << "AbsMoveInputTest:: moved: " << mouse_pos; BOOST_LOG(tests) << "AbsMoveInputTest:: get updated mouse loc"; auto new_loc = platf::get_mouse_loc(input); BOOST_LOG(tests) << "AbsMoveInputTest:: got updated mouse loc: " << new_loc; bool has_input_moved = old_loc.x != new_loc.x || old_loc.y != new_loc.y; if (!has_input_moved) { BOOST_LOG(tests) << "AbsMoveInputTest:: haven't moved"; } else { BOOST_LOG(tests) << "AbsMoveInputTest:: moved"; } EXPECT_TRUE(has_input_moved); // Verify we moved to the absolute coordinate EXPECT_EQ(new_loc.x, mouse_pos.x); EXPECT_EQ(new_loc.y, mouse_pos.y); }
3,729
C++
.cpp
98
34.877551
97
0.674979
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,958
test_file_handler.cpp
LizardByte_Sunshine/tests/unit/test_file_handler.cpp
/** * @file tests/unit/test_file_handler.cpp * @brief Test src/file_handler.*. */ #include <src/file_handler.h> #include "../tests_common.h" struct FileHandlerParentDirectoryTest: testing::TestWithParam<std::tuple<std::string, std::string>> {}; TEST_P(FileHandlerParentDirectoryTest, Run) { auto [input, expected] = GetParam(); EXPECT_EQ(file_handler::get_parent_directory(input), expected); } INSTANTIATE_TEST_SUITE_P( FileHandlerTests, FileHandlerParentDirectoryTest, testing::Values( std::make_tuple("/path/to/file.txt", "/path/to"), std::make_tuple("/path/to/directory", "/path/to"), std::make_tuple("/path/to/directory/", "/path/to"))); struct FileHandlerMakeDirectoryTest: testing::TestWithParam<std::tuple<std::string, bool, bool>> {}; TEST_P(FileHandlerMakeDirectoryTest, Run) { auto [input, expected, remove] = GetParam(); const std::string test_dir = platf::appdata().string() + "/tests/path/"; input = test_dir + input; EXPECT_EQ(file_handler::make_directory(input), expected); EXPECT_TRUE(std::filesystem::exists(input)); // remove test directory if (remove) { std::filesystem::remove_all(test_dir); EXPECT_FALSE(std::filesystem::exists(test_dir)); } } INSTANTIATE_TEST_SUITE_P( FileHandlerTests, FileHandlerMakeDirectoryTest, testing::Values( std::make_tuple("dir_123", true, false), std::make_tuple("dir_123", true, true), std::make_tuple("dir_123/abc", true, false), std::make_tuple("dir_123/abc", true, true))); struct FileHandlerTests: testing::TestWithParam<std::tuple<int, std::string>> {}; INSTANTIATE_TEST_SUITE_P( TestFiles, FileHandlerTests, testing::Values( std::make_tuple(0, ""), // empty file std::make_tuple(1, "a"), // single character std::make_tuple(2, "Mr. Blue Sky - Electric Light Orchestra"), // single line std::make_tuple(3, R"( Morning! Today's forecast calls for blue skies The sun is shining in the sky There ain't a cloud in sight It's stopped raining Everybody's in the play And don't you know, it's a beautiful new day Hey, hey, hey! Running down the avenue See how the sun shines brightly in the city All the streets where once was pity Mr. Blue Sky is living here today! Hey, hey, hey! )") // multi-line )); TEST_P(FileHandlerTests, WriteFileTest) { auto [fileNum, content] = GetParam(); std::string fileName = "write_file_test_" + std::to_string(fileNum) + ".txt"; EXPECT_EQ(file_handler::write_file(fileName.c_str(), content), 0); } TEST_P(FileHandlerTests, ReadFileTest) { auto [fileNum, content] = GetParam(); std::string fileName = "write_file_test_" + std::to_string(fileNum) + ".txt"; EXPECT_EQ(file_handler::read_file(fileName.c_str()), content); } TEST(FileHandlerTests, ReadMissingFileTest) { // read missing file EXPECT_EQ(file_handler::read_file("non-existing-file.txt"), ""); }
2,871
C++
.cpp
76
35.052632
103
0.713053
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,959
test_rswrapper.cpp
LizardByte_Sunshine/tests/unit/test_rswrapper.cpp
/** * @file tests/unit/test_rswrapper.cpp * @brief Test src/rswrapper.* */ extern "C" { #include <src/rswrapper.h> } #include "../tests_common.h" TEST(ReedSolomonWrapperTests, InitTest) { reed_solomon_init(); // Ensure all function pointers were populated ASSERT_NE(reed_solomon_new, nullptr); ASSERT_NE(reed_solomon_release, nullptr); ASSERT_NE(reed_solomon_encode, nullptr); ASSERT_NE(reed_solomon_decode, nullptr); } TEST(ReedSolomonWrapperTests, EncodeTest) { reed_solomon_init(); auto rs = reed_solomon_new(1, 1); ASSERT_NE(rs, nullptr); uint8_t dataShard[16] = {}; uint8_t fecShard[16] = {}; // If we picked the incorrect ISA in our wrapper, we should crash here uint8_t *shardPtrs[2] = { dataShard, fecShard }; auto ret = reed_solomon_encode(rs, shardPtrs, 2, sizeof(dataShard)); ASSERT_EQ(ret, 0); reed_solomon_release(rs); }
877
C++
.cpp
28
28.785714
72
0.718193
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,960
test_entry_handler.cpp
LizardByte_Sunshine/tests/unit/test_entry_handler.cpp
/** * @file tests/unit/test_entry_handler.cpp * @brief Test src/entry_handler.*. */ #include <src/entry_handler.h> #include "../tests_common.h" #include "../tests_log_checker.h" TEST(EntryHandlerTests, LogPublisherDataTest) { // call log_publisher_data log_publisher_data(); // check if specific log messages exist ASSERT_TRUE(log_checker::line_starts_with("test_sunshine.log", "Info: Package Publisher: ")); ASSERT_TRUE(log_checker::line_starts_with("test_sunshine.log", "Info: Publisher Website: ")); ASSERT_TRUE(log_checker::line_starts_with("test_sunshine.log", "Info: Get support: ")); }
611
C++
.cpp
15
38.533333
95
0.725126
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,961
test_httpcommon.cpp
LizardByte_Sunshine/tests/unit/test_httpcommon.cpp
/** * @file tests/unit/test_httpcommon.cpp * @brief Test src/httpcommon.*. */ #include <src/httpcommon.h> #include "../tests_common.h" struct UrlEscapeTest: testing::TestWithParam<std::tuple<std::string, std::string>> {}; TEST_P(UrlEscapeTest, Run) { auto [input, expected] = GetParam(); ASSERT_EQ(http::url_escape(input), expected); } INSTANTIATE_TEST_SUITE_P( UrlEscapeTests, UrlEscapeTest, testing::Values( std::make_tuple("igdb_0123456789", "igdb_0123456789"), std::make_tuple("../../../", "..%2F..%2F..%2F"), std::make_tuple("..*\\", "..%2A%5C"))); struct UrlGetHostTest: testing::TestWithParam<std::tuple<std::string, std::string>> {}; TEST_P(UrlGetHostTest, Run) { auto [input, expected] = GetParam(); ASSERT_EQ(http::url_get_host(input), expected); } INSTANTIATE_TEST_SUITE_P( UrlGetHostTests, UrlGetHostTest, testing::Values( std::make_tuple("https://images.igdb.com/example.txt", "images.igdb.com"), std::make_tuple("http://localhost:8080", "localhost"), std::make_tuple("nonsense!!}{::", ""))); struct DownloadFileTest: testing::TestWithParam<std::tuple<std::string, std::string>> {}; TEST_P(DownloadFileTest, Run) { auto [url, filename] = GetParam(); const std::string test_dir = platf::appdata().string() + "/tests/"; std::basic_string path = test_dir + filename; ASSERT_TRUE(http::download_file(url, path)); } #ifdef SUNSHINE_BUILD_FLATPAK // requires running `npm run serve` prior to running the tests constexpr const char *URL_1 = "http://0.0.0.0:3000/hello.txt"; constexpr const char *URL_2 = "http://0.0.0.0:3000/hello-redirect.txt"; #else constexpr const char *URL_1 = "https://httpbin.org/base64/aGVsbG8h"; constexpr const char *URL_2 = "https://httpbin.org/redirect-to?url=/base64/aGVsbG8h"; #endif INSTANTIATE_TEST_SUITE_P( DownloadFileTests, DownloadFileTest, testing::Values( std::make_tuple(URL_1, "hello.txt"), std::make_tuple(URL_2, "hello-redirect.txt")));
1,965
C++
.cpp
51
35.960784
89
0.699422
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,962
test_logging.cpp
LizardByte_Sunshine/tests/unit/test_logging.cpp
/** * @file tests/unit/test_logging.cpp * @brief Test src/logging.*. */ #include <src/logging.h> #include "../tests_common.h" #include "../tests_log_checker.h" #include <random> namespace { std::array log_levels = { std::tuple("verbose", &verbose), std::tuple("debug", &debug), std::tuple("info", &info), std::tuple("warning", &warning), std::tuple("error", &error), std::tuple("fatal", &fatal), }; constexpr auto log_file = "test_sunshine.log"; } // namespace struct LogLevelsTest: testing::TestWithParam<decltype(log_levels)::value_type> {}; INSTANTIATE_TEST_SUITE_P( Logging, LogLevelsTest, testing::ValuesIn(log_levels), [](const auto &info) { return std::string(std::get<0>(info.param)); }); TEST_P(LogLevelsTest, PutMessage) { auto [label, plogger] = GetParam(); ASSERT_TRUE(plogger); auto &logger = *plogger; std::random_device rand_dev; std::mt19937_64 rand_gen(rand_dev()); auto test_message = std::to_string(rand_gen()) + std::to_string(rand_gen()); BOOST_LOG(logger) << test_message; ASSERT_TRUE(log_checker::line_contains(log_file, test_message)); }
1,129
C++
.cpp
35
29.371429
82
0.679263
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,963
test_video.cpp
LizardByte_Sunshine/tests/unit/test_video.cpp
/** * @file tests/unit/test_video.cpp * @brief Test src/video.*. */ #include <src/video.h> #include "../tests_common.h" struct EncoderTest: PlatformTestSuite, testing::WithParamInterface<video::encoder_t *> { void SetUp() override { auto &encoder = *GetParam(); if (!video::validate_encoder(encoder, false)) { // Encoder failed validation, // if it's software - fail (unless overriden with compile definition), otherwise skip if (encoder.name == "software" && std::string(TESTS_SOFTWARE_ENCODER_UNAVAILABLE) == "fail") { FAIL() << "Software encoder not available"; } else { GTEST_SKIP() << "Encoder not available"; } } } }; INSTANTIATE_TEST_SUITE_P( EncoderVariants, EncoderTest, testing::Values( #if !defined(__APPLE__) &video::nvenc, #endif #ifdef _WIN32 &video::amdvce, &video::quicksync, #endif #ifdef __linux__ &video::vaapi, #endif #ifdef __APPLE__ &video::videotoolbox, #endif &video::software), [](const auto &info) { return std::string(info.param->name); }); TEST_P(EncoderTest, ValidateEncoder) { // todo:: test something besides fixture setup }
1,167
C++
.cpp
44
23
100
0.663986
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,964
test_stream.cpp
LizardByte_Sunshine/tests/unit/test_stream.cpp
/** * @file tests/unit/test_stream.cpp * @brief Test src/stream.* */ #include <cstdint> #include <functional> #include <string> #include <vector> namespace stream { std::vector<uint8_t> concat_and_insert(uint64_t insert_size, uint64_t slice_size, const std::string_view &data1, const std::string_view &data2); } #include "../tests_common.h" TEST(ConcatAndInsertTests, ConcatNoInsertionTest) { char b1[] = { 'a', 'b' }; char b2[] = { 'c', 'd', 'e' }; auto res = stream::concat_and_insert(0, 2, std::string_view { b1, sizeof(b1) }, std::string_view { b2, sizeof(b2) }); auto expected = std::vector<uint8_t> { 'a', 'b', 'c', 'd', 'e' }; ASSERT_EQ(res, expected); } TEST(ConcatAndInsertTests, ConcatLargeStrideTest) { char b1[] = { 'a', 'b' }; char b2[] = { 'c', 'd', 'e' }; auto res = stream::concat_and_insert(1, sizeof(b1) + sizeof(b2) + 1, std::string_view { b1, sizeof(b1) }, std::string_view { b2, sizeof(b2) }); auto expected = std::vector<uint8_t> { 0, 'a', 'b', 'c', 'd', 'e' }; ASSERT_EQ(res, expected); } TEST(ConcatAndInsertTests, ConcatSmallStrideTest) { char b1[] = { 'a', 'b' }; char b2[] = { 'c', 'd', 'e' }; auto res = stream::concat_and_insert(1, 1, std::string_view { b1, sizeof(b1) }, std::string_view { b2, sizeof(b2) }); auto expected = std::vector<uint8_t> { 0, 'a', 0, 'b', 0, 'c', 0, 'd', 0, 'e' }; ASSERT_EQ(res, expected); }
1,391
C++
.cpp
34
38.647059
145
0.61658
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,965
test_common.cpp
LizardByte_Sunshine/tests/unit/platform/test_common.cpp
/** * @file tests/unit/platform/test_common.cpp * @brief Test src/platform/common.*. */ #include <src/platform/common.h> #include <boost/asio/ip/host_name.hpp> #include "../../tests_common.h" struct SetEnvTest: ::testing::TestWithParam<std::tuple<std::string, std::string, int>> { protected: void TearDown() override { // Clean up environment variable after each test const auto &[name, value, expected] = GetParam(); platf::unset_env(name); } }; TEST_P(SetEnvTest, SetEnvironmentVariableTests) { const auto &[name, value, expected] = GetParam(); platf::set_env(name, value); const char *env_value = std::getenv(name.c_str()); if (expected == 0 && !value.empty()) { ASSERT_NE(env_value, nullptr); ASSERT_EQ(std::string(env_value), value); } else { ASSERT_EQ(env_value, nullptr); } } TEST_P(SetEnvTest, UnsetEnvironmentVariableTests) { const auto &[name, value, expected] = GetParam(); platf::unset_env(name); const char *env_value = std::getenv(name.c_str()); if (expected == 0) { ASSERT_EQ(env_value, nullptr); } } INSTANTIATE_TEST_SUITE_P( SetEnvTests, SetEnvTest, ::testing::Values( std::make_tuple("SUNSHINE_UNIT_TEST_ENV_VAR", "test_value_0", 0), std::make_tuple("SUNSHINE_UNIT_TEST_ENV_VAR", "test_value_1", 0), std::make_tuple("", "test_value", -1))); TEST(HostnameTests, TestAsioEquality) { // These should be equivalent on all platforms for ASCII hostnames ASSERT_EQ(platf::get_host_name(), boost::asio::ip::host_name()); }
1,525
C++
.cpp
47
29.489362
88
0.686181
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,966
httpcommon.cpp
LizardByte_Sunshine/src/httpcommon.cpp
/** * @file src/httpcommon.cpp * @brief Definitions for common HTTP. */ #define BOOST_BIND_GLOBAL_PLACEHOLDERS #include "process.h" #include <filesystem> #include <utility> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/asio/ssl/context.hpp> #include <Simple-Web-Server/server_http.hpp> #include <Simple-Web-Server/server_https.hpp> #include <boost/asio/ssl/context_base.hpp> #include <curl/curl.h> #include "config.h" #include "crypto.h" #include "file_handler.h" #include "httpcommon.h" #include "logging.h" #include "network.h" #include "nvhttp.h" #include "platform/common.h" #include "rtsp.h" #include "utility.h" #include "uuid.h" namespace http { using namespace std::literals; namespace fs = std::filesystem; namespace pt = boost::property_tree; int reload_user_creds(const std::string &file); bool user_creds_exist(const std::string &file); std::string unique_id; net::net_e origin_web_ui_allowed; int init() { bool clean_slate = config::sunshine.flags[config::flag::FRESH_STATE]; origin_web_ui_allowed = net::from_enum_string(config::nvhttp.origin_web_ui_allowed); if (clean_slate) { unique_id = uuid_util::uuid_t::generate().string(); auto dir = std::filesystem::temp_directory_path() / "Sunshine"sv; config::nvhttp.cert = (dir / ("cert-"s + unique_id)).string(); config::nvhttp.pkey = (dir / ("pkey-"s + unique_id)).string(); } if (!fs::exists(config::nvhttp.pkey) || !fs::exists(config::nvhttp.cert)) { if (create_creds(config::nvhttp.pkey, config::nvhttp.cert)) { return -1; } } if (user_creds_exist(config::sunshine.credentials_file)) { if (reload_user_creds(config::sunshine.credentials_file)) return -1; } else { BOOST_LOG(info) << "Open the Web UI to set your new username and password and getting started"; } return 0; } int save_user_creds(const std::string &file, const std::string &username, const std::string &password, bool run_our_mouth) { pt::ptree outputTree; if (fs::exists(file)) { try { pt::read_json(file, outputTree); } catch (std::exception &e) { BOOST_LOG(error) << "Couldn't read user credentials: "sv << e.what(); return -1; } } auto salt = crypto::rand_alphabet(16); outputTree.put("username", username); outputTree.put("salt", salt); outputTree.put("password", util::hex(crypto::hash(password + salt)).to_string()); try { pt::write_json(file, outputTree); } catch (std::exception &e) { BOOST_LOG(error) << "error writing to the credentials file, perhaps try this again as an administrator? Details: "sv << e.what(); return -1; } BOOST_LOG(info) << "New credentials have been created"sv; return 0; } bool user_creds_exist(const std::string &file) { if (!fs::exists(file)) { return false; } pt::ptree inputTree; try { pt::read_json(file, inputTree); return inputTree.find("username") != inputTree.not_found() && inputTree.find("password") != inputTree.not_found() && inputTree.find("salt") != inputTree.not_found(); } catch (std::exception &e) { BOOST_LOG(error) << "validating user credentials: "sv << e.what(); } return false; } int reload_user_creds(const std::string &file) { pt::ptree inputTree; try { pt::read_json(file, inputTree); config::sunshine.username = inputTree.get<std::string>("username"); config::sunshine.password = inputTree.get<std::string>("password"); config::sunshine.salt = inputTree.get<std::string>("salt"); } catch (std::exception &e) { BOOST_LOG(error) << "loading user credentials: "sv << e.what(); return -1; } return 0; } int create_creds(const std::string &pkey, const std::string &cert) { fs::path pkey_path = pkey; fs::path cert_path = cert; auto creds = crypto::gen_creds("Sunshine Gamestream Host"sv, 2048); auto pkey_dir = pkey_path; auto cert_dir = cert_path; pkey_dir.remove_filename(); cert_dir.remove_filename(); std::error_code err_code {}; fs::create_directories(pkey_dir, err_code); if (err_code) { BOOST_LOG(error) << "Couldn't create directory ["sv << pkey_dir << "] :"sv << err_code.message(); return -1; } fs::create_directories(cert_dir, err_code); if (err_code) { BOOST_LOG(error) << "Couldn't create directory ["sv << cert_dir << "] :"sv << err_code.message(); return -1; } if (file_handler::write_file(pkey.c_str(), creds.pkey)) { BOOST_LOG(error) << "Couldn't open ["sv << config::nvhttp.pkey << ']'; return -1; } if (file_handler::write_file(cert.c_str(), creds.x509)) { BOOST_LOG(error) << "Couldn't open ["sv << config::nvhttp.cert << ']'; return -1; } fs::permissions(pkey_path, fs::perms::owner_read | fs::perms::owner_write, fs::perm_options::replace, err_code); if (err_code) { BOOST_LOG(error) << "Couldn't change permissions of ["sv << config::nvhttp.pkey << "] :"sv << err_code.message(); return -1; } fs::permissions(cert_path, fs::perms::owner_read | fs::perms::group_read | fs::perms::others_read | fs::perms::owner_write, fs::perm_options::replace, err_code); if (err_code) { BOOST_LOG(error) << "Couldn't change permissions of ["sv << config::nvhttp.cert << "] :"sv << err_code.message(); return -1; } return 0; } bool download_file(const std::string &url, const std::string &file) { CURL *curl = curl_easy_init(); if (curl) { // sonar complains about weak ssl and tls versions // ideally, the setopts should go after the early returns; however sonar cannot detect the fix curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); } else { BOOST_LOG(error) << "Couldn't create CURL instance"; return false; } std::string file_dir = file_handler::get_parent_directory(file); if (!file_handler::make_directory(file_dir)) { BOOST_LOG(error) << "Couldn't create directory ["sv << file_dir << ']'; curl_easy_cleanup(curl); return false; } FILE *fp = fopen(file.c_str(), "wb"); if (!fp) { BOOST_LOG(error) << "Couldn't open ["sv << file << ']'; curl_easy_cleanup(curl); return false; } curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); CURLcode result = curl_easy_perform(curl); if (result != CURLE_OK) { BOOST_LOG(error) << "Couldn't download ["sv << url << ", code:" << result << ']'; } curl_easy_cleanup(curl); fclose(fp); return result == CURLE_OK; } std::string url_escape(const std::string &url) { CURL *curl = curl_easy_init(); char *string = curl_easy_escape(curl, url.c_str(), url.length()); std::string result(string); curl_free(string); curl_easy_cleanup(curl); return result; } std::string url_get_host(const std::string &url) { CURLU *curlu = curl_url(); curl_url_set(curlu, CURLUPART_URL, url.c_str(), url.length()); char *host; if (curl_url_get(curlu, CURLUPART_HOST, &host, 0) != CURLUE_OK) { curl_url_cleanup(curlu); return ""; } std::string result(host); curl_free(host); curl_url_cleanup(curlu); return result; } } // namespace http
7,658
C++
.cpp
221
29.624434
135
0.634803
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,967
logging.cpp
LizardByte_Sunshine/src/logging.cpp
/** * @file src/logging.cpp * @brief Definitions for logging related functions. */ // standard includes #include <fstream> #include <iomanip> #include <iostream> // lib includes #include <boost/core/null_deleter.hpp> #include <boost/format.hpp> #include <boost/log/attributes/clock.hpp> #include <boost/log/common.hpp> #include <boost/log/expressions.hpp> #include <boost/log/sinks.hpp> #include <boost/log/sources/severity_logger.hpp> // local includes #include "logging.h" extern "C" { #include <libavutil/log.h> } using namespace std::literals; namespace bl = boost::log; boost::shared_ptr<boost::log::sinks::asynchronous_sink<boost::log::sinks::text_ostream_backend>> sink; bl::sources::severity_logger<int> verbose(0); // Dominating output bl::sources::severity_logger<int> debug(1); // Follow what is happening bl::sources::severity_logger<int> info(2); // Should be informed about bl::sources::severity_logger<int> warning(3); // Strange events bl::sources::severity_logger<int> error(4); // Recoverable errors bl::sources::severity_logger<int> fatal(5); // Unrecoverable errors #ifdef SUNSHINE_TESTS bl::sources::severity_logger<int> tests(10); // Automatic tests output #endif BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", int) namespace logging { deinit_t::~deinit_t() { deinit(); } void deinit() { log_flush(); bl::core::get()->remove_sink(sink); sink.reset(); } void formatter(const boost::log::record_view &view, boost::log::formatting_ostream &os) { constexpr const char *message = "Message"; constexpr const char *severity = "Severity"; auto log_level = view.attribute_values()[severity].extract<int>().get(); std::string_view log_type; switch (log_level) { case 0: log_type = "Verbose: "sv; break; case 1: log_type = "Debug: "sv; break; case 2: log_type = "Info: "sv; break; case 3: log_type = "Warning: "sv; break; case 4: log_type = "Error: "sv; break; case 5: log_type = "Fatal: "sv; break; #ifdef SUNSHINE_TESTS case 10: log_type = "Tests: "sv; break; #endif }; auto now = std::chrono::system_clock::now(); auto ms = std::chrono::duration_cast<std::chrono::milliseconds>( now - std::chrono::time_point_cast<std::chrono::seconds>(now)); auto t = std::chrono::system_clock::to_time_t(now); auto lt = *std::localtime(&t); os << "["sv << std::put_time(&lt, "%Y-%m-%d %H:%M:%S.") << boost::format("%03u") % ms.count() << "]: "sv << log_type << view.attribute_values()[message].extract<std::string>(); } [[nodiscard]] std::unique_ptr<deinit_t> init(int min_log_level, const std::string &log_file) { if (sink) { // Deinitialize the logging system before reinitializing it. This can probably only ever be hit in tests. deinit(); } setup_av_logging(min_log_level); sink = boost::make_shared<text_sink>(); #ifndef SUNSHINE_TESTS boost::shared_ptr<std::ostream> stream { &std::cout, boost::null_deleter() }; sink->locked_backend()->add_stream(stream); #endif sink->locked_backend()->add_stream(boost::make_shared<std::ofstream>(log_file)); sink->set_filter(severity >= min_log_level); sink->set_formatter(&formatter); // Flush after each log record to ensure log file contents on disk isn't stale. // This is particularly important when running from a Windows service. sink->locked_backend()->auto_flush(true); bl::core::get()->add_sink(sink); return std::make_unique<deinit_t>(); } void setup_av_logging(int min_log_level) { if (min_log_level >= 1) { av_log_set_level(AV_LOG_QUIET); } else { av_log_set_level(AV_LOG_DEBUG); } av_log_set_callback([](void *ptr, int level, const char *fmt, va_list vl) { static int print_prefix = 1; char buffer[1024]; av_log_format_line(ptr, level, fmt, vl, buffer, sizeof(buffer), &print_prefix); if (level <= AV_LOG_ERROR) { // We print AV_LOG_FATAL at the error level. FFmpeg prints things as fatal that // are expected in some cases, such as lack of codec support or similar things. BOOST_LOG(error) << buffer; } else if (level <= AV_LOG_WARNING) { BOOST_LOG(warning) << buffer; } else if (level <= AV_LOG_INFO) { BOOST_LOG(info) << buffer; } else if (level <= AV_LOG_VERBOSE) { // AV_LOG_VERBOSE is less verbose than AV_LOG_DEBUG BOOST_LOG(debug) << buffer; } else { BOOST_LOG(verbose) << buffer; } }); } void log_flush() { if (sink) { sink->flush(); } } void print_help(const char *name) { std::cout << "Usage: "sv << name << " [options] [/path/to/configuration_file] [--cmd]"sv << std::endl << " Any configurable option can be overwritten with: \"name=value\""sv << std::endl << std::endl << " Note: The configuration will be created if it doesn't exist."sv << std::endl << std::endl << " --help | print help"sv << std::endl << " --creds username password | set user credentials for the Web manager"sv << std::endl << " --version | print the version of sunshine"sv << std::endl << std::endl << " flags"sv << std::endl << " -0 | Read PIN from stdin"sv << std::endl << " -1 | Do not load previously saved state and do retain any state after shutdown"sv << std::endl << " | Effectively starting as if for the first time without overwriting any pairings with your devices"sv << std::endl << " -2 | Force replacement of headers in video stream"sv << std::endl << " -p | Enable/Disable UPnP"sv << std::endl << std::endl; } std::string bracket(const std::string &input) { return "["s + input + "]"s; } std::wstring bracket(const std::wstring &input) { return L"["s + input + L"]"s; } } // namespace logging
6,131
C++
.cpp
171
30.883041
135
0.622661
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,968
entry_handler.cpp
LizardByte_Sunshine/src/entry_handler.cpp
/** * @file entry_handler.cpp * @brief Definitions for entry handling functions. */ // standard includes #include <csignal> #include <iostream> #include <thread> // local includes #include "config.h" #include "confighttp.h" #include "entry_handler.h" #include "globals.h" #include "httpcommon.h" #include "logging.h" #include "network.h" #include "platform/common.h" #include "version.h" extern "C" { #ifdef _WIN32 #include <iphlpapi.h> #endif } using namespace std::literals; void launch_ui() { std::string url = "https://localhost:" + std::to_string(net::map_port(confighttp::PORT_HTTPS)); platf::open_url(url); } void launch_ui_with_path(std::string path) { std::string url = "https://localhost:" + std::to_string(net::map_port(confighttp::PORT_HTTPS)) + path; platf::open_url(url); } namespace args { int creds(const char *name, int argc, char *argv[]) { if (argc < 2 || argv[0] == "help"sv || argv[1] == "help"sv) { help(name); } http::save_user_creds(config::sunshine.credentials_file, argv[0], argv[1]); return 0; } int help(const char *name) { logging::print_help(name); return 0; } int version() { // version was already logged at startup return 0; } #ifdef _WIN32 int restore_nvprefs_undo() { if (nvprefs_instance.load()) { nvprefs_instance.restore_from_and_delete_undo_file_if_exists(); nvprefs_instance.unload(); } return 0; } #endif } // namespace args namespace lifetime { char **argv; std::atomic_int desired_exit_code; void exit_sunshine(int exit_code, bool async) { // Store the exit code of the first exit_sunshine() call int zero = 0; desired_exit_code.compare_exchange_strong(zero, exit_code); // Raise SIGINT to start termination std::raise(SIGINT); // Termination will happen asynchronously, but the caller may // have wanted synchronous behavior. while (!async) { std::this_thread::sleep_for(1s); } } void debug_trap() { #ifdef _WIN32 DebugBreak(); #else std::raise(SIGTRAP); #endif } char ** get_argv() { return argv; } } // namespace lifetime void log_publisher_data() { BOOST_LOG(info) << "Package Publisher: "sv << SUNSHINE_PUBLISHER_NAME; BOOST_LOG(info) << "Publisher Website: "sv << SUNSHINE_PUBLISHER_WEBSITE; BOOST_LOG(info) << "Get support: "sv << SUNSHINE_PUBLISHER_ISSUE_URL; } #ifdef _WIN32 bool is_gamestream_enabled() { DWORD enabled; DWORD size = sizeof(enabled); return RegGetValueW( HKEY_LOCAL_MACHINE, L"SOFTWARE\\NVIDIA Corporation\\NvStream", L"EnableStreaming", RRF_RT_REG_DWORD, nullptr, &enabled, &size) == ERROR_SUCCESS && enabled != 0; } namespace service_ctrl { class service_controller { public: /** * @brief Constructor for service_controller class. * @param service_desired_access SERVICE_* desired access flags. */ service_controller(DWORD service_desired_access) { scm_handle = OpenSCManagerA(nullptr, nullptr, SC_MANAGER_CONNECT); if (!scm_handle) { auto winerr = GetLastError(); BOOST_LOG(error) << "OpenSCManager() failed: "sv << winerr; return; } service_handle = OpenServiceA(scm_handle, "SunshineService", service_desired_access); if (!service_handle) { auto winerr = GetLastError(); BOOST_LOG(error) << "OpenService() failed: "sv << winerr; return; } } ~service_controller() { if (service_handle) { CloseServiceHandle(service_handle); } if (scm_handle) { CloseServiceHandle(scm_handle); } } /** * @brief Asynchronously starts the Sunshine service. */ bool start_service() { if (!service_handle) { return false; } if (!StartServiceA(service_handle, 0, nullptr)) { auto winerr = GetLastError(); if (winerr != ERROR_SERVICE_ALREADY_RUNNING) { BOOST_LOG(error) << "StartService() failed: "sv << winerr; return false; } } return true; } /** * @brief Query the service status. * @param status The SERVICE_STATUS struct to populate. */ bool query_service_status(SERVICE_STATUS &status) { if (!service_handle) { return false; } if (!QueryServiceStatus(service_handle, &status)) { auto winerr = GetLastError(); BOOST_LOG(error) << "QueryServiceStatus() failed: "sv << winerr; return false; } return true; } private: SC_HANDLE scm_handle = NULL; SC_HANDLE service_handle = NULL; }; bool is_service_running() { service_controller sc { SERVICE_QUERY_STATUS }; SERVICE_STATUS status; if (!sc.query_service_status(status)) { return false; } return status.dwCurrentState == SERVICE_RUNNING; } bool start_service() { service_controller sc { SERVICE_QUERY_STATUS | SERVICE_START }; std::cout << "Starting Sunshine..."sv; // This operation is asynchronous, so we must wait for it to complete if (!sc.start_service()) { return false; } SERVICE_STATUS status; do { Sleep(1000); std::cout << '.'; } while (sc.query_service_status(status) && status.dwCurrentState == SERVICE_START_PENDING); if (status.dwCurrentState != SERVICE_RUNNING) { BOOST_LOG(error) << SERVICE_NAME " failed to start: "sv << status.dwWin32ExitCode; return false; } std::cout << std::endl; return true; } bool wait_for_ui_ready() { std::cout << "Waiting for Web UI to be ready..."; // Wait up to 30 seconds for the web UI to start for (int i = 0; i < 30; i++) { PMIB_TCPTABLE tcp_table = nullptr; ULONG table_size = 0; ULONG err; auto fg = util::fail_guard([&tcp_table]() { free(tcp_table); }); do { // Query all open TCP sockets to look for our web UI port err = GetTcpTable(tcp_table, &table_size, false); if (err == ERROR_INSUFFICIENT_BUFFER) { free(tcp_table); tcp_table = (PMIB_TCPTABLE) malloc(table_size); } } while (err == ERROR_INSUFFICIENT_BUFFER); if (err != NO_ERROR) { BOOST_LOG(error) << "Failed to query TCP table: "sv << err; return false; } uint16_t port_nbo = htons(net::map_port(confighttp::PORT_HTTPS)); for (DWORD i = 0; i < tcp_table->dwNumEntries; i++) { auto &entry = tcp_table->table[i]; // Look for our port in the listening state if (entry.dwLocalPort == port_nbo && entry.dwState == MIB_TCP_STATE_LISTEN) { std::cout << std::endl; return true; } } Sleep(1000); std::cout << '.'; } std::cout << "timed out"sv << std::endl; return false; } } // namespace service_ctrl #endif
6,971
C++
.cpp
249
22.759036
104
0.624513
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,969
config.cpp
LizardByte_Sunshine/src/config.cpp
/** * @file src/config.cpp * @brief Definitions for the configuration of Sunshine. */ #include <algorithm> #include <filesystem> #include <fstream> #include <functional> #include <iostream> #include <thread> #include <unordered_map> #include <utility> #include <boost/asio.hpp> #include <boost/filesystem.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include "config.h" #include "entry_handler.h" #include "file_handler.h" #include "logging.h" #include "nvhttp.h" #include "rtsp.h" #include "utility.h" #include "platform/common.h" #ifdef _WIN32 #include <shellapi.h> #endif #ifndef __APPLE__ // For NVENC legacy constants #include <ffnvcodec/nvEncodeAPI.h> #endif namespace fs = std::filesystem; using namespace std::literals; #define CA_DIR "credentials" #define PRIVATE_KEY_FILE CA_DIR "/cakey.pem" #define CERTIFICATE_FILE CA_DIR "/cacert.pem" #define APPS_JSON_PATH platf::appdata().string() + "/apps.json" namespace config { namespace nv { nvenc::nvenc_two_pass twopass_from_view(const std::string_view &preset) { if (preset == "disabled") return nvenc::nvenc_two_pass::disabled; if (preset == "quarter_res") return nvenc::nvenc_two_pass::quarter_resolution; if (preset == "full_res") return nvenc::nvenc_two_pass::full_resolution; BOOST_LOG(warning) << "config: unknown nvenc_twopass value: " << preset; return nvenc::nvenc_two_pass::quarter_resolution; } } // namespace nv namespace amd { #ifndef _WIN32 // values accurate as of 27/12/2022, but aren't strictly necessary for MacOS build #define AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_SPEED 100 #define AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_QUALITY 30 #define AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_BALANCED 70 #define AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_SPEED 10 #define AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_QUALITY 0 #define AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_BALANCED 5 #define AMF_VIDEO_ENCODER_QUALITY_PRESET_SPEED 1 #define AMF_VIDEO_ENCODER_QUALITY_PRESET_QUALITY 2 #define AMF_VIDEO_ENCODER_QUALITY_PRESET_BALANCED 0 #define AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CONSTANT_QP 0 #define AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CBR 3 #define AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR 2 #define AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_LATENCY_CONSTRAINED_VBR 1 #define AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CONSTANT_QP 0 #define AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CBR 3 #define AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR 2 #define AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_LATENCY_CONSTRAINED_VBR 1 #define AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP 0 #define AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CBR 1 #define AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR 2 #define AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_LATENCY_CONSTRAINED_VBR 3 #define AMF_VIDEO_ENCODER_AV1_USAGE_TRANSCODING 0 #define AMF_VIDEO_ENCODER_AV1_USAGE_LOW_LATENCY 1 #define AMF_VIDEO_ENCODER_AV1_USAGE_ULTRA_LOW_LATENCY 2 #define AMF_VIDEO_ENCODER_AV1_USAGE_WEBCAM 3 #define AMF_VIDEO_ENCODER_AV1_USAGE_LOW_LATENCY_HIGH_QUALITY 5 #define AMF_VIDEO_ENCODER_HEVC_USAGE_TRANSCODING 0 #define AMF_VIDEO_ENCODER_HEVC_USAGE_ULTRA_LOW_LATENCY 1 #define AMF_VIDEO_ENCODER_HEVC_USAGE_LOW_LATENCY 2 #define AMF_VIDEO_ENCODER_HEVC_USAGE_WEBCAM 3 #define AMF_VIDEO_ENCODER_HEVC_USAGE_LOW_LATENCY_HIGH_QUALITY 5 #define AMF_VIDEO_ENCODER_USAGE_TRANSCODING 0 #define AMF_VIDEO_ENCODER_USAGE_ULTRA_LOW_LATENCY 1 #define AMF_VIDEO_ENCODER_USAGE_LOW_LATENCY 2 #define AMF_VIDEO_ENCODER_USAGE_WEBCAM 3 #define AMF_VIDEO_ENCODER_USAGE_LOW_LATENCY_HIGH_QUALITY 5 #define AMF_VIDEO_ENCODER_UNDEFINED 0 #define AMF_VIDEO_ENCODER_CABAC 1 #define AMF_VIDEO_ENCODER_CALV 2 #else #ifdef _GLIBCXX_USE_C99_INTTYPES #undef _GLIBCXX_USE_C99_INTTYPES #endif #include <AMF/components/VideoEncoderAV1.h> #include <AMF/components/VideoEncoderHEVC.h> #include <AMF/components/VideoEncoderVCE.h> #endif enum class quality_av1_e : int { speed = AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_SPEED, ///< Speed preset quality = AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_QUALITY, ///< Quality preset balanced = AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_BALANCED ///< Balanced preset }; enum class quality_hevc_e : int { speed = AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_SPEED, ///< Speed preset quality = AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_QUALITY, ///< Quality preset balanced = AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_BALANCED ///< Balanced preset }; enum class quality_h264_e : int { speed = AMF_VIDEO_ENCODER_QUALITY_PRESET_SPEED, ///< Speed preset quality = AMF_VIDEO_ENCODER_QUALITY_PRESET_QUALITY, ///< Quality preset balanced = AMF_VIDEO_ENCODER_QUALITY_PRESET_BALANCED ///< Balanced preset }; enum class rc_av1_e : int { cbr = AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CBR, ///< CBR cqp = AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CONSTANT_QP, ///< CQP vbr_latency = AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_LATENCY_CONSTRAINED_VBR, ///< VBR with latency constraints vbr_peak = AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR ///< VBR with peak constraints }; enum class rc_hevc_e : int { cbr = AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CBR, ///< CBR cqp = AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CONSTANT_QP, ///< CQP vbr_latency = AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_LATENCY_CONSTRAINED_VBR, ///< VBR with latency constraints vbr_peak = AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR ///< VBR with peak constraints }; enum class rc_h264_e : int { cbr = AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CBR, ///< CBR cqp = AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP, ///< CQP vbr_latency = AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_LATENCY_CONSTRAINED_VBR, ///< VBR with latency constraints vbr_peak = AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR ///< VBR with peak constraints }; enum class usage_av1_e : int { transcoding = AMF_VIDEO_ENCODER_AV1_USAGE_TRANSCODING, ///< Transcoding preset webcam = AMF_VIDEO_ENCODER_AV1_USAGE_WEBCAM, ///< Webcam preset lowlatency_high_quality = AMF_VIDEO_ENCODER_AV1_USAGE_LOW_LATENCY_HIGH_QUALITY, ///< Low latency high quality preset lowlatency = AMF_VIDEO_ENCODER_AV1_USAGE_LOW_LATENCY, ///< Low latency preset ultralowlatency = AMF_VIDEO_ENCODER_AV1_USAGE_ULTRA_LOW_LATENCY ///< Ultra low latency preset }; enum class usage_hevc_e : int { transcoding = AMF_VIDEO_ENCODER_HEVC_USAGE_TRANSCODING, ///< Transcoding preset webcam = AMF_VIDEO_ENCODER_HEVC_USAGE_WEBCAM, ///< Webcam preset lowlatency_high_quality = AMF_VIDEO_ENCODER_HEVC_USAGE_LOW_LATENCY_HIGH_QUALITY, ///< Low latency high quality preset lowlatency = AMF_VIDEO_ENCODER_HEVC_USAGE_LOW_LATENCY, ///< Low latency preset ultralowlatency = AMF_VIDEO_ENCODER_HEVC_USAGE_ULTRA_LOW_LATENCY ///< Ultra low latency preset }; enum class usage_h264_e : int { transcoding = AMF_VIDEO_ENCODER_USAGE_TRANSCODING, ///< Transcoding preset webcam = AMF_VIDEO_ENCODER_USAGE_WEBCAM, ///< Webcam preset lowlatency_high_quality = AMF_VIDEO_ENCODER_USAGE_LOW_LATENCY_HIGH_QUALITY, ///< Low latency high quality preset lowlatency = AMF_VIDEO_ENCODER_USAGE_LOW_LATENCY, ///< Low latency preset ultralowlatency = AMF_VIDEO_ENCODER_USAGE_ULTRA_LOW_LATENCY ///< Ultra low latency preset }; enum coder_e : int { _auto = AMF_VIDEO_ENCODER_UNDEFINED, ///< Auto cabac = AMF_VIDEO_ENCODER_CABAC, ///< CABAC cavlc = AMF_VIDEO_ENCODER_CALV ///< CAVLC }; template <class T> std::optional<int> quality_from_view(const std::string_view &quality_type, const std::optional<int>(&original)) { #define _CONVERT_(x) \ if (quality_type == #x##sv) return (int) T::x _CONVERT_(balanced); _CONVERT_(quality); _CONVERT_(speed); #undef _CONVERT_ return original; } template <class T> std::optional<int> rc_from_view(const std::string_view &rc, const std::optional<int>(&original)) { #define _CONVERT_(x) \ if (rc == #x##sv) return (int) T::x _CONVERT_(cbr); _CONVERT_(cqp); _CONVERT_(vbr_latency); _CONVERT_(vbr_peak); #undef _CONVERT_ return original; } template <class T> std::optional<int> usage_from_view(const std::string_view &usage, const std::optional<int>(&original)) { #define _CONVERT_(x) \ if (usage == #x##sv) return (int) T::x _CONVERT_(lowlatency); _CONVERT_(lowlatency_high_quality); _CONVERT_(transcoding); _CONVERT_(ultralowlatency); _CONVERT_(webcam); #undef _CONVERT_ return original; } int coder_from_view(const std::string_view &coder) { if (coder == "auto"sv) return _auto; if (coder == "cabac"sv || coder == "ac"sv) return cabac; if (coder == "cavlc"sv || coder == "vlc"sv) return cavlc; return _auto; } } // namespace amd namespace qsv { enum preset_e : int { veryslow = 1, ///< veryslow preset slower = 2, ///< slower preset slow = 3, ///< slow preset medium = 4, ///< medium preset fast = 5, ///< fast preset faster = 6, ///< faster preset veryfast = 7 ///< veryfast preset }; enum cavlc_e : int { _auto = false, ///< Auto enabled = true, ///< Enabled disabled = false ///< Disabled }; std::optional<int> preset_from_view(const std::string_view &preset) { #define _CONVERT_(x) \ if (preset == #x##sv) return x _CONVERT_(veryslow); _CONVERT_(slower); _CONVERT_(slow); _CONVERT_(medium); _CONVERT_(fast); _CONVERT_(faster); _CONVERT_(veryfast); #undef _CONVERT_ return std::nullopt; } std::optional<int> coder_from_view(const std::string_view &coder) { if (coder == "auto"sv) return _auto; if (coder == "cabac"sv || coder == "ac"sv) return disabled; if (coder == "cavlc"sv || coder == "vlc"sv) return enabled; return std::nullopt; } } // namespace qsv namespace vt { enum coder_e : int { _auto = 0, ///< Auto cabac, ///< CABAC cavlc ///< CAVLC }; int coder_from_view(const std::string_view &coder) { if (coder == "auto"sv) return _auto; if (coder == "cabac"sv || coder == "ac"sv) return cabac; if (coder == "cavlc"sv || coder == "vlc"sv) return cavlc; return -1; } int allow_software_from_view(const std::string_view &software) { if (software == "allowed"sv || software == "forced") return 1; return 0; } int force_software_from_view(const std::string_view &software) { if (software == "forced") return 1; return 0; } int rt_from_view(const std::string_view &rt) { if (rt == "disabled" || rt == "off" || rt == "0") return 0; return 1; } } // namespace vt namespace sw { int svtav1_preset_from_view(const std::string_view &preset) { #define _CONVERT_(x, y) \ if (preset == #x##sv) return y _CONVERT_(veryslow, 1); _CONVERT_(slower, 2); _CONVERT_(slow, 4); _CONVERT_(medium, 5); _CONVERT_(fast, 7); _CONVERT_(faster, 9); _CONVERT_(veryfast, 10); _CONVERT_(superfast, 11); _CONVERT_(ultrafast, 12); #undef _CONVERT_ return 11; // Default to superfast } } // namespace sw video_t video { 28, // qp 0, // hevc_mode 0, // av1_mode 1, // min_fps_factor 2, // min_threads { "superfast"s, // preset "zerolatency"s, // tune 11, // superfast }, // software {}, // nv true, // nv_realtime_hags true, // nv_opengl_vulkan_on_dxgi true, // nv_sunshine_high_power_mode {}, // nv_legacy { qsv::medium, // preset qsv::_auto, // cavlc false, // slow_hevc }, // qsv { (int) amd::usage_h264_e::ultralowlatency, // usage (h264) (int) amd::usage_hevc_e::ultralowlatency, // usage (hevc) (int) amd::usage_av1_e::ultralowlatency, // usage (av1) (int) amd::rc_h264_e::vbr_latency, // rate control (h264) (int) amd::rc_hevc_e::vbr_latency, // rate control (hevc) (int) amd::rc_av1_e::vbr_latency, // rate control (av1) 0, // enforce_hrd (int) amd::quality_h264_e::balanced, // quality (h264) (int) amd::quality_hevc_e::balanced, // quality (hevc) (int) amd::quality_av1_e::balanced, // quality (av1) 0, // preanalysis 1, // vbaq (int) amd::coder_e::_auto, // coder }, // amd { 0, 0, 1, -1, }, // vt { false, // strict_rc_buffer }, // vaapi {}, // capture {}, // encoder {}, // adapter_name {}, // output_name }; audio_t audio { {}, // audio_sink {}, // virtual_sink true, // install_steam_drivers }; stream_t stream { 10s, // ping_timeout APPS_JSON_PATH, 20, // fecPercentage ENCRYPTION_MODE_NEVER, // lan_encryption_mode ENCRYPTION_MODE_OPPORTUNISTIC, // wan_encryption_mode }; nvhttp_t nvhttp { "lan", // origin web manager PRIVATE_KEY_FILE, CERTIFICATE_FILE, platf::get_host_name(), // sunshine_name, "sunshine_state.json"s, // file_state {}, // external_ip }; input_t input { { { 0x10, 0xA0 }, { 0x11, 0xA2 }, { 0x12, 0xA4 }, }, -1ms, // back_button_timeout 500ms, // key_repeat_delay std::chrono::duration<double> { 1 / 24.9 }, // key_repeat_period { platf::supported_gamepads(nullptr).front().name.data(), platf::supported_gamepads(nullptr).front().name.size(), }, // Default gamepad true, // back as touchpad click enabled (manual DS4 only) true, // client gamepads with motion events are emulated as DS4 true, // client gamepads with touchpads are emulated as DS4 true, // keyboard enabled true, // mouse enabled true, // controller enabled true, // always send scancodes true, // high resolution scrolling true, // native pen/touch support }; sunshine_t sunshine { "en", // locale 2, // min_log_level 0, // flags {}, // User file {}, // Username {}, // Password {}, // Password Salt platf::appdata().string() + "/sunshine.conf", // config file {}, // cmd args 47989, // Base port number "ipv4", // Address family platf::appdata().string() + "/sunshine.log", // log file false, // notify_pre_releases {}, // prep commands }; bool endline(char ch) { return ch == '\r' || ch == '\n'; } bool space_tab(char ch) { return ch == ' ' || ch == '\t'; } bool whitespace(char ch) { return space_tab(ch) || endline(ch); } std::string to_string(const char *begin, const char *end) { std::string result; KITTY_WHILE_LOOP(auto pos = begin, pos != end, { auto comment = std::find(pos, end, '#'); auto endl = std::find_if(comment, end, endline); result.append(pos, comment); pos = endl; }) return result; } template <class It> It skip_list(It skipper, It end) { int stack = 1; while (skipper != end && stack) { if (*skipper == '[') { ++stack; } if (*skipper == ']') { --stack; } ++skipper; } return skipper; } std::pair< std::string_view::const_iterator, std::optional<std::pair<std::string, std::string>>> parse_option(std::string_view::const_iterator begin, std::string_view::const_iterator end) { begin = std::find_if_not(begin, end, whitespace); auto endl = std::find_if(begin, end, endline); auto endc = std::find(begin, endl, '#'); endc = std::find_if(std::make_reverse_iterator(endc), std::make_reverse_iterator(begin), std::not_fn(whitespace)).base(); auto eq = std::find(begin, endc, '='); if (eq == endc || eq == begin) { return std::make_pair(endl, std::nullopt); } auto end_name = std::find_if_not(std::make_reverse_iterator(eq), std::make_reverse_iterator(begin), space_tab).base(); auto begin_val = std::find_if_not(eq + 1, endc, space_tab); if (begin_val == endl) { return std::make_pair(endl, std::nullopt); } // Lists might contain newlines if (*begin_val == '[') { endl = skip_list(begin_val + 1, end); if (endl == end) { std::cout << "Warning: Config option ["sv << to_string(begin, end_name) << "] Missing ']'"sv; return std::make_pair(endl, std::nullopt); } } return std::make_pair( endl, std::make_pair(to_string(begin, end_name), to_string(begin_val, endl))); } std::unordered_map<std::string, std::string> parse_config(const std::string_view &file_content) { std::unordered_map<std::string, std::string> vars; auto pos = std::begin(file_content); auto end = std::end(file_content); while (pos < end) { // auto newline = std::find_if(pos, end, [](auto ch) { return ch == '\n' || ch == '\r'; }); TUPLE_2D(endl, var, parse_option(pos, end)); pos = endl; if (pos != end) { pos += (*pos == '\r') ? 2 : 1; } if (!var) { continue; } vars.emplace(std::move(*var)); } return vars; } void string_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::string &input) { auto it = vars.find(name); if (it == std::end(vars)) { return; } input = std::move(it->second); vars.erase(it); } template <typename T, typename F> void generic_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, T &input, F &&f) { std::string tmp; string_f(vars, name, tmp); if (!tmp.empty()) { input = f(tmp); } } void string_restricted_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::string &input, const std::vector<std::string_view> &allowed_vals) { std::string temp; string_f(vars, name, temp); for (auto &allowed_val : allowed_vals) { if (temp == allowed_val) { input = std::move(temp); return; } } } void path_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, fs::path &input) { // appdata needs to be retrieved once only static auto appdata = platf::appdata(); std::string temp; string_f(vars, name, temp); if (!temp.empty()) { input = temp; } if (input.is_relative()) { input = appdata / input; } auto dir = input; dir.remove_filename(); // Ensure the directories exists if (!fs::exists(dir)) { fs::create_directories(dir); } } void path_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::string &input) { fs::path temp = input; path_f(vars, name, temp); input = temp.string(); } void int_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, int &input) { auto it = vars.find(name); if (it == std::end(vars)) { return; } std::string_view val = it->second; // If value is something like: "756" instead of 756 if (val.size() >= 2 && val[0] == '"') { val = val.substr(1, val.size() - 2); } // If that integer is in hexadecimal if (val.size() >= 2 && val.substr(0, 2) == "0x"sv) { input = util::from_hex<int>(val.substr(2)); } else { input = util::from_view(val); } vars.erase(it); } void int_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::optional<int> &input) { auto it = vars.find(name); if (it == std::end(vars)) { return; } std::string_view val = it->second; // If value is something like: "756" instead of 756 if (val.size() >= 2 && val[0] == '"') { val = val.substr(1, val.size() - 2); } // If that integer is in hexadecimal if (val.size() >= 2 && val.substr(0, 2) == "0x"sv) { input = util::from_hex<int>(val.substr(2)); } else { input = util::from_view(val); } vars.erase(it); } template <class F> void int_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, int &input, F &&f) { std::string tmp; string_f(vars, name, tmp); if (!tmp.empty()) { input = f(tmp); } } template <class F> void int_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::optional<int> &input, F &&f) { std::string tmp; string_f(vars, name, tmp); if (!tmp.empty()) { input = f(tmp); } } void int_between_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, int &input, const std::pair<int, int> &range) { int temp = input; int_f(vars, name, temp); TUPLE_2D_REF(lower, upper, range); if (temp >= lower && temp <= upper) { input = temp; } } bool to_bool(std::string &boolean) { std::for_each(std::begin(boolean), std::end(boolean), [](char ch) { return (char) std::tolower(ch); }); return boolean == "true"sv || boolean == "yes"sv || boolean == "enable"sv || boolean == "enabled"sv || boolean == "on"sv || (std::find(std::begin(boolean), std::end(boolean), '1') != std::end(boolean)); } void bool_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, bool &input) { std::string tmp; string_f(vars, name, tmp); if (tmp.empty()) { return; } input = to_bool(tmp); } void double_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, double &input) { std::string tmp; string_f(vars, name, tmp); if (tmp.empty()) { return; } char *c_str_p; auto val = std::strtod(tmp.c_str(), &c_str_p); if (c_str_p == tmp.c_str()) { return; } input = val; } void double_between_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, double &input, const std::pair<double, double> &range) { double temp = input; double_f(vars, name, temp); TUPLE_2D_REF(lower, upper, range); if (temp >= lower && temp <= upper) { input = temp; } } void list_string_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::vector<std::string> &input) { std::string string; string_f(vars, name, string); if (string.empty()) { return; } input.clear(); auto begin = std::cbegin(string); if (*begin == '[') { ++begin; } begin = std::find_if_not(begin, std::cend(string), whitespace); if (begin == std::cend(string)) { return; } auto pos = begin; while (pos < std::cend(string)) { if (*pos == '[') { pos = skip_list(pos + 1, std::cend(string)) + 1; } else if (*pos == ']') { break; } else if (*pos == ',') { input.emplace_back(begin, pos); pos = begin = std::find_if_not(pos + 1, std::cend(string), whitespace); } else { ++pos; } } if (pos != begin) { input.emplace_back(begin, pos); } } void list_prep_cmd_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::vector<prep_cmd_t> &input) { std::string string; string_f(vars, name, string); std::stringstream jsonStream; // check if string is empty, i.e. when the value doesn't exist in the config file if (string.empty()) { return; } // We need to add a wrapping object to make it valid JSON, otherwise ptree cannot parse it. jsonStream << "{\"prep_cmd\":" << string << "}"; boost::property_tree::ptree jsonTree; boost::property_tree::read_json(jsonStream, jsonTree); for (auto &[_, prep_cmd] : jsonTree.get_child("prep_cmd"s)) { auto do_cmd = prep_cmd.get_optional<std::string>("do"s); auto undo_cmd = prep_cmd.get_optional<std::string>("undo"s); auto elevated = prep_cmd.get_optional<bool>("elevated"s); input.emplace_back(do_cmd.value_or(""), undo_cmd.value_or(""), elevated.value_or(false)); } } void list_int_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::vector<int> &input) { std::vector<std::string> list; list_string_f(vars, name, list); // check if list is empty, i.e. when the value doesn't exist in the config file if (list.empty()) { return; } // The framerate list must be cleared before adding values from the file configuration. // If the list is not cleared, then the specified parameters do not affect the behavior of the sunshine server. // That is, if you set only 30 fps in the configuration file, it will not work because by default, during initialization the list includes 10, 30, 60, 90 and 120 fps. input.clear(); for (auto &el : list) { std::string_view val = el; // If value is something like: "756" instead of 756 if (val.size() >= 2 && val[0] == '"') { val = val.substr(1, val.size() - 2); } int tmp; // If the integer is a hexadecimal if (val.size() >= 2 && val.substr(0, 2) == "0x"sv) { tmp = util::from_hex<int>(val.substr(2)); } else { tmp = util::from_view(val); } input.emplace_back(tmp); } } void map_int_int_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::unordered_map<int, int> &input) { std::vector<int> list; list_int_f(vars, name, list); // The list needs to be a multiple of 2 if (list.size() % 2) { std::cout << "Warning: expected "sv << name << " to have a multiple of two elements --> not "sv << list.size() << std::endl; return; } int x = 0; while (x < list.size()) { auto key = list[x++]; auto val = list[x++]; input.emplace(key, val); } } int apply_flags(const char *line) { int ret = 0; while (*line != '\0') { switch (*line) { case '0': config::sunshine.flags[config::flag::PIN_STDIN].flip(); break; case '1': config::sunshine.flags[config::flag::FRESH_STATE].flip(); break; case '2': config::sunshine.flags[config::flag::FORCE_VIDEO_HEADER_REPLACE].flip(); break; case 'p': config::sunshine.flags[config::flag::UPNP].flip(); break; default: std::cout << "Warning: Unrecognized flag: ["sv << *line << ']' << std::endl; ret = -1; } ++line; } return ret; } std::vector<std::string_view> & get_supported_gamepad_options() { const auto options = platf::supported_gamepads(nullptr); static std::vector<std::string_view> opts {}; opts.reserve(options.size()); for (auto &opt : options) { opts.emplace_back(opt.name); } return opts; } void apply_config(std::unordered_map<std::string, std::string> &&vars) { if (!fs::exists(stream.file_apps.c_str())) { fs::copy_file(SUNSHINE_ASSETS_DIR "/apps.json", stream.file_apps); } for (auto &[name, val] : vars) { std::cout << "["sv << name << "] -- ["sv << val << ']' << std::endl; } int_f(vars, "qp", video.qp); int_f(vars, "min_threads", video.min_threads); int_between_f(vars, "hevc_mode", video.hevc_mode, { 0, 3 }); int_between_f(vars, "av1_mode", video.av1_mode, { 0, 3 }); string_f(vars, "sw_preset", video.sw.sw_preset); if (!video.sw.sw_preset.empty()) { video.sw.svtav1_preset = sw::svtav1_preset_from_view(video.sw.sw_preset); } string_f(vars, "sw_tune", video.sw.sw_tune); int_between_f(vars, "nvenc_preset", video.nv.quality_preset, { 1, 7 }); int_between_f(vars, "nvenc_vbv_increase", video.nv.vbv_percentage_increase, { 0, 400 }); bool_f(vars, "nvenc_spatial_aq", video.nv.adaptive_quantization); generic_f(vars, "nvenc_twopass", video.nv.two_pass, nv::twopass_from_view); bool_f(vars, "nvenc_h264_cavlc", video.nv.h264_cavlc); bool_f(vars, "nvenc_realtime_hags", video.nv_realtime_hags); bool_f(vars, "nvenc_opengl_vulkan_on_dxgi", video.nv_opengl_vulkan_on_dxgi); bool_f(vars, "nvenc_latency_over_power", video.nv_sunshine_high_power_mode); #ifndef __APPLE__ video.nv_legacy.preset = video.nv.quality_preset + 11; video.nv_legacy.multipass = video.nv.two_pass == nvenc::nvenc_two_pass::quarter_resolution ? NV_ENC_TWO_PASS_QUARTER_RESOLUTION : video.nv.two_pass == nvenc::nvenc_two_pass::full_resolution ? NV_ENC_TWO_PASS_FULL_RESOLUTION : NV_ENC_MULTI_PASS_DISABLED; video.nv_legacy.h264_coder = video.nv.h264_cavlc ? NV_ENC_H264_ENTROPY_CODING_MODE_CAVLC : NV_ENC_H264_ENTROPY_CODING_MODE_CABAC; video.nv_legacy.aq = video.nv.adaptive_quantization; video.nv_legacy.vbv_percentage_increase = video.nv.vbv_percentage_increase; #endif int_f(vars, "qsv_preset", video.qsv.qsv_preset, qsv::preset_from_view); int_f(vars, "qsv_coder", video.qsv.qsv_cavlc, qsv::coder_from_view); bool_f(vars, "qsv_slow_hevc", video.qsv.qsv_slow_hevc); std::string quality; string_f(vars, "amd_quality", quality); if (!quality.empty()) { video.amd.amd_quality_h264 = amd::quality_from_view<amd::quality_h264_e>(quality, video.amd.amd_quality_h264); video.amd.amd_quality_hevc = amd::quality_from_view<amd::quality_hevc_e>(quality, video.amd.amd_quality_hevc); video.amd.amd_quality_av1 = amd::quality_from_view<amd::quality_av1_e>(quality, video.amd.amd_quality_av1); } std::string rc; string_f(vars, "amd_rc", rc); int_f(vars, "amd_coder", video.amd.amd_coder, amd::coder_from_view); if (!rc.empty()) { video.amd.amd_rc_h264 = amd::rc_from_view<amd::rc_h264_e>(rc, video.amd.amd_rc_h264); video.amd.amd_rc_hevc = amd::rc_from_view<amd::rc_hevc_e>(rc, video.amd.amd_rc_hevc); video.amd.amd_rc_av1 = amd::rc_from_view<amd::rc_av1_e>(rc, video.amd.amd_rc_av1); } std::string usage; string_f(vars, "amd_usage", usage); if (!usage.empty()) { video.amd.amd_usage_h264 = amd::usage_from_view<amd::usage_h264_e>(usage, video.amd.amd_usage_h264); video.amd.amd_usage_hevc = amd::usage_from_view<amd::usage_hevc_e>(usage, video.amd.amd_usage_hevc); video.amd.amd_usage_av1 = amd::usage_from_view<amd::usage_av1_e>(usage, video.amd.amd_usage_av1); } bool_f(vars, "amd_preanalysis", (bool &) video.amd.amd_preanalysis); bool_f(vars, "amd_vbaq", (bool &) video.amd.amd_vbaq); bool_f(vars, "amd_enforce_hrd", (bool &) video.amd.amd_enforce_hrd); int_f(vars, "vt_coder", video.vt.vt_coder, vt::coder_from_view); int_f(vars, "vt_software", video.vt.vt_allow_sw, vt::allow_software_from_view); int_f(vars, "vt_software", video.vt.vt_require_sw, vt::force_software_from_view); int_f(vars, "vt_realtime", video.vt.vt_realtime, vt::rt_from_view); bool_f(vars, "vaapi_strict_rc_buffer", video.vaapi.strict_rc_buffer); string_f(vars, "capture", video.capture); string_f(vars, "encoder", video.encoder); string_f(vars, "adapter_name", video.adapter_name); string_f(vars, "output_name", video.output_name); int_between_f(vars, "min_fps_factor", video.min_fps_factor, { 1, 3 }); path_f(vars, "pkey", nvhttp.pkey); path_f(vars, "cert", nvhttp.cert); string_f(vars, "sunshine_name", nvhttp.sunshine_name); path_f(vars, "log_path", config::sunshine.log_file); path_f(vars, "file_state", nvhttp.file_state); // Must be run after "file_state" config::sunshine.credentials_file = config::nvhttp.file_state; path_f(vars, "credentials_file", config::sunshine.credentials_file); string_f(vars, "external_ip", nvhttp.external_ip); list_prep_cmd_f(vars, "global_prep_cmd", config::sunshine.prep_cmds); string_f(vars, "audio_sink", audio.sink); string_f(vars, "virtual_sink", audio.virtual_sink); bool_f(vars, "install_steam_audio_drivers", audio.install_steam_drivers); string_restricted_f(vars, "origin_web_ui_allowed", nvhttp.origin_web_ui_allowed, { "pc"sv, "lan"sv, "wan"sv }); int to = -1; int_between_f(vars, "ping_timeout", to, { -1, std::numeric_limits<int>::max() }); if (to != -1) { stream.ping_timeout = std::chrono::milliseconds(to); } int_between_f(vars, "lan_encryption_mode", stream.lan_encryption_mode, { 0, 2 }); int_between_f(vars, "wan_encryption_mode", stream.wan_encryption_mode, { 0, 2 }); path_f(vars, "file_apps", stream.file_apps); int_between_f(vars, "fec_percentage", stream.fec_percentage, { 1, 255 }); map_int_int_f(vars, "keybindings"s, input.keybindings); // This config option will only be used by the UI // When editing in the config file itself, use "keybindings" bool map_rightalt_to_win = false; bool_f(vars, "key_rightalt_to_key_win", map_rightalt_to_win); if (map_rightalt_to_win) { input.keybindings.emplace(0xA5, 0x5B); } to = std::numeric_limits<int>::min(); int_f(vars, "back_button_timeout", to); if (to > std::numeric_limits<int>::min()) { input.back_button_timeout = std::chrono::milliseconds { to }; } double repeat_frequency { 0 }; double_between_f(vars, "key_repeat_frequency", repeat_frequency, { 0, std::numeric_limits<double>::max() }); if (repeat_frequency > 0) { config::input.key_repeat_period = std::chrono::duration<double> { 1 / repeat_frequency }; } to = -1; int_f(vars, "key_repeat_delay", to); if (to >= 0) { input.key_repeat_delay = std::chrono::milliseconds { to }; } string_restricted_f(vars, "gamepad"s, input.gamepad, get_supported_gamepad_options()); bool_f(vars, "ds4_back_as_touchpad_click", input.ds4_back_as_touchpad_click); bool_f(vars, "motion_as_ds4", input.motion_as_ds4); bool_f(vars, "touchpad_as_ds4", input.touchpad_as_ds4); bool_f(vars, "mouse", input.mouse); bool_f(vars, "keyboard", input.keyboard); bool_f(vars, "controller", input.controller); bool_f(vars, "always_send_scancodes", input.always_send_scancodes); bool_f(vars, "high_resolution_scrolling", input.high_resolution_scrolling); bool_f(vars, "native_pen_touch", input.native_pen_touch); bool_f(vars, "notify_pre_releases", sunshine.notify_pre_releases); int port = sunshine.port; int_between_f(vars, "port"s, port, { 1024 + nvhttp::PORT_HTTPS, 65535 - rtsp_stream::RTSP_SETUP_PORT }); sunshine.port = (std::uint16_t) port; string_restricted_f(vars, "address_family", sunshine.address_family, { "ipv4"sv, "both"sv }); bool upnp = false; bool_f(vars, "upnp"s, upnp); if (upnp) { config::sunshine.flags[config::flag::UPNP].flip(); } string_restricted_f(vars, "locale", config::sunshine.locale, { "de"sv, // German "en"sv, // English "en_GB"sv, // English (UK) "en_US"sv, // English (US) "es"sv, // Spanish "fr"sv, // French "it"sv, // Italian "ja"sv, // Japanese "pt"sv, // Portuguese "ru"sv, // Russian "sv"sv, // Swedish "tr"sv, // Turkish "zh"sv, // Chinese }); std::string log_level_string; string_f(vars, "min_log_level", log_level_string); if (!log_level_string.empty()) { if (log_level_string == "verbose"sv) { sunshine.min_log_level = 0; } else if (log_level_string == "debug"sv) { sunshine.min_log_level = 1; } else if (log_level_string == "info"sv) { sunshine.min_log_level = 2; } else if (log_level_string == "warning"sv) { sunshine.min_log_level = 3; } else if (log_level_string == "error"sv) { sunshine.min_log_level = 4; } else if (log_level_string == "fatal"sv) { sunshine.min_log_level = 5; } else if (log_level_string == "none"sv) { sunshine.min_log_level = 6; } else { // accept digit directly auto val = log_level_string[0]; if (val >= '0' && val < '7') { sunshine.min_log_level = val - '0'; } } } auto it = vars.find("flags"s); if (it != std::end(vars)) { apply_flags(it->second.c_str()); vars.erase(it); } if (sunshine.min_log_level <= 3) { for (auto &[var, _] : vars) { std::cout << "Warning: Unrecognized configurable option ["sv << var << ']' << std::endl; } } } int parse(int argc, char *argv[]) { std::unordered_map<std::string, std::string> cmd_vars; #ifdef _WIN32 bool shortcut_launch = false; bool service_admin_launch = false; #endif for (auto x = 1; x < argc; ++x) { auto line = argv[x]; if (line == "--help"sv) { logging::print_help(*argv); return 1; } #ifdef _WIN32 else if (line == "--shortcut"sv) { shortcut_launch = true; } else if (line == "--shortcut-admin"sv) { service_admin_launch = true; } #endif else if (*line == '-') { if (*(line + 1) == '-') { sunshine.cmd.name = line + 2; sunshine.cmd.argc = argc - x - 1; sunshine.cmd.argv = argv + x + 1; break; } if (apply_flags(line + 1)) { logging::print_help(*argv); return -1; } } else { auto line_end = line + strlen(line); auto pos = std::find(line, line_end, '='); if (pos == line_end) { sunshine.config_file = line; } else { TUPLE_EL(var, 1, parse_option(line, line_end)); if (!var) { logging::print_help(*argv); return -1; } TUPLE_EL_REF(name, 0, *var); auto it = cmd_vars.find(name); if (it != std::end(cmd_vars)) { cmd_vars.erase(it); } cmd_vars.emplace(std::move(*var)); } } } bool config_loaded = false; try { // Create appdata folder if it does not exist file_handler::make_directory(platf::appdata().string()); // Create empty config file if it does not exist if (!fs::exists(sunshine.config_file)) { std::ofstream { sunshine.config_file }; } // Read config file auto vars = parse_config(file_handler::read_file(sunshine.config_file.c_str())); for (auto &[name, value] : cmd_vars) { vars.insert_or_assign(std::move(name), std::move(value)); } // Apply the config. Note: This will try to create any paths // referenced in the config, so we may receive exceptions if // the path is incorrect or inaccessible. apply_config(std::move(vars)); config_loaded = true; } catch (const std::filesystem::filesystem_error &err) { BOOST_LOG(fatal) << "Failed to apply config: "sv << err.what(); } catch (const boost::filesystem::filesystem_error &err) { BOOST_LOG(fatal) << "Failed to apply config: "sv << err.what(); } #ifdef _WIN32 // UCRT64 raises an access denied exception if launching from the shortcut // as non-admin and the config folder is not yet present; we can defer // so that service instance will do the work instead. if (!config_loaded && !shortcut_launch) { BOOST_LOG(fatal) << "To relaunch Sunshine successfully, use the shortcut in the Start Menu. Do not run Sunshine.exe manually."sv; std::this_thread::sleep_for(10s); #else if (!config_loaded) { #endif return -1; } #ifdef _WIN32 // We have to wait until the config is loaded to handle these launches, // because we need to have the correct base port loaded in our config. // Exception: UCRT64 shortcut_launch instances may have no config loaded due to // insufficient permissions to create folder; port defaults will be acceptable. if (service_admin_launch) { // This is a relaunch as admin to start the service service_ctrl::start_service(); // Always return 1 to ensure Sunshine doesn't start normally return 1; } else if (shortcut_launch) { if (!service_ctrl::is_service_running()) { // If the service isn't running, relaunch ourselves as admin to start it WCHAR executable[MAX_PATH]; GetModuleFileNameW(NULL, executable, ARRAYSIZE(executable)); SHELLEXECUTEINFOW shell_exec_info {}; shell_exec_info.cbSize = sizeof(shell_exec_info); shell_exec_info.fMask = SEE_MASK_NOASYNC | SEE_MASK_NO_CONSOLE | SEE_MASK_NOCLOSEPROCESS; shell_exec_info.lpVerb = L"runas"; shell_exec_info.lpFile = executable; shell_exec_info.lpParameters = L"--shortcut-admin"; shell_exec_info.nShow = SW_NORMAL; if (!ShellExecuteExW(&shell_exec_info)) { auto winerr = GetLastError(); std::cout << "Error: ShellExecuteEx() failed:"sv << winerr << std::endl; return 1; } // Wait for the elevated process to finish starting the service WaitForSingleObject(shell_exec_info.hProcess, INFINITE); CloseHandle(shell_exec_info.hProcess); // Wait for the UI to be ready for connections service_ctrl::wait_for_ui_ready(); } // Launch the web UI launch_ui(); // Always return 1 to ensure Sunshine doesn't start normally return 1; } #endif return 0; } } // namespace config
43,002
C++
.cpp
1,109
32.191163
171
0.608286
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,970
network.cpp
LizardByte_Sunshine/src/network.cpp
/** * @file src/network.cpp * @brief Definitions for networking related functions. */ #include "network.h" #include "config.h" #include "logging.h" #include "utility.h" #include <algorithm> #include <sstream> using namespace std::literals; namespace ip = boost::asio::ip; namespace net { std::vector<ip::network_v4> pc_ips_v4 { ip::make_network_v4("127.0.0.0/8"sv), }; std::vector<ip::network_v4> lan_ips_v4 { ip::make_network_v4("192.168.0.0/16"sv), ip::make_network_v4("172.16.0.0/12"sv), ip::make_network_v4("10.0.0.0/8"sv), ip::make_network_v4("100.64.0.0/10"sv), ip::make_network_v4("169.254.0.0/16"sv), }; std::vector<ip::network_v6> pc_ips_v6 { ip::make_network_v6("::1/128"sv), }; std::vector<ip::network_v6> lan_ips_v6 { ip::make_network_v6("fc00::/7"sv), ip::make_network_v6("fe80::/64"sv), }; net_e from_enum_string(const std::string_view &view) { if (view == "wan") { return WAN; } if (view == "lan") { return LAN; } return PC; } net_e from_address(const std::string_view &view) { auto addr = normalize_address(ip::make_address(view)); if (addr.is_v6()) { for (auto &range : pc_ips_v6) { if (range.hosts().find(addr.to_v6()) != range.hosts().end()) { return PC; } } for (auto &range : lan_ips_v6) { if (range.hosts().find(addr.to_v6()) != range.hosts().end()) { return LAN; } } } else { for (auto &range : pc_ips_v4) { if (range.hosts().find(addr.to_v4()) != range.hosts().end()) { return PC; } } for (auto &range : lan_ips_v4) { if (range.hosts().find(addr.to_v4()) != range.hosts().end()) { return LAN; } } } return WAN; } std::string_view to_enum_string(net_e net) { switch (net) { case PC: return "pc"sv; case LAN: return "lan"sv; case WAN: return "wan"sv; } // avoid warning return "wan"sv; } af_e af_from_enum_string(const std::string_view &view) { if (view == "ipv4") { return IPV4; } if (view == "both") { return BOTH; } // avoid warning return BOTH; } std::string_view af_to_any_address_string(af_e af) { switch (af) { case IPV4: return "0.0.0.0"sv; case BOTH: return "::"sv; } // avoid warning return "::"sv; } boost::asio::ip::address normalize_address(boost::asio::ip::address address) { // Convert IPv6-mapped IPv4 addresses into regular IPv4 addresses if (address.is_v6()) { auto v6 = address.to_v6(); if (v6.is_v4_mapped()) { return boost::asio::ip::make_address_v4(boost::asio::ip::v4_mapped, v6); } } return address; } std::string addr_to_normalized_string(boost::asio::ip::address address) { return normalize_address(address).to_string(); } std::string addr_to_url_escaped_string(boost::asio::ip::address address) { address = normalize_address(address); if (address.is_v6()) { std::stringstream ss; ss << '[' << address.to_string() << ']'; return ss.str(); } else { return address.to_string(); } } int encryption_mode_for_address(boost::asio::ip::address address) { auto nettype = net::from_address(address.to_string()); if (nettype == net::net_e::PC || nettype == net::net_e::LAN) { return config::stream.lan_encryption_mode; } else { return config::stream.wan_encryption_mode; } } host_t host_create(af_e af, ENetAddress &addr, std::uint16_t port) { static std::once_flag enet_init_flag; std::call_once(enet_init_flag, []() { enet_initialize(); }); auto any_addr = net::af_to_any_address_string(af); enet_address_set_host(&addr, any_addr.data()); enet_address_set_port(&addr, port); // Maximum of 128 clients, which should be enough for anyone auto host = host_t { enet_host_create(af == IPV4 ? AF_INET : AF_INET6, &addr, 128, 0, 0, 0) }; // Enable opportunistic QoS tagging (automatically disables if the network appears to drop tagged packets) enet_socket_set_option(host->socket, ENET_SOCKOPT_QOS, 1); return host; } void free_host(ENetHost *host) { std::for_each(host->peers, host->peers + host->peerCount, [](ENetPeer &peer_ref) { ENetPeer *peer = &peer_ref; if (peer) { enet_peer_disconnect_now(peer, 0); } }); enet_host_destroy(host); } std::uint16_t map_port(int port) { // calculate the port from the config port auto mapped_port = (std::uint16_t)((int) config::sunshine.port + port); // Ensure port is in the range of 1024-65535 if (mapped_port < 1024 || mapped_port > 65535) { BOOST_LOG(warning) << "Port out of range: "sv << mapped_port; } return mapped_port; } /** * @brief Returns a string for use as the instance name for mDNS. * @param hostname The hostname to use for instance name generation. * @return Hostname-based instance name or "Sunshine" if hostname is invalid. */ std::string mdns_instance_name(const std::string_view &hostname) { // Start with the unmodified hostname std::string instancename { hostname.data(), hostname.size() }; // Truncate to 63 characters per RFC 6763 section 7.2. if (instancename.size() > 63) { instancename.resize(63); } for (auto i = 0; i < instancename.size(); i++) { // Replace any spaces with dashes if (instancename[i] == ' ') { instancename[i] = '-'; } else if (!std::isalnum(instancename[i]) && instancename[i] != '-') { // Stop at the first invalid character instancename.resize(i); break; } } return !instancename.empty() ? instancename : "Sunshine"; } } // namespace net
5,936
C++
.cpp
203
23.955665
110
0.600948
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,971
cbs.cpp
LizardByte_Sunshine/src/cbs.cpp
/** * @file src/cbs.cpp * @brief Definitions for FFmpeg Coded Bitstream API. */ extern "C" { #include <libavcodec/avcodec.h> #include <libavcodec/cbs_h264.h> #include <libavcodec/cbs_h265.h> #include <libavcodec/h264_levels.h> #include <libavutil/pixdesc.h> } #include "cbs.h" #include "logging.h" #include "utility.h" using namespace std::literals; namespace cbs { void close(CodedBitstreamContext *c) { ff_cbs_close(&c); } using ctx_t = util::safe_ptr<CodedBitstreamContext, close>; class frag_t: public CodedBitstreamFragment { public: frag_t(frag_t &&o) { std::copy((std::uint8_t *) &o, (std::uint8_t *) (&o + 1), (std::uint8_t *) this); o.data = nullptr; o.units = nullptr; }; frag_t() { std::fill_n((std::uint8_t *) this, sizeof(*this), 0); } frag_t & operator=(frag_t &&o) { std::copy((std::uint8_t *) &o, (std::uint8_t *) (&o + 1), (std::uint8_t *) this); o.data = nullptr; o.units = nullptr; return *this; }; ~frag_t() { if (data || units) { ff_cbs_fragment_free(this); } } }; util::buffer_t<std::uint8_t> write(cbs::ctx_t &cbs_ctx, std::uint8_t nal, void *uh, AVCodecID codec_id) { cbs::frag_t frag; auto err = ff_cbs_insert_unit_content(&frag, -1, nal, uh, nullptr); if (err < 0) { char err_str[AV_ERROR_MAX_STRING_SIZE] { 0 }; BOOST_LOG(error) << "Could not insert NAL unit SPS: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); return {}; } err = ff_cbs_write_fragment_data(cbs_ctx.get(), &frag); if (err < 0) { char err_str[AV_ERROR_MAX_STRING_SIZE] { 0 }; BOOST_LOG(error) << "Could not write fragment data: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); return {}; } // frag.data_size * 8 - frag.data_bit_padding == bits in fragment util::buffer_t<std::uint8_t> data { frag.data_size }; std::copy_n(frag.data, frag.data_size, std::begin(data)); return data; } util::buffer_t<std::uint8_t> write(std::uint8_t nal, void *uh, AVCodecID codec_id) { cbs::ctx_t cbs_ctx; ff_cbs_init(&cbs_ctx, codec_id, nullptr); return write(cbs_ctx, nal, uh, codec_id); } h264_t make_sps_h264(const AVCodecContext *avctx, const AVPacket *packet) { cbs::ctx_t ctx; if (ff_cbs_init(&ctx, AV_CODEC_ID_H264, nullptr)) { return {}; } cbs::frag_t frag; int err = ff_cbs_read_packet(ctx.get(), &frag, packet); if (err < 0) { char err_str[AV_ERROR_MAX_STRING_SIZE] { 0 }; BOOST_LOG(error) << "Couldn't read packet: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); return {}; } auto sps_p = ((CodedBitstreamH264Context *) ctx->priv_data)->active_sps; // This is a very large struct that cannot safely be stored on the stack auto sps = std::make_unique<H264RawSPS>(*sps_p); if (avctx->refs > 0) { sps->max_num_ref_frames = avctx->refs; } sps->vui_parameters_present_flag = 1; auto &vui = sps->vui; std::memset(&vui, 0, sizeof(vui)); vui.video_format = 5; vui.colour_description_present_flag = 1; vui.video_signal_type_present_flag = 1; vui.video_full_range_flag = avctx->color_range == AVCOL_RANGE_JPEG; vui.colour_primaries = avctx->color_primaries; vui.transfer_characteristics = avctx->color_trc; vui.matrix_coefficients = avctx->colorspace; vui.low_delay_hrd_flag = 1 - vui.fixed_frame_rate_flag; vui.bitstream_restriction_flag = 1; vui.motion_vectors_over_pic_boundaries_flag = 1; vui.log2_max_mv_length_horizontal = 16; vui.log2_max_mv_length_vertical = 16; vui.max_num_reorder_frames = 0; vui.max_dec_frame_buffering = sps->max_num_ref_frames; cbs::ctx_t write_ctx; ff_cbs_init(&write_ctx, AV_CODEC_ID_H264, nullptr); return h264_t { write(write_ctx, sps->nal_unit_header.nal_unit_type, (void *) &sps->nal_unit_header, AV_CODEC_ID_H264), write(ctx, sps_p->nal_unit_header.nal_unit_type, (void *) &sps_p->nal_unit_header, AV_CODEC_ID_H264) }; } hevc_t make_sps_hevc(const AVCodecContext *avctx, const AVPacket *packet) { cbs::ctx_t ctx; if (ff_cbs_init(&ctx, AV_CODEC_ID_H265, nullptr)) { return {}; } cbs::frag_t frag; int err = ff_cbs_read_packet(ctx.get(), &frag, packet); if (err < 0) { char err_str[AV_ERROR_MAX_STRING_SIZE] { 0 }; BOOST_LOG(error) << "Couldn't read packet: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); return {}; } auto vps_p = ((CodedBitstreamH265Context *) ctx->priv_data)->active_vps; auto sps_p = ((CodedBitstreamH265Context *) ctx->priv_data)->active_sps; // These are very large structs that cannot safely be stored on the stack auto sps = std::make_unique<H265RawSPS>(*sps_p); auto vps = std::make_unique<H265RawVPS>(*vps_p); vps->profile_tier_level.general_profile_compatibility_flag[4] = 1; sps->profile_tier_level.general_profile_compatibility_flag[4] = 1; auto &vui = sps->vui; std::memset(&vui, 0, sizeof(vui)); sps->vui_parameters_present_flag = 1; // skip sample aspect ratio vui.video_format = 5; vui.colour_description_present_flag = 1; vui.video_signal_type_present_flag = 1; vui.video_full_range_flag = avctx->color_range == AVCOL_RANGE_JPEG; vui.colour_primaries = avctx->color_primaries; vui.transfer_characteristics = avctx->color_trc; vui.matrix_coefficients = avctx->colorspace; vui.vui_timing_info_present_flag = vps->vps_timing_info_present_flag; vui.vui_num_units_in_tick = vps->vps_num_units_in_tick; vui.vui_time_scale = vps->vps_time_scale; vui.vui_poc_proportional_to_timing_flag = vps->vps_poc_proportional_to_timing_flag; vui.vui_num_ticks_poc_diff_one_minus1 = vps->vps_num_ticks_poc_diff_one_minus1; vui.vui_hrd_parameters_present_flag = 0; vui.bitstream_restriction_flag = 1; vui.motion_vectors_over_pic_boundaries_flag = 1; vui.restricted_ref_pic_lists_flag = 1; vui.max_bytes_per_pic_denom = 0; vui.max_bits_per_min_cu_denom = 0; vui.log2_max_mv_length_horizontal = 15; vui.log2_max_mv_length_vertical = 15; cbs::ctx_t write_ctx; ff_cbs_init(&write_ctx, AV_CODEC_ID_H265, nullptr); return hevc_t { nal_t { write(write_ctx, vps->nal_unit_header.nal_unit_type, (void *) &vps->nal_unit_header, AV_CODEC_ID_H265), write(ctx, vps_p->nal_unit_header.nal_unit_type, (void *) &vps_p->nal_unit_header, AV_CODEC_ID_H265), }, nal_t { write(write_ctx, sps->nal_unit_header.nal_unit_type, (void *) &sps->nal_unit_header, AV_CODEC_ID_H265), write(ctx, sps_p->nal_unit_header.nal_unit_type, (void *) &sps_p->nal_unit_header, AV_CODEC_ID_H265), }, }; } /** * This function initializes a Coded Bitstream Context and reads the packet into a Coded Bitstream Fragment. * It then checks if the SPS->VUI (Video Usability Information) is present in the active SPS of the packet. * This is done for both H264 and H265 codecs. */ bool validate_sps(const AVPacket *packet, int codec_id) { cbs::ctx_t ctx; if (ff_cbs_init(&ctx, (AVCodecID) codec_id, nullptr)) { return false; } cbs::frag_t frag; int err = ff_cbs_read_packet(ctx.get(), &frag, packet); if (err < 0) { char err_str[AV_ERROR_MAX_STRING_SIZE] { 0 }; BOOST_LOG(error) << "Couldn't read packet: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); return false; } if (codec_id == AV_CODEC_ID_H264) { auto h264 = (CodedBitstreamH264Context *) ctx->priv_data; if (!h264->active_sps->vui_parameters_present_flag) { return false; } return true; } return ((CodedBitstreamH265Context *) ctx->priv_data)->active_sps->vui_parameters_present_flag; } } // namespace cbs
7,982
C++
.cpp
198
35.09596
126
0.646869
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,972
video.cpp
LizardByte_Sunshine/src/video.cpp
/** * @file src/video.cpp * @brief Definitions for video. */ #include <atomic> #include <bitset> #include <list> #include <thread> #include <boost/pointer_cast.hpp> extern "C" { #include <libavutil/imgutils.h> #include <libavutil/mastering_display_metadata.h> #include <libavutil/opt.h> #include <libavutil/pixdesc.h> } #include "cbs.h" #include "config.h" #include "globals.h" #include "input.h" #include "logging.h" #include "nvenc/nvenc_base.h" #include "platform/common.h" #include "sync.h" #include "video.h" #ifdef _WIN32 extern "C" { #include <libavutil/hwcontext_d3d11va.h> } #endif using namespace std::literals; namespace video { void free_ctx(AVCodecContext *ctx) { avcodec_free_context(&ctx); } void free_frame(AVFrame *frame) { av_frame_free(&frame); } void free_buffer(AVBufferRef *ref) { av_buffer_unref(&ref); } namespace nv { enum class profile_h264_e : int { high = 2, ///< High profile high_444p = 3, ///< High 4:4:4 Predictive profile }; enum class profile_hevc_e : int { main = 0, ///< Main profile main_10 = 1, ///< Main 10 profile rext = 2, ///< Rext profile }; } // namespace nv namespace qsv { enum class profile_h264_e : int { high = 100, ///< High profile high_444p = 244, ///< High 4:4:4 Predictive profile }; enum class profile_hevc_e : int { main = 1, ///< Main profile main_10 = 2, ///< Main 10 profile rext = 4, ///< RExt profile }; enum class profile_av1_e : int { main = 1, ///< Main profile high = 2, ///< High profile }; } // namespace qsv util::Either<avcodec_buffer_t, int> dxgi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *); util::Either<avcodec_buffer_t, int> vaapi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *); util::Either<avcodec_buffer_t, int> cuda_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *); util::Either<avcodec_buffer_t, int> vt_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *); class avcodec_software_encode_device_t: public platf::avcodec_encode_device_t { public: int convert(platf::img_t &img) override { // If we need to add aspect ratio padding, we need to scale into an intermediate output buffer bool requires_padding = (sw_frame->width != sws_output_frame->width || sw_frame->height != sws_output_frame->height); // Setup the input frame using the caller's img_t sws_input_frame->data[0] = img.data; sws_input_frame->linesize[0] = img.row_pitch; // Perform color conversion and scaling to the final size auto status = sws_scale_frame(sws.get(), requires_padding ? sws_output_frame.get() : sw_frame.get(), sws_input_frame.get()); if (status < 0) { char string[AV_ERROR_MAX_STRING_SIZE]; BOOST_LOG(error) << "Couldn't scale frame: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); return -1; } // If we require aspect ratio padding, copy the output frame into the final padded frame if (requires_padding) { auto fmt_desc = av_pix_fmt_desc_get((AVPixelFormat) sws_output_frame->format); auto planes = av_pix_fmt_count_planes((AVPixelFormat) sws_output_frame->format); for (int plane = 0; plane < planes; plane++) { auto shift_h = plane == 0 ? 0 : fmt_desc->log2_chroma_h; auto shift_w = plane == 0 ? 0 : fmt_desc->log2_chroma_w; auto offset = ((offsetW >> shift_w) * fmt_desc->comp[plane].step) + (offsetH >> shift_h) * sw_frame->linesize[plane]; // Copy line-by-line to preserve leading padding for each row for (int line = 0; line < sws_output_frame->height >> shift_h; line++) { memcpy(sw_frame->data[plane] + offset + (line * sw_frame->linesize[plane]), sws_output_frame->data[plane] + (line * sws_output_frame->linesize[plane]), (size_t) (sws_output_frame->width >> shift_w) * fmt_desc->comp[plane].step); } } } // If frame is not a software frame, it means we still need to transfer from main memory // to vram memory if (frame->hw_frames_ctx) { auto status = av_hwframe_transfer_data(frame, sw_frame.get(), 0); if (status < 0) { char string[AV_ERROR_MAX_STRING_SIZE]; BOOST_LOG(error) << "Failed to transfer image data to hardware frame: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); return -1; } } return 0; } int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx) override { this->frame = frame; // If it's a hwframe, allocate buffers for hardware if (hw_frames_ctx) { hw_frame.reset(frame); if (av_hwframe_get_buffer(hw_frames_ctx, frame, 0)) return -1; } else { sw_frame.reset(frame); } return 0; } void apply_colorspace() override { auto avcodec_colorspace = avcodec_colorspace_from_sunshine_colorspace(colorspace); sws_setColorspaceDetails(sws.get(), sws_getCoefficients(SWS_CS_DEFAULT), 0, sws_getCoefficients(avcodec_colorspace.software_format), avcodec_colorspace.range - 1, 0, 1 << 16, 1 << 16); } /** * When preserving aspect ratio, ensure that padding is black */ void prefill() { auto frame = sw_frame ? sw_frame.get() : this->frame; av_frame_get_buffer(frame, 0); av_frame_make_writable(frame); ptrdiff_t linesize[4] = { frame->linesize[0], frame->linesize[1], frame->linesize[2], frame->linesize[3] }; av_image_fill_black(frame->data, linesize, (AVPixelFormat) frame->format, frame->color_range, frame->width, frame->height); } int init(int in_width, int in_height, AVFrame *frame, AVPixelFormat format, bool hardware) { // If the device used is hardware, yet the image resides on main memory if (hardware) { sw_frame.reset(av_frame_alloc()); sw_frame->width = frame->width; sw_frame->height = frame->height; sw_frame->format = format; } else { this->frame = frame; } // Fill aspect ratio padding in the destination frame prefill(); auto out_width = frame->width; auto out_height = frame->height; // Ensure aspect ratio is maintained auto scalar = std::fminf((float) out_width / in_width, (float) out_height / in_height); out_width = in_width * scalar; out_height = in_height * scalar; sws_input_frame.reset(av_frame_alloc()); sws_input_frame->width = in_width; sws_input_frame->height = in_height; sws_input_frame->format = AV_PIX_FMT_BGR0; sws_output_frame.reset(av_frame_alloc()); sws_output_frame->width = out_width; sws_output_frame->height = out_height; sws_output_frame->format = format; // Result is always positive offsetW = (frame->width - out_width) / 2; offsetH = (frame->height - out_height) / 2; sws.reset(sws_alloc_context()); if (!sws) { return -1; } AVDictionary *options { nullptr }; av_dict_set_int(&options, "srcw", sws_input_frame->width, 0); av_dict_set_int(&options, "srch", sws_input_frame->height, 0); av_dict_set_int(&options, "src_format", sws_input_frame->format, 0); av_dict_set_int(&options, "dstw", sws_output_frame->width, 0); av_dict_set_int(&options, "dsth", sws_output_frame->height, 0); av_dict_set_int(&options, "dst_format", sws_output_frame->format, 0); av_dict_set_int(&options, "sws_flags", SWS_LANCZOS | SWS_ACCURATE_RND, 0); av_dict_set_int(&options, "threads", config::video.min_threads, 0); auto status = av_opt_set_dict(sws.get(), &options); av_dict_free(&options); if (status < 0) { char string[AV_ERROR_MAX_STRING_SIZE]; BOOST_LOG(error) << "Failed to set SWS options: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); return -1; } status = sws_init_context(sws.get(), nullptr, nullptr); if (status < 0) { char string[AV_ERROR_MAX_STRING_SIZE]; BOOST_LOG(error) << "Failed to initialize SWS: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); return -1; } return 0; } // Store ownership when frame is hw_frame avcodec_frame_t hw_frame; avcodec_frame_t sw_frame; avcodec_frame_t sws_input_frame; avcodec_frame_t sws_output_frame; sws_t sws; // Offset of input image to output frame in pixels int offsetW; int offsetH; }; enum flag_e : uint32_t { DEFAULT = 0, ///< Default flags PARALLEL_ENCODING = 1 << 1, ///< Capture and encoding can run concurrently on separate threads H264_ONLY = 1 << 2, ///< When HEVC is too heavy LIMITED_GOP_SIZE = 1 << 3, ///< Some encoders don't like it when you have an infinite GOP_SIZE. e.g. VAAPI SINGLE_SLICE_ONLY = 1 << 4, ///< Never use multiple slices. Older intel iGPU's ruin it for everyone else CBR_WITH_VBR = 1 << 5, ///< Use a VBR rate control mode to simulate CBR RELAXED_COMPLIANCE = 1 << 6, ///< Use FF_COMPLIANCE_UNOFFICIAL compliance mode NO_RC_BUF_LIMIT = 1 << 7, ///< Don't set rc_buffer_size REF_FRAMES_INVALIDATION = 1 << 8, ///< Support reference frames invalidation ALWAYS_REPROBE = 1 << 9, ///< This is an encoder of last resort and we want to aggressively probe for a better one YUV444_SUPPORT = 1 << 10, ///< Encoder may support 4:4:4 chroma sampling depending on hardware }; class avcodec_encode_session_t: public encode_session_t { public: avcodec_encode_session_t() = default; avcodec_encode_session_t(avcodec_ctx_t &&avcodec_ctx, std::unique_ptr<platf::avcodec_encode_device_t> encode_device, int inject): avcodec_ctx { std::move(avcodec_ctx) }, device { std::move(encode_device) }, inject { inject } {} avcodec_encode_session_t(avcodec_encode_session_t &&other) noexcept = default; ~avcodec_encode_session_t() { // Order matters here because the context relies on the hwdevice still being valid avcodec_ctx.reset(); device.reset(); } // Ensure objects are destroyed in the correct order avcodec_encode_session_t & operator=(avcodec_encode_session_t &&other) { device = std::move(other.device); avcodec_ctx = std::move(other.avcodec_ctx); replacements = std::move(other.replacements); sps = std::move(other.sps); vps = std::move(other.vps); inject = other.inject; return *this; } int convert(platf::img_t &img) override { if (!device) return -1; return device->convert(img); } void request_idr_frame() override { if (device && device->frame) { auto &frame = device->frame; frame->pict_type = AV_PICTURE_TYPE_I; frame->flags |= AV_FRAME_FLAG_KEY; } } void request_normal_frame() override { if (device && device->frame) { auto &frame = device->frame; frame->pict_type = AV_PICTURE_TYPE_NONE; frame->flags &= ~AV_FRAME_FLAG_KEY; } } void invalidate_ref_frames(int64_t first_frame, int64_t last_frame) override { BOOST_LOG(error) << "Encoder doesn't support reference frame invalidation"; request_idr_frame(); } avcodec_ctx_t avcodec_ctx; std::unique_ptr<platf::avcodec_encode_device_t> device; std::vector<packet_raw_t::replace_t> replacements; cbs::nal_t sps; cbs::nal_t vps; // inject sps/vps data into idr pictures int inject; }; class nvenc_encode_session_t: public encode_session_t { public: nvenc_encode_session_t(std::unique_ptr<platf::nvenc_encode_device_t> encode_device): device(std::move(encode_device)) { } int convert(platf::img_t &img) override { if (!device) return -1; return device->convert(img); } void request_idr_frame() override { force_idr = true; } void request_normal_frame() override { force_idr = false; } void invalidate_ref_frames(int64_t first_frame, int64_t last_frame) override { if (!device || !device->nvenc) return; if (!device->nvenc->invalidate_ref_frames(first_frame, last_frame)) { force_idr = true; } } nvenc::nvenc_encoded_frame encode_frame(uint64_t frame_index) { if (!device || !device->nvenc) return {}; auto result = device->nvenc->encode_frame(frame_index, force_idr); force_idr = false; return result; } private: std::unique_ptr<platf::nvenc_encode_device_t> device; bool force_idr = false; }; struct sync_session_ctx_t { safe::signal_t *join_event; safe::mail_raw_t::event_t<bool> shutdown_event; safe::mail_raw_t::queue_t<packet_t> packets; safe::mail_raw_t::event_t<bool> idr_events; safe::mail_raw_t::event_t<hdr_info_t> hdr_events; safe::mail_raw_t::event_t<input::touch_port_t> touch_port_events; config_t config; int frame_nr; void *channel_data; }; struct sync_session_t { sync_session_ctx_t *ctx; std::unique_ptr<encode_session_t> session; }; using encode_session_ctx_queue_t = safe::queue_t<sync_session_ctx_t>; using encode_e = platf::capture_e; struct capture_ctx_t { img_event_t images; config_t config; }; struct capture_thread_async_ctx_t { std::shared_ptr<safe::queue_t<capture_ctx_t>> capture_ctx_queue; std::thread capture_thread; safe::signal_t reinit_event; const encoder_t *encoder_p; sync_util::sync_t<std::weak_ptr<platf::display_t>> display_wp; }; struct capture_thread_sync_ctx_t { encode_session_ctx_queue_t encode_session_ctx_queue { 30 }; }; int start_capture_sync(capture_thread_sync_ctx_t &ctx); void end_capture_sync(capture_thread_sync_ctx_t &ctx); int start_capture_async(capture_thread_async_ctx_t &ctx); void end_capture_async(capture_thread_async_ctx_t &ctx); // Keep a reference counter to ensure the capture thread only runs when other threads have a reference to the capture thread auto capture_thread_async = safe::make_shared<capture_thread_async_ctx_t>(start_capture_async, end_capture_async); auto capture_thread_sync = safe::make_shared<capture_thread_sync_ctx_t>(start_capture_sync, end_capture_sync); #ifdef _WIN32 encoder_t nvenc { "nvenc"sv, std::make_unique<encoder_platform_formats_nvenc>( platf::mem_type_e::dxgi, platf::pix_fmt_e::nv12, platf::pix_fmt_e::p010, platf::pix_fmt_e::ayuv, platf::pix_fmt_e::yuv444p16), { {}, // Common options {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "av1_nvenc"s, }, { {}, // Common options {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "hevc_nvenc"s, }, { {}, // Common options {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "h264_nvenc"s, }, PARALLEL_ENCODING | REF_FRAMES_INVALIDATION | YUV444_SUPPORT // flags }; #elif !defined(__APPLE__) encoder_t nvenc { "nvenc"sv, std::make_unique<encoder_platform_formats_avcodec>( #ifdef _WIN32 AV_HWDEVICE_TYPE_D3D11VA, AV_HWDEVICE_TYPE_NONE, AV_PIX_FMT_D3D11, #else AV_HWDEVICE_TYPE_CUDA, AV_HWDEVICE_TYPE_NONE, AV_PIX_FMT_CUDA, #endif AV_PIX_FMT_NV12, AV_PIX_FMT_P010, AV_PIX_FMT_NONE, AV_PIX_FMT_NONE, #ifdef _WIN32 dxgi_init_avcodec_hardware_input_buffer #else cuda_init_avcodec_hardware_input_buffer #endif ), { // Common options { { "delay"s, 0 }, { "forced-idr"s, 1 }, { "zerolatency"s, 1 }, { "surfaces"s, 1 }, { "filler_data"s, false }, { "preset"s, &config::video.nv_legacy.preset }, { "tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY }, { "rc"s, NV_ENC_PARAMS_RC_CBR }, { "multipass"s, &config::video.nv_legacy.multipass }, { "aq"s, &config::video.nv_legacy.aq }, }, {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "av1_nvenc"s, }, { // Common options { { "delay"s, 0 }, { "forced-idr"s, 1 }, { "zerolatency"s, 1 }, { "surfaces"s, 1 }, { "preset"s, &config::video.nv_legacy.preset }, { "tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY }, { "rc"s, NV_ENC_PARAMS_RC_CBR }, { "multipass"s, &config::video.nv_legacy.multipass }, { "aq"s, &config::video.nv_legacy.aq }, }, { // SDR-specific options { "profile"s, (int) nv::profile_hevc_e::main }, }, { // HDR-specific options { "profile"s, (int) nv::profile_hevc_e::main_10 }, }, {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "hevc_nvenc"s, }, { { { "delay"s, 0 }, { "forced-idr"s, 1 }, { "zerolatency"s, 1 }, { "surfaces"s, 1 }, { "preset"s, &config::video.nv_legacy.preset }, { "tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY }, { "rc"s, NV_ENC_PARAMS_RC_CBR }, { "coder"s, &config::video.nv_legacy.h264_coder }, { "multipass"s, &config::video.nv_legacy.multipass }, { "aq"s, &config::video.nv_legacy.aq }, }, { // SDR-specific options { "profile"s, (int) nv::profile_h264_e::high }, }, {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "h264_nvenc"s, }, PARALLEL_ENCODING }; #endif #ifdef _WIN32 encoder_t quicksync { "quicksync"sv, std::make_unique<encoder_platform_formats_avcodec>( AV_HWDEVICE_TYPE_D3D11VA, AV_HWDEVICE_TYPE_QSV, AV_PIX_FMT_QSV, AV_PIX_FMT_NV12, AV_PIX_FMT_P010, AV_PIX_FMT_VUYX, AV_PIX_FMT_XV30, dxgi_init_avcodec_hardware_input_buffer), { // Common options { { "preset"s, &config::video.qsv.qsv_preset }, { "forced_idr"s, 1 }, { "async_depth"s, 1 }, { "low_delay_brc"s, 1 }, { "low_power"s, 1 }, }, { // SDR-specific options { "profile"s, (int) qsv::profile_av1_e::main }, }, { // HDR-specific options { "profile"s, (int) qsv::profile_av1_e::main }, }, { // YUV444 SDR-specific options { "profile"s, (int) qsv::profile_av1_e::high }, }, { // YUV444 HDR-specific options { "profile"s, (int) qsv::profile_av1_e::high }, }, {}, // Fallback options "av1_qsv"s, }, { // Common options { { "preset"s, &config::video.qsv.qsv_preset }, { "forced_idr"s, 1 }, { "async_depth"s, 1 }, { "low_delay_brc"s, 1 }, { "low_power"s, 1 }, { "recovery_point_sei"s, 0 }, { "pic_timing_sei"s, 0 }, }, { // SDR-specific options { "profile"s, (int) qsv::profile_hevc_e::main }, }, { // HDR-specific options { "profile"s, (int) qsv::profile_hevc_e::main_10 }, }, { // YUV444 SDR-specific options { "profile"s, (int) qsv::profile_hevc_e::rext }, }, { // YUV444 HDR-specific options { "profile"s, (int) qsv::profile_hevc_e::rext }, }, { // Fallback options { "low_power"s, []() { return config::video.qsv.qsv_slow_hevc ? 0 : 1; } }, }, "hevc_qsv"s, }, { // Common options { { "preset"s, &config::video.qsv.qsv_preset }, { "cavlc"s, &config::video.qsv.qsv_cavlc }, { "forced_idr"s, 1 }, { "async_depth"s, 1 }, { "low_delay_brc"s, 1 }, { "low_power"s, 1 }, { "recovery_point_sei"s, 0 }, { "vcm"s, 1 }, { "pic_timing_sei"s, 0 }, { "max_dec_frame_buffering"s, 1 }, }, { // SDR-specific options { "profile"s, (int) qsv::profile_h264_e::high }, }, {}, // HDR-specific options { // YUV444 SDR-specific options { "profile"s, (int) qsv::profile_h264_e::high_444p }, }, {}, // YUV444 HDR-specific options { // Fallback options { "low_power"s, 0 }, // Some old/low-end Intel GPUs don't support low power encoding }, "h264_qsv"s, }, PARALLEL_ENCODING | CBR_WITH_VBR | RELAXED_COMPLIANCE | NO_RC_BUF_LIMIT | YUV444_SUPPORT }; encoder_t amdvce { "amdvce"sv, std::make_unique<encoder_platform_formats_avcodec>( AV_HWDEVICE_TYPE_D3D11VA, AV_HWDEVICE_TYPE_NONE, AV_PIX_FMT_D3D11, AV_PIX_FMT_NV12, AV_PIX_FMT_P010, AV_PIX_FMT_NONE, AV_PIX_FMT_NONE, dxgi_init_avcodec_hardware_input_buffer), { // Common options { { "filler_data"s, false }, { "forced_idr"s, 1 }, { "latency"s, "lowest_latency"s }, { "skip_frame"s, 0 }, { "log_to_dbg"s, []() { return config::sunshine.min_log_level < 2 ? 1 : 0; } }, { "preencode"s, &config::video.amd.amd_preanalysis }, { "quality"s, &config::video.amd.amd_quality_av1 }, { "rc"s, &config::video.amd.amd_rc_av1 }, { "usage"s, &config::video.amd.amd_usage_av1 }, { "enforce_hrd"s, &config::video.amd.amd_enforce_hrd }, }, {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "av1_amf"s, }, { // Common options { { "filler_data"s, false }, { "forced_idr"s, 1 }, { "latency"s, 1 }, { "skip_frame"s, 0 }, { "log_to_dbg"s, []() { return config::sunshine.min_log_level < 2 ? 1 : 0; } }, { "gops_per_idr"s, 1 }, { "header_insertion_mode"s, "idr"s }, { "preencode"s, &config::video.amd.amd_preanalysis }, { "quality"s, &config::video.amd.amd_quality_hevc }, { "rc"s, &config::video.amd.amd_rc_hevc }, { "usage"s, &config::video.amd.amd_usage_hevc }, { "vbaq"s, &config::video.amd.amd_vbaq }, { "enforce_hrd"s, &config::video.amd.amd_enforce_hrd }, }, {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "hevc_amf"s, }, { // Common options { { "filler_data"s, false }, { "forced_idr"s, 1 }, { "latency"s, 1 }, { "frame_skipping"s, 0 }, { "log_to_dbg"s, []() { return config::sunshine.min_log_level < 2 ? 1 : 0; } }, { "preencode"s, &config::video.amd.amd_preanalysis }, { "quality"s, &config::video.amd.amd_quality_h264 }, { "rc"s, &config::video.amd.amd_rc_h264 }, { "usage"s, &config::video.amd.amd_usage_h264 }, { "vbaq"s, &config::video.amd.amd_vbaq }, { "enforce_hrd"s, &config::video.amd.amd_enforce_hrd }, }, {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options { // Fallback options { "usage"s, 2 /* AMF_VIDEO_ENCODER_USAGE_LOW_LATENCY */ }, // Workaround for https://github.com/GPUOpen-LibrariesAndSDKs/AMF/issues/410 }, "h264_amf"s, }, PARALLEL_ENCODING }; #endif encoder_t software { "software"sv, std::make_unique<encoder_platform_formats_avcodec>( AV_HWDEVICE_TYPE_NONE, AV_HWDEVICE_TYPE_NONE, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV444P10, nullptr), { // libsvtav1 takes different presets than libx264/libx265. // We set an infinite GOP length, use a low delay prediction structure, // force I frames to be key frames, and set max bitrate to default to work // around a FFmpeg bug with CBR mode. { { "svtav1-params"s, "keyint=-1:pred-struct=1:force-key-frames=1:mbr=0"s }, { "preset"s, &config::video.sw.svtav1_preset }, }, {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options #ifdef ENABLE_BROKEN_AV1_ENCODER // Due to bugs preventing on-demand IDR frames from working and very poor // real-time encoding performance, we do not enable libsvtav1 by default. // It is only suitable for testing AV1 until the IDR frame issue is fixed. "libsvtav1"s, #else {}, #endif }, { // x265's Info SEI is so long that it causes the IDR picture data to be // kicked to the 2nd packet in the frame, breaking Moonlight's parsing logic. // It also looks like gop_size isn't passed on to x265, so we have to set // 'keyint=-1' in the parameters ourselves. { { "forced-idr"s, 1 }, { "x265-params"s, "info=0:keyint=-1"s }, { "preset"s, &config::video.sw.sw_preset }, { "tune"s, &config::video.sw.sw_tune }, }, {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "libx265"s, }, { // Common options { { "preset"s, &config::video.sw.sw_preset }, { "tune"s, &config::video.sw.sw_tune }, }, {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "libx264"s, }, H264_ONLY | PARALLEL_ENCODING | ALWAYS_REPROBE | YUV444_SUPPORT }; #ifdef __linux__ encoder_t vaapi { "vaapi"sv, std::make_unique<encoder_platform_formats_avcodec>( AV_HWDEVICE_TYPE_VAAPI, AV_HWDEVICE_TYPE_NONE, AV_PIX_FMT_VAAPI, AV_PIX_FMT_NV12, AV_PIX_FMT_P010, AV_PIX_FMT_NONE, AV_PIX_FMT_NONE, vaapi_init_avcodec_hardware_input_buffer), { // Common options { { "async_depth"s, 1 }, { "idr_interval"s, std::numeric_limits<int>::max() }, }, {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "av1_vaapi"s, }, { // Common options { { "async_depth"s, 1 }, { "sei"s, 0 }, { "idr_interval"s, std::numeric_limits<int>::max() }, }, {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "hevc_vaapi"s, }, { // Common options { { "async_depth"s, 1 }, { "sei"s, 0 }, { "idr_interval"s, std::numeric_limits<int>::max() }, }, {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "h264_vaapi"s, }, // RC buffer size will be set in platform code if supported LIMITED_GOP_SIZE | PARALLEL_ENCODING | NO_RC_BUF_LIMIT }; #endif #ifdef __APPLE__ encoder_t videotoolbox { "videotoolbox"sv, std::make_unique<encoder_platform_formats_avcodec>( AV_HWDEVICE_TYPE_VIDEOTOOLBOX, AV_HWDEVICE_TYPE_NONE, AV_PIX_FMT_VIDEOTOOLBOX, AV_PIX_FMT_NV12, AV_PIX_FMT_P010, AV_PIX_FMT_NONE, AV_PIX_FMT_NONE, vt_init_avcodec_hardware_input_buffer), { // Common options { { "allow_sw"s, &config::video.vt.vt_allow_sw }, { "require_sw"s, &config::video.vt.vt_require_sw }, { "realtime"s, &config::video.vt.vt_realtime }, { "prio_speed"s, 1 }, { "max_ref_frames"s, 1 }, }, {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "av1_videotoolbox"s, }, { // Common options { { "allow_sw"s, &config::video.vt.vt_allow_sw }, { "require_sw"s, &config::video.vt.vt_require_sw }, { "realtime"s, &config::video.vt.vt_realtime }, { "prio_speed"s, 1 }, { "max_ref_frames"s, 1 }, }, {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options {}, // Fallback options "hevc_videotoolbox"s, }, { // Common options { { "allow_sw"s, &config::video.vt.vt_allow_sw }, { "require_sw"s, &config::video.vt.vt_require_sw }, { "realtime"s, &config::video.vt.vt_realtime }, { "prio_speed"s, 1 }, { "max_ref_frames"s, 1 }, }, {}, // SDR-specific options {}, // HDR-specific options {}, // YUV444 SDR-specific options {}, // YUV444 HDR-specific options { // Fallback options { "flags"s, "-low_delay" }, }, "h264_videotoolbox"s, }, DEFAULT }; #endif static const std::vector<encoder_t *> encoders { #ifndef __APPLE__ &nvenc, #endif #ifdef _WIN32 &quicksync, &amdvce, #endif #ifdef __linux__ &vaapi, #endif #ifdef __APPLE__ &videotoolbox, #endif &software }; static encoder_t *chosen_encoder; int active_hevc_mode; int active_av1_mode; bool last_encoder_probe_supported_ref_frames_invalidation = false; std::array<bool, 3> last_encoder_probe_supported_yuv444_for_codec = {}; void reset_display(std::shared_ptr<platf::display_t> &disp, const platf::mem_type_e &type, const std::string &display_name, const config_t &config) { // We try this twice, in case we still get an error on reinitialization for (int x = 0; x < 2; ++x) { disp.reset(); disp = platf::display(type, display_name, config); if (disp) { break; } // The capture code depends on us to sleep between failures std::this_thread::sleep_for(200ms); } } /** * @brief Update the list of display names before or during a stream. * @details This will attempt to keep `current_display_index` pointing at the same display. * @param dev_type The encoder device type used for display lookup. * @param display_names The list of display names to repopulate. * @param current_display_index The current display index or -1 if not yet known. */ void refresh_displays(platf::mem_type_e dev_type, std::vector<std::string> &display_names, int &current_display_index) { std::string current_display_name; // If we have a current display index, let's start with that if (current_display_index >= 0 && current_display_index < display_names.size()) { current_display_name = display_names.at(current_display_index); } // Refresh the display names auto old_display_names = std::move(display_names); display_names = platf::display_names(dev_type); // If we now have no displays, let's put the old display array back and fail if (display_names.empty() && !old_display_names.empty()) { BOOST_LOG(error) << "No displays were found after reenumeration!"sv; display_names = std::move(old_display_names); return; } else if (display_names.empty()) { display_names.emplace_back(config::video.output_name); } // We now have a new display name list, so reset the index back to 0 current_display_index = 0; // If we had a name previously, let's try to find it in the new list if (!current_display_name.empty()) { for (int x = 0; x < display_names.size(); ++x) { if (display_names[x] == current_display_name) { current_display_index = x; return; } } // The old display was removed, so we'll start back at the first display again BOOST_LOG(warning) << "Previous active display ["sv << current_display_name << "] is no longer present"sv; } else { for (int x = 0; x < display_names.size(); ++x) { if (display_names[x] == config::video.output_name) { current_display_index = x; return; } } } } void captureThread( std::shared_ptr<safe::queue_t<capture_ctx_t>> capture_ctx_queue, sync_util::sync_t<std::weak_ptr<platf::display_t>> &display_wp, safe::signal_t &reinit_event, const encoder_t &encoder) { std::vector<capture_ctx_t> capture_ctxs; auto fg = util::fail_guard([&]() { capture_ctx_queue->stop(); // Stop all sessions listening to this thread for (auto &capture_ctx : capture_ctxs) { capture_ctx.images->stop(); } for (auto &capture_ctx : capture_ctx_queue->unsafe()) { capture_ctx.images->stop(); } }); auto switch_display_event = mail::man->event<int>(mail::switch_display); // Wait for the initial capture context or a request to stop the queue auto initial_capture_ctx = capture_ctx_queue->pop(); if (!initial_capture_ctx) { return; } capture_ctxs.emplace_back(std::move(*initial_capture_ctx)); // Get all the monitor names now, rather than at boot, to // get the most up-to-date list available monitors std::vector<std::string> display_names; int display_p = -1; refresh_displays(encoder.platform_formats->dev_type, display_names, display_p); auto disp = platf::display(encoder.platform_formats->dev_type, display_names[display_p], capture_ctxs.front().config); if (!disp) { return; } display_wp = disp; constexpr auto capture_buffer_size = 12; std::list<std::shared_ptr<platf::img_t>> imgs(capture_buffer_size); std::vector<std::optional<std::chrono::steady_clock::time_point>> imgs_used_timestamps; const std::chrono::seconds trim_timeot = 3s; auto trim_imgs = [&]() { // count allocated and used within current pool size_t allocated_count = 0; size_t used_count = 0; for (const auto &img : imgs) { if (img) { allocated_count += 1; if (img.use_count() > 1) { used_count += 1; } } } // remember the timestamp of currently used count const auto now = std::chrono::steady_clock::now(); if (imgs_used_timestamps.size() <= used_count) { imgs_used_timestamps.resize(used_count + 1); } imgs_used_timestamps[used_count] = now; // decide whether to trim allocated unused above the currently used count // based on last used timestamp and universal timeout size_t trim_target = used_count; for (size_t i = used_count; i < imgs_used_timestamps.size(); i++) { if (imgs_used_timestamps[i] && now - *imgs_used_timestamps[i] < trim_timeot) { trim_target = i; } } // trim allocated unused above the newly decided trim target if (allocated_count > trim_target) { size_t to_trim = allocated_count - trim_target; // prioritize trimming least recently used for (auto it = imgs.rbegin(); it != imgs.rend(); it++) { auto &img = *it; if (img && img.use_count() == 1) { img.reset(); to_trim -= 1; if (to_trim == 0) break; } } // forget timestamps that no longer relevant imgs_used_timestamps.resize(trim_target + 1); } }; auto pull_free_image_callback = [&](std::shared_ptr<platf::img_t> &img_out) -> bool { img_out.reset(); while (capture_ctx_queue->running()) { // pick first allocated but unused for (auto it = imgs.begin(); it != imgs.end(); it++) { if (*it && it->use_count() == 1) { img_out = *it; if (it != imgs.begin()) { // move image to the front of the list to prioritize its reusal imgs.erase(it); imgs.push_front(img_out); } break; } } // otherwise pick first unallocated if (!img_out) { for (auto it = imgs.begin(); it != imgs.end(); it++) { if (!*it) { // allocate image *it = disp->alloc_img(); img_out = *it; if (it != imgs.begin()) { // move image to the front of the list to prioritize its reusal imgs.erase(it); imgs.push_front(img_out); } break; } } } if (img_out) { // trim allocated but unused portion of the pool based on timeouts trim_imgs(); img_out->frame_timestamp.reset(); return true; } else { // sleep and retry if image pool is full std::this_thread::sleep_for(1ms); } } return false; }; // Capture takes place on this thread platf::adjust_thread_priority(platf::thread_priority_e::critical); while (capture_ctx_queue->running()) { bool artificial_reinit = false; auto push_captured_image_callback = [&](std::shared_ptr<platf::img_t> &&img, bool frame_captured) -> bool { KITTY_WHILE_LOOP(auto capture_ctx = std::begin(capture_ctxs), capture_ctx != std::end(capture_ctxs), { if (!capture_ctx->images->running()) { capture_ctx = capture_ctxs.erase(capture_ctx); continue; } if (frame_captured) { capture_ctx->images->raise(img); } ++capture_ctx; }) if (!capture_ctx_queue->running()) { return false; } while (capture_ctx_queue->peek()) { capture_ctxs.emplace_back(std::move(*capture_ctx_queue->pop())); } if (switch_display_event->peek()) { artificial_reinit = true; return false; } return true; }; auto status = disp->capture(push_captured_image_callback, pull_free_image_callback, &display_cursor); if (artificial_reinit && status != platf::capture_e::error) { status = platf::capture_e::reinit; artificial_reinit = false; } switch (status) { case platf::capture_e::reinit: { reinit_event.raise(true); // Some classes of images contain references to the display --> display won't delete unless img is deleted for (auto &img : imgs) { img.reset(); } // display_wp is modified in this thread only // Wait for the other shared_ptr's of display to be destroyed. // New displays will only be created in this thread. while (display_wp->use_count() != 1) { // Free images that weren't consumed by the encoders. These can reference the display and prevent // the ref count from reaching 1. We do this here rather than on the encoder thread to avoid race // conditions where the encoding loop might free a good frame after reinitializing if we capture // a new frame here before the encoder has finished reinitializing. KITTY_WHILE_LOOP(auto capture_ctx = std::begin(capture_ctxs), capture_ctx != std::end(capture_ctxs), { if (!capture_ctx->images->running()) { capture_ctx = capture_ctxs.erase(capture_ctx); continue; } while (capture_ctx->images->peek()) { capture_ctx->images->pop(); } ++capture_ctx; }); std::this_thread::sleep_for(20ms); } while (capture_ctx_queue->running()) { // Release the display before reenumerating displays, since some capture backends // only support a single display session per device/application. disp.reset(); // Refresh display names since a display removal might have caused the reinitialization refresh_displays(encoder.platform_formats->dev_type, display_names, display_p); // Process any pending display switch with the new list of displays if (switch_display_event->peek()) { display_p = std::clamp(*switch_display_event->pop(), 0, (int) display_names.size() - 1); } // reset_display() will sleep between retries reset_display(disp, encoder.platform_formats->dev_type, display_names[display_p], capture_ctxs.front().config); if (disp) { break; } } if (!disp) { return; } display_wp = disp; reinit_event.reset(); continue; } case platf::capture_e::error: case platf::capture_e::ok: case platf::capture_e::timeout: case platf::capture_e::interrupted: return; default: BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']'; return; } } } int encode_avcodec(int64_t frame_nr, avcodec_encode_session_t &session, safe::mail_raw_t::queue_t<packet_t> &packets, void *channel_data, std::optional<std::chrono::steady_clock::time_point> frame_timestamp) { auto &frame = session.device->frame; frame->pts = frame_nr; auto &ctx = session.avcodec_ctx; auto &sps = session.sps; auto &vps = session.vps; // send the frame to the encoder auto ret = avcodec_send_frame(ctx.get(), frame); if (ret < 0) { char err_str[AV_ERROR_MAX_STRING_SIZE] { 0 }; BOOST_LOG(error) << "Could not send a frame for encoding: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, ret); return -1; } while (ret >= 0) { auto packet = std::make_unique<packet_raw_avcodec>(); auto av_packet = packet.get()->av_packet; ret = avcodec_receive_packet(ctx.get(), av_packet); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { return 0; } else if (ret < 0) { return ret; } if (av_packet->flags & AV_PKT_FLAG_KEY) { BOOST_LOG(debug) << "Frame "sv << frame_nr << ": IDR Keyframe (AV_FRAME_FLAG_KEY)"sv; } if ((frame->flags & AV_FRAME_FLAG_KEY) && !(av_packet->flags & AV_PKT_FLAG_KEY)) { BOOST_LOG(error) << "Encoder did not produce IDR frame when requested!"sv; } if (session.inject) { if (session.inject == 1) { auto h264 = cbs::make_sps_h264(ctx.get(), av_packet); sps = std::move(h264.sps); } else { auto hevc = cbs::make_sps_hevc(ctx.get(), av_packet); sps = std::move(hevc.sps); vps = std::move(hevc.vps); session.replacements.emplace_back( std::string_view((char *) std::begin(vps.old), vps.old.size()), std::string_view((char *) std::begin(vps._new), vps._new.size())); } session.inject = 0; session.replacements.emplace_back( std::string_view((char *) std::begin(sps.old), sps.old.size()), std::string_view((char *) std::begin(sps._new), sps._new.size())); } if (av_packet && av_packet->pts == frame_nr) { packet->frame_timestamp = frame_timestamp; } packet->replacements = &session.replacements; packet->channel_data = channel_data; packets->raise(std::move(packet)); } return 0; } int encode_nvenc(int64_t frame_nr, nvenc_encode_session_t &session, safe::mail_raw_t::queue_t<packet_t> &packets, void *channel_data, std::optional<std::chrono::steady_clock::time_point> frame_timestamp) { auto encoded_frame = session.encode_frame(frame_nr); if (encoded_frame.data.empty()) { BOOST_LOG(error) << "NvENC returned empty packet"; return -1; } if (frame_nr != encoded_frame.frame_index) { BOOST_LOG(error) << "NvENC frame index mismatch " << frame_nr << " " << encoded_frame.frame_index; } auto packet = std::make_unique<packet_raw_generic>(std::move(encoded_frame.data), encoded_frame.frame_index, encoded_frame.idr); packet->channel_data = channel_data; packet->after_ref_frame_invalidation = encoded_frame.after_ref_frame_invalidation; packet->frame_timestamp = frame_timestamp; packets->raise(std::move(packet)); return 0; } int encode(int64_t frame_nr, encode_session_t &session, safe::mail_raw_t::queue_t<packet_t> &packets, void *channel_data, std::optional<std::chrono::steady_clock::time_point> frame_timestamp) { if (auto avcodec_session = dynamic_cast<avcodec_encode_session_t *>(&session)) { return encode_avcodec(frame_nr, *avcodec_session, packets, channel_data, frame_timestamp); } else if (auto nvenc_session = dynamic_cast<nvenc_encode_session_t *>(&session)) { return encode_nvenc(frame_nr, *nvenc_session, packets, channel_data, frame_timestamp); } return -1; } std::unique_ptr<avcodec_encode_session_t> make_avcodec_encode_session(platf::display_t *disp, const encoder_t &encoder, const config_t &config, int width, int height, std::unique_ptr<platf::avcodec_encode_device_t> encode_device) { auto platform_formats = dynamic_cast<const encoder_platform_formats_avcodec *>(encoder.platform_formats.get()); if (!platform_formats) { return nullptr; } bool hardware = platform_formats->avcodec_base_dev_type != AV_HWDEVICE_TYPE_NONE; auto &video_format = encoder.codec_from_config(config); if (!video_format[encoder_t::PASSED] || !disp->is_codec_supported(video_format.name, config)) { BOOST_LOG(error) << encoder.name << ": "sv << video_format.name << " mode not supported"sv; return nullptr; } if (config.dynamicRange && !video_format[encoder_t::DYNAMIC_RANGE]) { BOOST_LOG(error) << video_format.name << ": dynamic range not supported"sv; return nullptr; } if (config.chromaSamplingType == 1 && !video_format[encoder_t::YUV444]) { BOOST_LOG(error) << video_format.name << ": YUV 4:4:4 not supported"sv; return nullptr; } auto codec = avcodec_find_encoder_by_name(video_format.name.c_str()); if (!codec) { BOOST_LOG(error) << "Couldn't open ["sv << video_format.name << ']'; return nullptr; } auto colorspace = encode_device->colorspace; auto sw_fmt = (colorspace.bit_depth == 8 && config.chromaSamplingType == 0) ? platform_formats->avcodec_pix_fmt_8bit : (colorspace.bit_depth == 8 && config.chromaSamplingType == 1) ? platform_formats->avcodec_pix_fmt_yuv444_8bit : (colorspace.bit_depth == 10 && config.chromaSamplingType == 0) ? platform_formats->avcodec_pix_fmt_10bit : (colorspace.bit_depth == 10 && config.chromaSamplingType == 1) ? platform_formats->avcodec_pix_fmt_yuv444_10bit : AV_PIX_FMT_NONE; // Allow up to 1 retry to apply the set of fallback options. // // Note: If we later end up needing multiple sets of // fallback options, we may need to allow more retries // to try applying each set. avcodec_ctx_t ctx; for (int retries = 0; retries < 2; retries++) { ctx.reset(avcodec_alloc_context3(codec)); ctx->width = config.width; ctx->height = config.height; ctx->time_base = AVRational { 1, config.framerate }; ctx->framerate = AVRational { config.framerate, 1 }; switch (config.videoFormat) { case 0: // 10-bit h264 encoding is not supported by our streaming protocol assert(!config.dynamicRange); ctx->profile = (config.chromaSamplingType == 1) ? FF_PROFILE_H264_HIGH_444_PREDICTIVE : FF_PROFILE_H264_HIGH; break; case 1: if (config.chromaSamplingType == 1) { // HEVC uses the same RExt profile for both 8 and 10 bit YUV 4:4:4 encoding ctx->profile = FF_PROFILE_HEVC_REXT; } else { ctx->profile = config.dynamicRange ? FF_PROFILE_HEVC_MAIN_10 : FF_PROFILE_HEVC_MAIN; } break; case 2: // AV1 supports both 8 and 10 bit encoding with the same Main profile // but YUV 4:4:4 sampling requires High profile ctx->profile = (config.chromaSamplingType == 1) ? FF_PROFILE_AV1_HIGH : FF_PROFILE_AV1_MAIN; break; } // B-frames delay decoder output, so never use them ctx->max_b_frames = 0; // Use an infinite GOP length since I-frames are generated on demand ctx->gop_size = encoder.flags & LIMITED_GOP_SIZE ? std::numeric_limits<std::int16_t>::max() : std::numeric_limits<int>::max(); ctx->keyint_min = std::numeric_limits<int>::max(); // Some client decoders have limits on the number of reference frames if (config.numRefFrames) { if (video_format[encoder_t::REF_FRAMES_RESTRICT]) { ctx->refs = config.numRefFrames; } else { BOOST_LOG(warning) << "Client requested reference frame limit, but encoder doesn't support it!"sv; } } // We forcefully reset the flags to avoid clash on reuse of AVCodecContext ctx->flags = 0; ctx->flags |= AV_CODEC_FLAG_CLOSED_GOP | AV_CODEC_FLAG_LOW_DELAY; ctx->flags2 |= AV_CODEC_FLAG2_FAST; auto avcodec_colorspace = avcodec_colorspace_from_sunshine_colorspace(colorspace); ctx->color_range = avcodec_colorspace.range; ctx->color_primaries = avcodec_colorspace.primaries; ctx->color_trc = avcodec_colorspace.transfer_function; ctx->colorspace = avcodec_colorspace.matrix; // Used by cbs::make_sps_hevc ctx->sw_pix_fmt = sw_fmt; if (hardware) { avcodec_buffer_t encoding_stream_context; ctx->pix_fmt = platform_formats->avcodec_dev_pix_fmt; // Create the base hwdevice context auto buf_or_error = platform_formats->init_avcodec_hardware_input_buffer(encode_device.get()); if (buf_or_error.has_right()) { return nullptr; } encoding_stream_context = std::move(buf_or_error.left()); // If this encoder requires derivation from the base, derive the desired type if (platform_formats->avcodec_derived_dev_type != AV_HWDEVICE_TYPE_NONE) { avcodec_buffer_t derived_context; // Allow the hwdevice to prepare for this type of context to be derived if (encode_device->prepare_to_derive_context(platform_formats->avcodec_derived_dev_type)) { return nullptr; } auto err = av_hwdevice_ctx_create_derived(&derived_context, platform_formats->avcodec_derived_dev_type, encoding_stream_context.get(), 0); if (err) { char err_str[AV_ERROR_MAX_STRING_SIZE] { 0 }; BOOST_LOG(error) << "Failed to derive device context: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); return nullptr; } encoding_stream_context = std::move(derived_context); } // Initialize avcodec hardware frames { avcodec_buffer_t frame_ref { av_hwframe_ctx_alloc(encoding_stream_context.get()) }; auto frame_ctx = (AVHWFramesContext *) frame_ref->data; frame_ctx->format = ctx->pix_fmt; frame_ctx->sw_format = sw_fmt; frame_ctx->height = ctx->height; frame_ctx->width = ctx->width; frame_ctx->initial_pool_size = 0; // Allow the hwdevice to modify hwframe context parameters encode_device->init_hwframes(frame_ctx); if (auto err = av_hwframe_ctx_init(frame_ref.get()); err < 0) { return nullptr; } ctx->hw_frames_ctx = av_buffer_ref(frame_ref.get()); } ctx->slices = config.slicesPerFrame; } else /* software */ { ctx->pix_fmt = sw_fmt; // Clients will request for the fewest slices per frame to get the // most efficient encode, but we may want to provide more slices than // requested to ensure we have enough parallelism for good performance. ctx->slices = std::max(config.slicesPerFrame, config::video.min_threads); } if (encoder.flags & SINGLE_SLICE_ONLY) { ctx->slices = 1; } ctx->thread_type = FF_THREAD_SLICE; ctx->thread_count = ctx->slices; AVDictionary *options { nullptr }; auto handle_option = [&options](const encoder_t::option_t &option) { std::visit( util::overloaded { [&](int v) { av_dict_set_int(&options, option.name.c_str(), v, 0); }, [&](int *v) { av_dict_set_int(&options, option.name.c_str(), *v, 0); }, [&](std::optional<int> *v) { if(*v) av_dict_set_int(&options, option.name.c_str(), **v, 0); }, [&](std::function<int()> v) { av_dict_set_int(&options, option.name.c_str(), v(), 0); }, [&](const std::string &v) { av_dict_set(&options, option.name.c_str(), v.c_str(), 0); }, [&](std::string *v) { if(!v->empty()) av_dict_set(&options, option.name.c_str(), v->c_str(), 0); } }, option.value); }; // Apply common options, then format-specific overrides for (auto &option : video_format.common_options) { handle_option(option); } for (auto &option : (config.dynamicRange ? video_format.hdr_options : video_format.sdr_options)) { handle_option(option); } if (config.chromaSamplingType == 1) { for (auto &option : (config.dynamicRange ? video_format.hdr444_options : video_format.sdr444_options)) { handle_option(option); } } if (retries > 0) { for (auto &option : video_format.fallback_options) { handle_option(option); } } auto bitrate = config.bitrate * 1000; ctx->rc_max_rate = bitrate; ctx->bit_rate = bitrate; if (encoder.flags & CBR_WITH_VBR) { // Ensure rc_max_bitrate != bit_rate to force VBR mode ctx->bit_rate--; } else { ctx->rc_min_rate = bitrate; } if (encoder.flags & RELAXED_COMPLIANCE) { ctx->strict_std_compliance = FF_COMPLIANCE_UNOFFICIAL; } if (!(encoder.flags & NO_RC_BUF_LIMIT)) { if (!hardware && (ctx->slices > 1 || config.videoFormat == 1)) { // Use a larger rc_buffer_size for software encoding when slices are enabled, // because libx264 can severely degrade quality if the buffer is too small. // libx265 encounters this issue more frequently, so always scale the // buffer by 1.5x for software HEVC encoding. ctx->rc_buffer_size = bitrate / ((config.framerate * 10) / 15); } else { ctx->rc_buffer_size = bitrate / config.framerate; #ifndef __APPLE__ if (encoder.name == "nvenc" && config::video.nv_legacy.vbv_percentage_increase > 0) { ctx->rc_buffer_size += ctx->rc_buffer_size * config::video.nv_legacy.vbv_percentage_increase / 100; } #endif } } // Allow the encoding device a final opportunity to set/unset or override any options encode_device->init_codec_options(ctx.get(), &options); if (auto status = avcodec_open2(ctx.get(), codec, &options)) { char err_str[AV_ERROR_MAX_STRING_SIZE] { 0 }; if (!video_format.fallback_options.empty() && retries == 0) { BOOST_LOG(info) << "Retrying with fallback configuration options for ["sv << video_format.name << "] after error: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, status); continue; } else { BOOST_LOG(error) << "Could not open codec ["sv << video_format.name << "]: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, status); return nullptr; } } // Successfully opened the codec break; } avcodec_frame_t frame { av_frame_alloc() }; frame->format = ctx->pix_fmt; frame->width = ctx->width; frame->height = ctx->height; frame->color_range = ctx->color_range; frame->color_primaries = ctx->color_primaries; frame->color_trc = ctx->color_trc; frame->colorspace = ctx->colorspace; frame->chroma_location = ctx->chroma_sample_location; // Attach HDR metadata to the AVFrame if (colorspace_is_hdr(colorspace)) { SS_HDR_METADATA hdr_metadata; if (disp->get_hdr_metadata(hdr_metadata)) { auto mdm = av_mastering_display_metadata_create_side_data(frame.get()); mdm->display_primaries[0][0] = av_make_q(hdr_metadata.displayPrimaries[0].x, 50000); mdm->display_primaries[0][1] = av_make_q(hdr_metadata.displayPrimaries[0].y, 50000); mdm->display_primaries[1][0] = av_make_q(hdr_metadata.displayPrimaries[1].x, 50000); mdm->display_primaries[1][1] = av_make_q(hdr_metadata.displayPrimaries[1].y, 50000); mdm->display_primaries[2][0] = av_make_q(hdr_metadata.displayPrimaries[2].x, 50000); mdm->display_primaries[2][1] = av_make_q(hdr_metadata.displayPrimaries[2].y, 50000); mdm->white_point[0] = av_make_q(hdr_metadata.whitePoint.x, 50000); mdm->white_point[1] = av_make_q(hdr_metadata.whitePoint.y, 50000); mdm->min_luminance = av_make_q(hdr_metadata.minDisplayLuminance, 10000); mdm->max_luminance = av_make_q(hdr_metadata.maxDisplayLuminance, 1); mdm->has_luminance = hdr_metadata.maxDisplayLuminance != 0 ? 1 : 0; mdm->has_primaries = hdr_metadata.displayPrimaries[0].x != 0 ? 1 : 0; if (hdr_metadata.maxContentLightLevel != 0 || hdr_metadata.maxFrameAverageLightLevel != 0) { auto clm = av_content_light_metadata_create_side_data(frame.get()); clm->MaxCLL = hdr_metadata.maxContentLightLevel; clm->MaxFALL = hdr_metadata.maxFrameAverageLightLevel; } } else { BOOST_LOG(error) << "Couldn't get display hdr metadata when colorspace selection indicates it should have one"; } } std::unique_ptr<platf::avcodec_encode_device_t> encode_device_final; if (!encode_device->data) { auto software_encode_device = std::make_unique<avcodec_software_encode_device_t>(); if (software_encode_device->init(width, height, frame.get(), sw_fmt, hardware)) { return nullptr; } software_encode_device->colorspace = colorspace; encode_device_final = std::move(software_encode_device); } else { encode_device_final = std::move(encode_device); } if (encode_device_final->set_frame(frame.release(), ctx->hw_frames_ctx)) { return nullptr; } encode_device_final->apply_colorspace(); auto session = std::make_unique<avcodec_encode_session_t>( std::move(ctx), std::move(encode_device_final), // 0 ==> don't inject, 1 ==> inject for h264, 2 ==> inject for hevc config.videoFormat <= 1 ? (1 - (int) video_format[encoder_t::VUI_PARAMETERS]) * (1 + config.videoFormat) : 0); return session; } std::unique_ptr<nvenc_encode_session_t> make_nvenc_encode_session(const config_t &client_config, std::unique_ptr<platf::nvenc_encode_device_t> encode_device) { if (!encode_device->init_encoder(client_config, encode_device->colorspace)) { return nullptr; } return std::make_unique<nvenc_encode_session_t>(std::move(encode_device)); } std::unique_ptr<encode_session_t> make_encode_session(platf::display_t *disp, const encoder_t &encoder, const config_t &config, int width, int height, std::unique_ptr<platf::encode_device_t> encode_device) { if (dynamic_cast<platf::avcodec_encode_device_t *>(encode_device.get())) { auto avcodec_encode_device = boost::dynamic_pointer_cast<platf::avcodec_encode_device_t>(std::move(encode_device)); return make_avcodec_encode_session(disp, encoder, config, width, height, std::move(avcodec_encode_device)); } else if (dynamic_cast<platf::nvenc_encode_device_t *>(encode_device.get())) { auto nvenc_encode_device = boost::dynamic_pointer_cast<platf::nvenc_encode_device_t>(std::move(encode_device)); return make_nvenc_encode_session(config, std::move(nvenc_encode_device)); } return nullptr; } void encode_run( int &frame_nr, // Store progress of the frame number safe::mail_t mail, img_event_t images, config_t config, std::shared_ptr<platf::display_t> disp, std::unique_ptr<platf::encode_device_t> encode_device, safe::signal_t &reinit_event, const encoder_t &encoder, void *channel_data) { auto session = make_encode_session(disp.get(), encoder, config, disp->width, disp->height, std::move(encode_device)); if (!session) { return; } // set minimum frame time, avoiding violation of client-requested target framerate auto minimum_frame_time = std::chrono::milliseconds(1000 / std::min(config.framerate, (config::video.min_fps_factor * 10))); BOOST_LOG(debug) << "Minimum frame time set to "sv << minimum_frame_time.count() << "ms, based on min fps factor of "sv << config::video.min_fps_factor << "."sv; auto shutdown_event = mail->event<bool>(mail::shutdown); auto packets = mail::man->queue<packet_t>(mail::video_packets); auto idr_events = mail->event<bool>(mail::idr); auto invalidate_ref_frames_events = mail->event<std::pair<int64_t, int64_t>>(mail::invalidate_ref_frames); { // Load a dummy image into the AVFrame to ensure we have something to encode // even if we timeout waiting on the first frame. This is a relatively large // allocation which can be freed immediately after convert(), so we do this // in a separate scope. auto dummy_img = disp->alloc_img(); if (!dummy_img || disp->dummy_img(dummy_img.get()) || session->convert(*dummy_img)) { return; } } while (true) { // Break out of the encoding loop if any of the following are true: // a) The stream is ending // b) Sunshine is quitting // c) The capture side is waiting to reinit and we've encoded at least one frame // // If we have to reinit before we have received any captured frames, we will encode // the blank dummy frame just to let Moonlight know that we're alive. if (shutdown_event->peek() || !images->running() || (reinit_event.peek() && frame_nr > 1)) { break; } bool requested_idr_frame = false; while (invalidate_ref_frames_events->peek()) { if (auto frames = invalidate_ref_frames_events->pop(0ms)) { session->invalidate_ref_frames(frames->first, frames->second); } } if (idr_events->peek()) { requested_idr_frame = true; idr_events->pop(); } if (requested_idr_frame) { session->request_idr_frame(); } std::optional<std::chrono::steady_clock::time_point> frame_timestamp; // Encode at a minimum FPS to avoid image quality issues with static content if (!requested_idr_frame || images->peek()) { if (auto img = images->pop(minimum_frame_time)) { frame_timestamp = img->frame_timestamp; if (session->convert(*img)) { BOOST_LOG(error) << "Could not convert image"sv; return; } } else if (!images->running()) { break; } } if (encode(frame_nr++, *session, packets, channel_data, frame_timestamp)) { BOOST_LOG(error) << "Could not encode video packet"sv; return; } session->request_normal_frame(); } } input::touch_port_t make_port(platf::display_t *display, const config_t &config) { float wd = display->width; float hd = display->height; float wt = config.width; float ht = config.height; auto scalar = std::fminf(wt / wd, ht / hd); auto w2 = scalar * wd; auto h2 = scalar * hd; auto offsetX = (config.width - w2) * 0.5f; auto offsetY = (config.height - h2) * 0.5f; return input::touch_port_t { { display->offset_x, display->offset_y, config.width, config.height, }, display->env_width, display->env_height, offsetX, offsetY, 1.0f / scalar, }; } std::unique_ptr<platf::encode_device_t> make_encode_device(platf::display_t &disp, const encoder_t &encoder, const config_t &config) { std::unique_ptr<platf::encode_device_t> result; auto colorspace = colorspace_from_client_config(config, disp.is_hdr()); platf::pix_fmt_e pix_fmt; if (config.chromaSamplingType == 1) { // YUV 4:4:4 if (!(encoder.flags & YUV444_SUPPORT)) { // Encoder can't support YUV 4:4:4 regardless of hardware capabilities return {}; } pix_fmt = (colorspace.bit_depth == 10) ? encoder.platform_formats->pix_fmt_yuv444_10bit : encoder.platform_formats->pix_fmt_yuv444_8bit; } else { // YUV 4:2:0 pix_fmt = (colorspace.bit_depth == 10) ? encoder.platform_formats->pix_fmt_10bit : encoder.platform_formats->pix_fmt_8bit; } { auto encoder_name = encoder.codec_from_config(config).name; BOOST_LOG(info) << "Creating encoder " << logging::bracket(encoder_name); auto color_coding = colorspace.colorspace == colorspace_e::bt2020 ? "HDR (Rec. 2020 + SMPTE 2084 PQ)" : colorspace.colorspace == colorspace_e::rec601 ? "SDR (Rec. 601)" : colorspace.colorspace == colorspace_e::rec709 ? "SDR (Rec. 709)" : colorspace.colorspace == colorspace_e::bt2020sdr ? "SDR (Rec. 2020)" : "unknown"; BOOST_LOG(info) << "Color coding: " << color_coding; BOOST_LOG(info) << "Color depth: " << colorspace.bit_depth << "-bit"; BOOST_LOG(info) << "Color range: " << (colorspace.full_range ? "JPEG" : "MPEG"); } if (dynamic_cast<const encoder_platform_formats_avcodec *>(encoder.platform_formats.get())) { result = disp.make_avcodec_encode_device(pix_fmt); } else if (dynamic_cast<const encoder_platform_formats_nvenc *>(encoder.platform_formats.get())) { result = disp.make_nvenc_encode_device(pix_fmt); } if (result) { result->colorspace = colorspace; } return result; } std::optional<sync_session_t> make_synced_session(platf::display_t *disp, const encoder_t &encoder, platf::img_t &img, sync_session_ctx_t &ctx) { sync_session_t encode_session; encode_session.ctx = &ctx; auto encode_device = make_encode_device(*disp, encoder, ctx.config); if (!encode_device) { return std::nullopt; } // absolute mouse coordinates require that the dimensions of the screen are known ctx.touch_port_events->raise(make_port(disp, ctx.config)); // Update client with our current HDR display state hdr_info_t hdr_info = std::make_unique<hdr_info_raw_t>(false); if (colorspace_is_hdr(encode_device->colorspace)) { if (disp->get_hdr_metadata(hdr_info->metadata)) { hdr_info->enabled = true; } else { BOOST_LOG(error) << "Couldn't get display hdr metadata when colorspace selection indicates it should have one"; } } ctx.hdr_events->raise(std::move(hdr_info)); auto session = make_encode_session(disp, encoder, ctx.config, img.width, img.height, std::move(encode_device)); if (!session) { return std::nullopt; } // Load the initial image to prepare for encoding if (session->convert(img)) { BOOST_LOG(error) << "Could not convert initial image"sv; return std::nullopt; } encode_session.session = std::move(session); return encode_session; } encode_e encode_run_sync( std::vector<std::unique_ptr<sync_session_ctx_t>> &synced_session_ctxs, encode_session_ctx_queue_t &encode_session_ctx_queue, std::vector<std::string> &display_names, int &display_p) { const auto &encoder = *chosen_encoder; std::shared_ptr<platf::display_t> disp; auto switch_display_event = mail::man->event<int>(mail::switch_display); if (synced_session_ctxs.empty()) { auto ctx = encode_session_ctx_queue.pop(); if (!ctx) { return encode_e::ok; } synced_session_ctxs.emplace_back(std::make_unique<sync_session_ctx_t>(std::move(*ctx))); } while (encode_session_ctx_queue.running()) { // Refresh display names since a display removal might have caused the reinitialization refresh_displays(encoder.platform_formats->dev_type, display_names, display_p); // Process any pending display switch with the new list of displays if (switch_display_event->peek()) { display_p = std::clamp(*switch_display_event->pop(), 0, (int) display_names.size() - 1); } // reset_display() will sleep between retries reset_display(disp, encoder.platform_formats->dev_type, display_names[display_p], synced_session_ctxs.front()->config); if (disp) { break; } } if (!disp) { return encode_e::error; } auto img = disp->alloc_img(); if (!img || disp->dummy_img(img.get())) { return encode_e::error; } std::vector<sync_session_t> synced_sessions; for (auto &ctx : synced_session_ctxs) { auto synced_session = make_synced_session(disp.get(), encoder, *img, *ctx); if (!synced_session) { return encode_e::error; } synced_sessions.emplace_back(std::move(*synced_session)); } auto ec = platf::capture_e::ok; while (encode_session_ctx_queue.running()) { auto push_captured_image_callback = [&](std::shared_ptr<platf::img_t> &&img, bool frame_captured) -> bool { while (encode_session_ctx_queue.peek()) { auto encode_session_ctx = encode_session_ctx_queue.pop(); if (!encode_session_ctx) { return false; } synced_session_ctxs.emplace_back(std::make_unique<sync_session_ctx_t>(std::move(*encode_session_ctx))); auto encode_session = make_synced_session(disp.get(), encoder, *img, *synced_session_ctxs.back()); if (!encode_session) { ec = platf::capture_e::error; return false; } synced_sessions.emplace_back(std::move(*encode_session)); } KITTY_WHILE_LOOP(auto pos = std::begin(synced_sessions), pos != std::end(synced_sessions), { auto ctx = pos->ctx; if (ctx->shutdown_event->peek()) { // Let waiting thread know it can delete shutdown_event ctx->join_event->raise(true); pos = synced_sessions.erase(pos); synced_session_ctxs.erase(std::find_if(std::begin(synced_session_ctxs), std::end(synced_session_ctxs), [&ctx_p = ctx](auto &ctx) { return ctx.get() == ctx_p; })); if (synced_sessions.empty()) { return false; } continue; } if (ctx->idr_events->peek()) { pos->session->request_idr_frame(); ctx->idr_events->pop(); } if (frame_captured && pos->session->convert(*img)) { BOOST_LOG(error) << "Could not convert image"sv; ctx->shutdown_event->raise(true); continue; } std::optional<std::chrono::steady_clock::time_point> frame_timestamp; if (img) { frame_timestamp = img->frame_timestamp; } if (encode(ctx->frame_nr++, *pos->session, ctx->packets, ctx->channel_data, frame_timestamp)) { BOOST_LOG(error) << "Could not encode video packet"sv; ctx->shutdown_event->raise(true); continue; } pos->session->request_normal_frame(); ++pos; }) if (switch_display_event->peek()) { ec = platf::capture_e::reinit; return false; } return true; }; auto pull_free_image_callback = [&img](std::shared_ptr<platf::img_t> &img_out) -> bool { img_out = img; img_out->frame_timestamp.reset(); return true; }; auto status = disp->capture(push_captured_image_callback, pull_free_image_callback, &display_cursor); switch (status) { case platf::capture_e::reinit: case platf::capture_e::error: case platf::capture_e::ok: case platf::capture_e::timeout: case platf::capture_e::interrupted: return ec != platf::capture_e::ok ? ec : status; } } return encode_e::ok; } void captureThreadSync() { auto ref = capture_thread_sync.ref(); std::vector<std::unique_ptr<sync_session_ctx_t>> synced_session_ctxs; auto &ctx = ref->encode_session_ctx_queue; auto lg = util::fail_guard([&]() { ctx.stop(); for (auto &ctx : synced_session_ctxs) { ctx->shutdown_event->raise(true); ctx->join_event->raise(true); } for (auto &ctx : ctx.unsafe()) { ctx.shutdown_event->raise(true); ctx.join_event->raise(true); } }); // Encoding and capture takes place on this thread platf::adjust_thread_priority(platf::thread_priority_e::high); std::vector<std::string> display_names; int display_p = -1; while (encode_run_sync(synced_session_ctxs, ctx, display_names, display_p) == encode_e::reinit) {} } void capture_async( safe::mail_t mail, config_t &config, void *channel_data) { auto shutdown_event = mail->event<bool>(mail::shutdown); auto images = std::make_shared<img_event_t::element_type>(); auto lg = util::fail_guard([&]() { images->stop(); shutdown_event->raise(true); }); auto ref = capture_thread_async.ref(); if (!ref) { return; } ref->capture_ctx_queue->raise(capture_ctx_t { images, config }); if (!ref->capture_ctx_queue->running()) { return; } int frame_nr = 1; auto touch_port_event = mail->event<input::touch_port_t>(mail::touch_port); auto hdr_event = mail->event<hdr_info_t>(mail::hdr); // Encoding takes place on this thread platf::adjust_thread_priority(platf::thread_priority_e::high); while (!shutdown_event->peek() && images->running()) { // Wait for the main capture event when the display is being reinitialized if (ref->reinit_event.peek()) { std::this_thread::sleep_for(20ms); continue; } // Wait for the display to be ready std::shared_ptr<platf::display_t> display; { auto lg = ref->display_wp.lock(); if (ref->display_wp->expired()) { continue; } display = ref->display_wp->lock(); } auto &encoder = *chosen_encoder; auto encode_device = make_encode_device(*display, encoder, config); if (!encode_device) { return; } // absolute mouse coordinates require that the dimensions of the screen are known touch_port_event->raise(make_port(display.get(), config)); // Update client with our current HDR display state hdr_info_t hdr_info = std::make_unique<hdr_info_raw_t>(false); if (colorspace_is_hdr(encode_device->colorspace)) { if (display->get_hdr_metadata(hdr_info->metadata)) { hdr_info->enabled = true; } else { BOOST_LOG(error) << "Couldn't get display hdr metadata when colorspace selection indicates it should have one"; } } hdr_event->raise(std::move(hdr_info)); encode_run( frame_nr, mail, images, config, display, std::move(encode_device), ref->reinit_event, *ref->encoder_p, channel_data); } } void capture( safe::mail_t mail, config_t config, void *channel_data) { auto idr_events = mail->event<bool>(mail::idr); idr_events->raise(true); if (chosen_encoder->flags & PARALLEL_ENCODING) { capture_async(std::move(mail), config, channel_data); } else { safe::signal_t join_event; auto ref = capture_thread_sync.ref(); ref->encode_session_ctx_queue.raise(sync_session_ctx_t { &join_event, mail->event<bool>(mail::shutdown), mail::man->queue<packet_t>(mail::video_packets), std::move(idr_events), mail->event<hdr_info_t>(mail::hdr), mail->event<input::touch_port_t>(mail::touch_port), config, 1, channel_data, }); // Wait for join signal join_event.view(); } } enum validate_flag_e { VUI_PARAMS = 0x01, ///< VUI parameters }; int validate_config(std::shared_ptr<platf::display_t> disp, const encoder_t &encoder, const config_t &config) { auto encode_device = make_encode_device(*disp, encoder, config); if (!encode_device) { return -1; } auto session = make_encode_session(disp.get(), encoder, config, disp->width, disp->height, std::move(encode_device)); if (!session) { return -1; } { // Image buffers are large, so we use a separate scope to free it immediately after convert() auto img = disp->alloc_img(); if (!img || disp->dummy_img(img.get()) || session->convert(*img)) { return -1; } } session->request_idr_frame(); auto packets = mail::man->queue<packet_t>(mail::video_packets); while (!packets->peek()) { if (encode(1, *session, packets, nullptr, {})) { return -1; } } auto packet = packets->pop(); if (!packet->is_idr()) { BOOST_LOG(error) << "First packet type is not an IDR frame"sv; return -1; } int flag = 0; // This check only applies for H.264 and HEVC if (config.videoFormat <= 1) { if (auto packet_avcodec = dynamic_cast<packet_raw_avcodec *>(packet.get())) { if (cbs::validate_sps(packet_avcodec->av_packet, config.videoFormat ? AV_CODEC_ID_H265 : AV_CODEC_ID_H264)) { flag |= VUI_PARAMS; } } else { // Don't check it for non-avcodec encoders. flag |= VUI_PARAMS; } } return flag; } bool validate_encoder(encoder_t &encoder, bool expect_failure) { std::shared_ptr<platf::display_t> disp; BOOST_LOG(info) << "Trying encoder ["sv << encoder.name << ']'; auto fg = util::fail_guard([&]() { BOOST_LOG(info) << "Encoder ["sv << encoder.name << "] failed"sv; }); auto test_hevc = active_hevc_mode >= 2 || (active_hevc_mode == 0 && !(encoder.flags & H264_ONLY)); auto test_av1 = active_av1_mode >= 2 || (active_av1_mode == 0 && !(encoder.flags & H264_ONLY)); encoder.h264.capabilities.set(); encoder.hevc.capabilities.set(); encoder.av1.capabilities.set(); // First, test encoder viability config_t config_max_ref_frames { 1920, 1080, 60, 1000, 1, 1, 1, 0, 0, 0 }; config_t config_autoselect { 1920, 1080, 60, 1000, 1, 0, 1, 0, 0, 0 }; // If the encoder isn't supported at all (not even H.264), bail early reset_display(disp, encoder.platform_formats->dev_type, config::video.output_name, config_autoselect); if (!disp) { return false; } if (!disp->is_codec_supported(encoder.h264.name, config_autoselect)) { fg.disable(); BOOST_LOG(info) << "Encoder ["sv << encoder.name << "] is not supported on this GPU"sv; return false; } // If we're expecting failure, use the autoselect ref config first since that will always succeed // if the encoder is available. auto max_ref_frames_h264 = expect_failure ? -1 : validate_config(disp, encoder, config_max_ref_frames); auto autoselect_h264 = max_ref_frames_h264 >= 0 ? max_ref_frames_h264 : validate_config(disp, encoder, config_autoselect); if (autoselect_h264 < 0) { return false; } else if (expect_failure) { // We expected failure, but actually succeeded. Do the max_ref_frames probe we skipped. max_ref_frames_h264 = validate_config(disp, encoder, config_max_ref_frames); } std::vector<std::pair<validate_flag_e, encoder_t::flag_e>> packet_deficiencies { { VUI_PARAMS, encoder_t::VUI_PARAMETERS }, }; for (auto [validate_flag, encoder_flag] : packet_deficiencies) { encoder.h264[encoder_flag] = (max_ref_frames_h264 & validate_flag && autoselect_h264 & validate_flag); } encoder.h264[encoder_t::REF_FRAMES_RESTRICT] = max_ref_frames_h264 >= 0; encoder.h264[encoder_t::PASSED] = true; if (test_hevc) { config_max_ref_frames.videoFormat = 1; config_autoselect.videoFormat = 1; if (disp->is_codec_supported(encoder.hevc.name, config_autoselect)) { auto max_ref_frames_hevc = validate_config(disp, encoder, config_max_ref_frames); // If H.264 succeeded with max ref frames specified, assume that we can count on // HEVC to also succeed with max ref frames specified if HEVC is supported. auto autoselect_hevc = (max_ref_frames_hevc >= 0 || max_ref_frames_h264 >= 0) ? max_ref_frames_hevc : validate_config(disp, encoder, config_autoselect); for (auto [validate_flag, encoder_flag] : packet_deficiencies) { encoder.hevc[encoder_flag] = (max_ref_frames_hevc & validate_flag && autoselect_hevc & validate_flag); } encoder.hevc[encoder_t::REF_FRAMES_RESTRICT] = max_ref_frames_hevc >= 0; encoder.hevc[encoder_t::PASSED] = max_ref_frames_hevc >= 0 || autoselect_hevc >= 0; } else { BOOST_LOG(info) << "Encoder ["sv << encoder.hevc.name << "] is not supported on this GPU"sv; encoder.hevc.capabilities.reset(); } } else { // Clear all cap bits for HEVC if we didn't probe it encoder.hevc.capabilities.reset(); } if (test_av1) { config_max_ref_frames.videoFormat = 2; config_autoselect.videoFormat = 2; if (disp->is_codec_supported(encoder.av1.name, config_autoselect)) { auto max_ref_frames_av1 = validate_config(disp, encoder, config_max_ref_frames); // If H.264 succeeded with max ref frames specified, assume that we can count on // AV1 to also succeed with max ref frames specified if AV1 is supported. auto autoselect_av1 = (max_ref_frames_av1 >= 0 || max_ref_frames_h264 >= 0) ? max_ref_frames_av1 : validate_config(disp, encoder, config_autoselect); for (auto [validate_flag, encoder_flag] : packet_deficiencies) { encoder.av1[encoder_flag] = (max_ref_frames_av1 & validate_flag && autoselect_av1 & validate_flag); } encoder.av1[encoder_t::REF_FRAMES_RESTRICT] = max_ref_frames_av1 >= 0; encoder.av1[encoder_t::PASSED] = max_ref_frames_av1 >= 0 || autoselect_av1 >= 0; } else { BOOST_LOG(info) << "Encoder ["sv << encoder.av1.name << "] is not supported on this GPU"sv; encoder.av1.capabilities.reset(); } } else { // Clear all cap bits for AV1 if we didn't probe it encoder.av1.capabilities.reset(); } // Test HDR and YUV444 support { // H.264 is special because encoders may support YUV 4:4:4 without supporting 10-bit color depth if (encoder.flags & YUV444_SUPPORT) { config_t config_h264_yuv444 { 1920, 1080, 60, 1000, 1, 0, 1, 0, 0, 1 }; encoder.h264[encoder_t::YUV444] = disp->is_codec_supported(encoder.h264.name, config_h264_yuv444) && validate_config(disp, encoder, config_h264_yuv444) >= 0; } else { encoder.h264[encoder_t::YUV444] = false; } const config_t generic_hdr_config = { 1920, 1080, 60, 1000, 1, 0, 3, 1, 1, 0 }; // Reset the display since we're switching from SDR to HDR reset_display(disp, encoder.platform_formats->dev_type, config::video.output_name, generic_hdr_config); if (!disp) { return false; } auto test_hdr_and_yuv444 = [&](auto &flag_map, auto video_format) { auto config = generic_hdr_config; config.videoFormat = video_format; if (!flag_map[encoder_t::PASSED]) return; auto encoder_codec_name = encoder.codec_from_config(config).name; // Test 4:4:4 HDR first. If 4:4:4 is supported, 4:2:0 should also be supported. config.chromaSamplingType = 1; if ((encoder.flags & YUV444_SUPPORT) && disp->is_codec_supported(encoder_codec_name, config) && validate_config(disp, encoder, config) >= 0) { flag_map[encoder_t::DYNAMIC_RANGE] = true; flag_map[encoder_t::YUV444] = true; return; } else { flag_map[encoder_t::YUV444] = false; } // Test 4:2:0 HDR config.chromaSamplingType = 0; if (disp->is_codec_supported(encoder_codec_name, config) && validate_config(disp, encoder, config) >= 0) { flag_map[encoder_t::DYNAMIC_RANGE] = true; } else { flag_map[encoder_t::DYNAMIC_RANGE] = false; } }; // HDR is not supported with H.264. Don't bother even trying it. encoder.h264[encoder_t::DYNAMIC_RANGE] = false; test_hdr_and_yuv444(encoder.hevc, 1); test_hdr_and_yuv444(encoder.av1, 2); } encoder.h264[encoder_t::VUI_PARAMETERS] = encoder.h264[encoder_t::VUI_PARAMETERS] && !config::sunshine.flags[config::flag::FORCE_VIDEO_HEADER_REPLACE]; encoder.hevc[encoder_t::VUI_PARAMETERS] = encoder.hevc[encoder_t::VUI_PARAMETERS] && !config::sunshine.flags[config::flag::FORCE_VIDEO_HEADER_REPLACE]; if (!encoder.h264[encoder_t::VUI_PARAMETERS]) { BOOST_LOG(warning) << encoder.name << ": h264 missing sps->vui parameters"sv; } if (encoder.hevc[encoder_t::PASSED] && !encoder.hevc[encoder_t::VUI_PARAMETERS]) { BOOST_LOG(warning) << encoder.name << ": hevc missing sps->vui parameters"sv; } fg.disable(); return true; } int probe_encoders() { auto encoder_list = encoders; // If we already have a good encoder, check to see if another probe is required if (chosen_encoder && !(chosen_encoder->flags & ALWAYS_REPROBE) && !platf::needs_encoder_reenumeration()) { return 0; } // Restart encoder selection auto previous_encoder = chosen_encoder; chosen_encoder = nullptr; active_hevc_mode = config::video.hevc_mode; active_av1_mode = config::video.av1_mode; last_encoder_probe_supported_ref_frames_invalidation = false; auto adjust_encoder_constraints = [&](encoder_t *encoder) { // If we can't satisfy both the encoder and codec requirement, prefer the encoder over codec support if (active_hevc_mode == 3 && !encoder->hevc[encoder_t::DYNAMIC_RANGE]) { BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support HEVC Main10 on this system"sv; active_hevc_mode = 0; } else if (active_hevc_mode == 2 && !encoder->hevc[encoder_t::PASSED]) { BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support HEVC on this system"sv; active_hevc_mode = 0; } if (active_av1_mode == 3 && !encoder->av1[encoder_t::DYNAMIC_RANGE]) { BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support AV1 Main10 on this system"sv; active_av1_mode = 0; } else if (active_av1_mode == 2 && !encoder->av1[encoder_t::PASSED]) { BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support AV1 on this system"sv; active_av1_mode = 0; } }; if (!config::video.encoder.empty()) { // If there is a specific encoder specified, use it if it passes validation KITTY_WHILE_LOOP(auto pos = std::begin(encoder_list), pos != std::end(encoder_list), { auto encoder = *pos; if (encoder->name == config::video.encoder) { // Remove the encoder from the list entirely if it fails validation if (!validate_encoder(*encoder, previous_encoder && previous_encoder != encoder)) { pos = encoder_list.erase(pos); break; } // We will return an encoder here even if it fails one of the codec requirements specified by the user adjust_encoder_constraints(encoder); chosen_encoder = encoder; break; } pos++; }); if (chosen_encoder == nullptr) { BOOST_LOG(error) << "Couldn't find any working encoder matching ["sv << config::video.encoder << ']'; } } BOOST_LOG(info) << "// Testing for available encoders, this may generate errors. You can safely ignore those errors. //"sv; // If we haven't found an encoder yet, but we want one with specific codec support, search for that now. if (chosen_encoder == nullptr && (active_hevc_mode >= 2 || active_av1_mode >= 2)) { KITTY_WHILE_LOOP(auto pos = std::begin(encoder_list), pos != std::end(encoder_list), { auto encoder = *pos; // Remove the encoder from the list entirely if it fails validation if (!validate_encoder(*encoder, previous_encoder && previous_encoder != encoder)) { pos = encoder_list.erase(pos); continue; } // Skip it if it doesn't support the specified codec at all if ((active_hevc_mode >= 2 && !encoder->hevc[encoder_t::PASSED]) || (active_av1_mode >= 2 && !encoder->av1[encoder_t::PASSED])) { pos++; continue; } // Skip it if it doesn't support HDR on the specified codec if ((active_hevc_mode == 3 && !encoder->hevc[encoder_t::DYNAMIC_RANGE]) || (active_av1_mode == 3 && !encoder->av1[encoder_t::DYNAMIC_RANGE])) { pos++; continue; } chosen_encoder = encoder; break; }); if (chosen_encoder == nullptr) { BOOST_LOG(error) << "Couldn't find any working encoder that meets HEVC/AV1 requirements"sv; } } // If no encoder was specified or the specified encoder was unusable, keep trying // the remaining encoders until we find one that passes validation. if (chosen_encoder == nullptr) { KITTY_WHILE_LOOP(auto pos = std::begin(encoder_list), pos != std::end(encoder_list), { auto encoder = *pos; // If we've used a previous encoder and it's not this one, we expect this encoder to // fail to validate. It will use a slightly different order of checks to more quickly // eliminate failing encoders. if (!validate_encoder(*encoder, previous_encoder && previous_encoder != encoder)) { pos = encoder_list.erase(pos); continue; } // We will return an encoder here even if it fails one of the codec requirements specified by the user adjust_encoder_constraints(encoder); chosen_encoder = encoder; break; }); } if (chosen_encoder == nullptr) { BOOST_LOG(fatal) << "Unable to find display or encoder during startup."sv; if (!config::video.adapter_name.empty() || !config::video.output_name.empty()) { BOOST_LOG(fatal) << "Please ensure your manually chosen GPU and monitor are connected and powered on."sv; } else { BOOST_LOG(fatal) << "Please check that a display is connected and powered on."sv; } return -1; } BOOST_LOG(info); BOOST_LOG(info) << "// Ignore any errors mentioned above, they are not relevant. //"sv; BOOST_LOG(info); auto &encoder = *chosen_encoder; last_encoder_probe_supported_ref_frames_invalidation = (encoder.flags & REF_FRAMES_INVALIDATION); last_encoder_probe_supported_yuv444_for_codec[0] = encoder.h264[encoder_t::PASSED] && encoder.h264[encoder_t::YUV444]; last_encoder_probe_supported_yuv444_for_codec[1] = encoder.hevc[encoder_t::PASSED] && encoder.hevc[encoder_t::YUV444]; last_encoder_probe_supported_yuv444_for_codec[2] = encoder.av1[encoder_t::PASSED] && encoder.av1[encoder_t::YUV444]; BOOST_LOG(debug) << "------ h264 ------"sv; for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) { auto flag = (encoder_t::flag_e) x; BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.h264[flag] ? ": supported"sv : ": unsupported"sv); } BOOST_LOG(debug) << "-------------------"sv; BOOST_LOG(info) << "Found H.264 encoder: "sv << encoder.h264.name << " ["sv << encoder.name << ']'; if (encoder.hevc[encoder_t::PASSED]) { BOOST_LOG(debug) << "------ hevc ------"sv; for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) { auto flag = (encoder_t::flag_e) x; BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.hevc[flag] ? ": supported"sv : ": unsupported"sv); } BOOST_LOG(debug) << "-------------------"sv; BOOST_LOG(info) << "Found HEVC encoder: "sv << encoder.hevc.name << " ["sv << encoder.name << ']'; } if (encoder.av1[encoder_t::PASSED]) { BOOST_LOG(debug) << "------ av1 ------"sv; for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) { auto flag = (encoder_t::flag_e) x; BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.av1[flag] ? ": supported"sv : ": unsupported"sv); } BOOST_LOG(debug) << "-------------------"sv; BOOST_LOG(info) << "Found AV1 encoder: "sv << encoder.av1.name << " ["sv << encoder.name << ']'; } if (active_hevc_mode == 0) { active_hevc_mode = encoder.hevc[encoder_t::PASSED] ? (encoder.hevc[encoder_t::DYNAMIC_RANGE] ? 3 : 2) : 1; } if (active_av1_mode == 0) { active_av1_mode = encoder.av1[encoder_t::PASSED] ? (encoder.av1[encoder_t::DYNAMIC_RANGE] ? 3 : 2) : 1; } return 0; } // Linux only declaration typedef int (*vaapi_init_avcodec_hardware_input_buffer_fn)(platf::avcodec_encode_device_t *encode_device, AVBufferRef **hw_device_buf); util::Either<avcodec_buffer_t, int> vaapi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *encode_device) { avcodec_buffer_t hw_device_buf; // If an egl hwdevice if (encode_device->data) { if (((vaapi_init_avcodec_hardware_input_buffer_fn) encode_device->data)(encode_device, &hw_device_buf)) { return -1; } return hw_device_buf; } auto render_device = config::video.adapter_name.empty() ? nullptr : config::video.adapter_name.c_str(); auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VAAPI, render_device, nullptr, 0); if (status < 0) { char string[AV_ERROR_MAX_STRING_SIZE]; BOOST_LOG(error) << "Failed to create a VAAPI device: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); return -1; } return hw_device_buf; } util::Either<avcodec_buffer_t, int> cuda_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *encode_device) { avcodec_buffer_t hw_device_buf; auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_CUDA, nullptr, nullptr, 1 /* AV_CUDA_USE_PRIMARY_CONTEXT */); if (status < 0) { char string[AV_ERROR_MAX_STRING_SIZE]; BOOST_LOG(error) << "Failed to create a CUDA device: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); return -1; } return hw_device_buf; } util::Either<avcodec_buffer_t, int> vt_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *encode_device) { avcodec_buffer_t hw_device_buf; auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VIDEOTOOLBOX, nullptr, nullptr, 0); if (status < 0) { char string[AV_ERROR_MAX_STRING_SIZE]; BOOST_LOG(error) << "Failed to create a VideoToolbox device: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); return -1; } return hw_device_buf; } #ifdef _WIN32 } void do_nothing(void *) {} namespace video { util::Either<avcodec_buffer_t, int> dxgi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *encode_device) { avcodec_buffer_t ctx_buf { av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_D3D11VA) }; auto ctx = (AVD3D11VADeviceContext *) ((AVHWDeviceContext *) ctx_buf->data)->hwctx; std::fill_n((std::uint8_t *) ctx, sizeof(AVD3D11VADeviceContext), 0); auto device = (ID3D11Device *) encode_device->data; device->AddRef(); ctx->device = device; ctx->lock_ctx = (void *) 1; ctx->lock = do_nothing; ctx->unlock = do_nothing; auto err = av_hwdevice_ctx_init(ctx_buf.get()); if (err) { char err_str[AV_ERROR_MAX_STRING_SIZE] { 0 }; BOOST_LOG(error) << "Failed to create FFMpeg hardware device context: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); return err; } return ctx_buf; } #endif int start_capture_async(capture_thread_async_ctx_t &capture_thread_ctx) { capture_thread_ctx.encoder_p = chosen_encoder; capture_thread_ctx.reinit_event.reset(); capture_thread_ctx.capture_ctx_queue = std::make_shared<safe::queue_t<capture_ctx_t>>(30); capture_thread_ctx.capture_thread = std::thread { captureThread, capture_thread_ctx.capture_ctx_queue, std::ref(capture_thread_ctx.display_wp), std::ref(capture_thread_ctx.reinit_event), std::ref(*capture_thread_ctx.encoder_p) }; return 0; } void end_capture_async(capture_thread_async_ctx_t &capture_thread_ctx) { capture_thread_ctx.capture_ctx_queue->stop(); capture_thread_ctx.capture_thread.join(); } int start_capture_sync(capture_thread_sync_ctx_t &ctx) { std::thread { &captureThreadSync }.detach(); return 0; } void end_capture_sync(capture_thread_sync_ctx_t &ctx) {} platf::mem_type_e map_base_dev_type(AVHWDeviceType type) { switch (type) { case AV_HWDEVICE_TYPE_D3D11VA: return platf::mem_type_e::dxgi; case AV_HWDEVICE_TYPE_VAAPI: return platf::mem_type_e::vaapi; case AV_HWDEVICE_TYPE_CUDA: return platf::mem_type_e::cuda; case AV_HWDEVICE_TYPE_NONE: return platf::mem_type_e::system; case AV_HWDEVICE_TYPE_VIDEOTOOLBOX: return platf::mem_type_e::videotoolbox; default: return platf::mem_type_e::unknown; } return platf::mem_type_e::unknown; } platf::pix_fmt_e map_pix_fmt(AVPixelFormat fmt) { switch (fmt) { case AV_PIX_FMT_VUYX: return platf::pix_fmt_e::ayuv; case AV_PIX_FMT_XV30: return platf::pix_fmt_e::y410; case AV_PIX_FMT_YUV420P10: return platf::pix_fmt_e::yuv420p10; case AV_PIX_FMT_YUV420P: return platf::pix_fmt_e::yuv420p; case AV_PIX_FMT_NV12: return platf::pix_fmt_e::nv12; case AV_PIX_FMT_P010: return platf::pix_fmt_e::p010; default: return platf::pix_fmt_e::unknown; } return platf::pix_fmt_e::unknown; } } // namespace video
100,656
C++
.cpp
2,448
33.646242
207
0.608997
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,973
stat_trackers.cpp
LizardByte_Sunshine/src/stat_trackers.cpp
/** * @file src/stat_trackers.cpp * @brief Definitions for streaming statistic tracking. */ #include "stat_trackers.h" namespace stat_trackers { boost::format one_digit_after_decimal() { return boost::format("%1$.1f"); } boost::format two_digits_after_decimal() { return boost::format("%1$.2f"); } } // namespace stat_trackers
374
C++
.cpp
15
20.866667
56
0.660969
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,974
confighttp.cpp
LizardByte_Sunshine/src/confighttp.cpp
/** * @file src/confighttp.cpp * @brief Definitions for the Web UI Config HTTP server. * * @todo Authentication, better handling of routes common to nvhttp, cleanup */ #define BOOST_BIND_GLOBAL_PLACEHOLDERS #include "process.h" #include <filesystem> #include <set> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/algorithm/string.hpp> #include <boost/asio/ssl/context.hpp> #include <boost/filesystem.hpp> #include <Simple-Web-Server/crypto.hpp> #include <Simple-Web-Server/server_https.hpp> #include <boost/asio/ssl/context_base.hpp> #include "config.h" #include "confighttp.h" #include "crypto.h" #include "file_handler.h" #include "globals.h" #include "httpcommon.h" #include "logging.h" #include "network.h" #include "nvhttp.h" #include "platform/common.h" #include "rtsp.h" #include "utility.h" #include "uuid.h" #include "version.h" using namespace std::literals; namespace confighttp { namespace fs = std::filesystem; namespace pt = boost::property_tree; using https_server_t = SimpleWeb::Server<SimpleWeb::HTTPS>; using args_t = SimpleWeb::CaseInsensitiveMultimap; using resp_https_t = std::shared_ptr<typename SimpleWeb::ServerBase<SimpleWeb::HTTPS>::Response>; using req_https_t = std::shared_ptr<typename SimpleWeb::ServerBase<SimpleWeb::HTTPS>::Request>; enum class op_e { ADD, ///< Add client REMOVE ///< Remove client }; void print_req(const req_https_t &request) { BOOST_LOG(debug) << "METHOD :: "sv << request->method; BOOST_LOG(debug) << "DESTINATION :: "sv << request->path; for (auto &[name, val] : request->header) { BOOST_LOG(debug) << name << " -- " << (name == "Authorization" ? "CREDENTIALS REDACTED" : val); } BOOST_LOG(debug) << " [--] "sv; for (auto &[name, val] : request->parse_query_string()) { BOOST_LOG(debug) << name << " -- " << val; } BOOST_LOG(debug) << " [--] "sv; } void send_unauthorized(resp_https_t response, req_https_t request) { auto address = net::addr_to_normalized_string(request->remote_endpoint().address()); BOOST_LOG(info) << "Web UI: ["sv << address << "] -- not authorized"sv; const SimpleWeb::CaseInsensitiveMultimap headers { { "WWW-Authenticate", R"(Basic realm="Sunshine Gamestream Host", charset="UTF-8")" } }; response->write(SimpleWeb::StatusCode::client_error_unauthorized, headers); } void send_redirect(resp_https_t response, req_https_t request, const char *path) { auto address = net::addr_to_normalized_string(request->remote_endpoint().address()); BOOST_LOG(info) << "Web UI: ["sv << address << "] -- not authorized"sv; const SimpleWeb::CaseInsensitiveMultimap headers { { "Location", path } }; response->write(SimpleWeb::StatusCode::redirection_temporary_redirect, headers); } bool authenticate(resp_https_t response, req_https_t request) { auto address = net::addr_to_normalized_string(request->remote_endpoint().address()); auto ip_type = net::from_address(address); if (ip_type > http::origin_web_ui_allowed) { BOOST_LOG(info) << "Web UI: ["sv << address << "] -- denied"sv; response->write(SimpleWeb::StatusCode::client_error_forbidden); return false; } // If credentials are shown, redirect the user to a /welcome page if (config::sunshine.username.empty()) { send_redirect(response, request, "/welcome"); return false; } auto fg = util::fail_guard([&]() { send_unauthorized(response, request); }); auto auth = request->header.find("authorization"); if (auth == request->header.end()) { return false; } auto &rawAuth = auth->second; auto authData = SimpleWeb::Crypto::Base64::decode(rawAuth.substr("Basic "sv.length())); int index = authData.find(':'); if (index >= authData.size() - 1) { return false; } auto username = authData.substr(0, index); auto password = authData.substr(index + 1); auto hash = util::hex(crypto::hash(password + config::sunshine.salt)).to_string(); if (!boost::iequals(username, config::sunshine.username) || hash != config::sunshine.password) { return false; } fg.disable(); return true; } void not_found(resp_https_t response, req_https_t request) { pt::ptree tree; tree.put("root.<xmlattr>.status_code", 404); std::ostringstream data; pt::write_xml(data, tree); response->write(data.str()); *response << "HTTP/1.1 404 NOT FOUND\r\n" << data.str(); } /** * @todo combine these functions into a single function that accepts the page, i.e "index", "pin", "apps" */ void getIndexPage(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); std::string content = file_handler::read_file(WEB_DIR "index.html"); SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", "text/html; charset=utf-8"); response->write(content, headers); } void getPinPage(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); std::string content = file_handler::read_file(WEB_DIR "pin.html"); SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", "text/html; charset=utf-8"); response->write(content, headers); } void getAppsPage(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); std::string content = file_handler::read_file(WEB_DIR "apps.html"); SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", "text/html; charset=utf-8"); headers.emplace("Access-Control-Allow-Origin", "https://images.igdb.com/"); response->write(content, headers); } void getClientsPage(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); std::string content = file_handler::read_file(WEB_DIR "clients.html"); SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", "text/html; charset=utf-8"); response->write(content, headers); } void getConfigPage(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); std::string content = file_handler::read_file(WEB_DIR "config.html"); SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", "text/html; charset=utf-8"); response->write(content, headers); } void getPasswordPage(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); std::string content = file_handler::read_file(WEB_DIR "password.html"); SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", "text/html; charset=utf-8"); response->write(content, headers); } void getWelcomePage(resp_https_t response, req_https_t request) { print_req(request); if (!config::sunshine.username.empty()) { send_redirect(response, request, "/"); return; } std::string content = file_handler::read_file(WEB_DIR "welcome.html"); SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", "text/html; charset=utf-8"); response->write(content, headers); } void getTroubleshootingPage(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); std::string content = file_handler::read_file(WEB_DIR "troubleshooting.html"); SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", "text/html; charset=utf-8"); response->write(content, headers); } /** * @todo combine function with getSunshineLogoImage and possibly getNodeModules * @todo use mime_types map */ void getFaviconImage(resp_https_t response, req_https_t request) { print_req(request); std::ifstream in(WEB_DIR "images/sunshine.ico", std::ios::binary); SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", "image/x-icon"); response->write(SimpleWeb::StatusCode::success_ok, in, headers); } /** * @todo combine function with getFaviconImage and possibly getNodeModules * @todo use mime_types map */ void getSunshineLogoImage(resp_https_t response, req_https_t request) { print_req(request); std::ifstream in(WEB_DIR "images/logo-sunshine-45.png", std::ios::binary); SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", "image/png"); response->write(SimpleWeb::StatusCode::success_ok, in, headers); } bool isChildPath(fs::path const &base, fs::path const &query) { auto relPath = fs::relative(base, query); return *(relPath.begin()) != fs::path(".."); } void getNodeModules(resp_https_t response, req_https_t request) { print_req(request); fs::path webDirPath(WEB_DIR); fs::path nodeModulesPath(webDirPath / "assets"); // .relative_path is needed to shed any leading slash that might exist in the request path auto filePath = fs::weakly_canonical(webDirPath / fs::path(request->path).relative_path()); // Don't do anything if file does not exist or is outside the assets directory if (!isChildPath(filePath, nodeModulesPath)) { BOOST_LOG(warning) << "Someone requested a path " << filePath << " that is outside the assets folder"; response->write(SimpleWeb::StatusCode::client_error_bad_request, "Bad Request"); } else if (!fs::exists(filePath)) { response->write(SimpleWeb::StatusCode::client_error_not_found); } else { auto relPath = fs::relative(filePath, webDirPath); // get the mime type from the file extension mime_types map // remove the leading period from the extension auto mimeType = mime_types.find(relPath.extension().string().substr(1)); // check if the extension is in the map at the x position if (mimeType != mime_types.end()) { // if it is, set the content type to the mime type SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", mimeType->second); std::ifstream in(filePath.string(), std::ios::binary); response->write(SimpleWeb::StatusCode::success_ok, in, headers); } // do not return any file if the type is not in the map } } /** * @brief Get the list of available applications. * @param response The HTTP response object. * @param request The HTTP request object. */ void getApps(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); std::string content = file_handler::read_file(config::stream.file_apps.c_str()); SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", "application/json"); response->write(content, headers); } /** * @brief Get the logs from the log file. * @param response The HTTP response object. * @param request The HTTP request object. */ void getLogs(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); std::string content = file_handler::read_file(config::sunshine.log_file.c_str()); SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", "text/plain"); response->write(SimpleWeb::StatusCode::success_ok, content, headers); } /** * @brief Save an application. If the application already exists, it will be updated, otherwise it will be added. * @param response The HTTP response object. * @param request The HTTP request object. * The body for the post request should be JSON serialized in the following format: * @code{.json} * { * "name": "Application Name", * "output": "Log Output Path", * "cmd": "Command to run the application", * "index": -1, * "exclude-global-prep-cmd": false, * "elevated": false, * "auto-detach": true, * "wait-all": true, * "exit-timeout": 5, * "prep-cmd": [ * { * "do": "Command to prepare", * "undo": "Command to undo preparation", * "elevated": false * } * ], * "detached": [ * "Detached command" * ], * "image-path": "Full path to the application image. Must be a png file.", * } * @endcode */ void saveApp(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); std::stringstream ss; ss << request->content.rdbuf(); pt::ptree outputTree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_json(data, outputTree); response->write(data.str()); }); pt::ptree inputTree, fileTree; BOOST_LOG(info) << config::stream.file_apps; try { // TODO: Input Validation pt::read_json(ss, inputTree); pt::read_json(config::stream.file_apps, fileTree); if (inputTree.get_child("prep-cmd").empty()) { inputTree.erase("prep-cmd"); } if (inputTree.get_child("detached").empty()) { inputTree.erase("detached"); } auto &apps_node = fileTree.get_child("apps"s); int index = inputTree.get<int>("index"); inputTree.erase("index"); if (index == -1) { apps_node.push_back(std::make_pair("", inputTree)); } else { // Unfortunately Boost PT does not allow to directly edit the array, copy should do the trick pt::ptree newApps; int i = 0; for (const auto &[k, v] : apps_node) { if (i == index) { newApps.push_back(std::make_pair("", inputTree)); } else { newApps.push_back(std::make_pair("", v)); } i++; } fileTree.erase("apps"); fileTree.push_back(std::make_pair("apps", newApps)); } // Sort the apps array by name std::vector<pt::ptree> apps_vector; for (const auto &[k, v] : fileTree.get_child("apps")) { apps_vector.push_back(v); } std::ranges::sort(apps_vector, [](const pt::ptree &a, const pt::ptree &b) { return a.get<std::string>("name") < b.get<std::string>("name"); }); pt::ptree sorted_apps; for (const auto &app : apps_vector) { sorted_apps.push_back(std::make_pair("", app)); } fileTree.erase("apps"); fileTree.add_child("apps", sorted_apps); pt::write_json(config::stream.file_apps, fileTree); } catch (std::exception &e) { BOOST_LOG(warning) << "SaveApp: "sv << e.what(); outputTree.put("status", "false"); outputTree.put("error", "Invalid Input JSON"); return; } outputTree.put("status", "true"); proc::refresh(config::stream.file_apps); } /** * @brief Delete an application. * @param response The HTTP response object. * @param request The HTTP request object. */ void deleteApp(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); pt::ptree outputTree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_json(data, outputTree); response->write(data.str()); }); pt::ptree fileTree; try { pt::read_json(config::stream.file_apps, fileTree); auto &apps_node = fileTree.get_child("apps"s); int index = stoi(request->path_match[1]); if (index < 0) { outputTree.put("status", "false"); outputTree.put("error", "Invalid Index"); return; } else { // Unfortunately Boost PT does not allow to directly edit the array, copy should do the trick pt::ptree newApps; int i = 0; for (const auto &[k, v] : apps_node) { if (i++ != index) { newApps.push_back(std::make_pair("", v)); } } fileTree.erase("apps"); fileTree.push_back(std::make_pair("apps", newApps)); } pt::write_json(config::stream.file_apps, fileTree); } catch (std::exception &e) { BOOST_LOG(warning) << "DeleteApp: "sv << e.what(); outputTree.put("status", "false"); outputTree.put("error", "Invalid File JSON"); return; } outputTree.put("status", "true"); proc::refresh(config::stream.file_apps); } /** * @brief Upload a cover image. * @param response The HTTP response object. * @param request The HTTP request object. * The body for the post request should be JSON serialized in the following format: * @code{.json} * { * "key": "igdb_<game_id>", * "url": "https://images.igdb.com/igdb/image/upload/t_cover_big_2x/<slug>.png", * } * @endcode */ void uploadCover(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; std::stringstream ss; std::stringstream configStream; ss << request->content.rdbuf(); pt::ptree outputTree; auto g = util::fail_guard([&]() { std::ostringstream data; SimpleWeb::StatusCode code = SimpleWeb::StatusCode::success_ok; if (outputTree.get_child_optional("error").has_value()) { code = SimpleWeb::StatusCode::client_error_bad_request; } pt::write_json(data, outputTree); response->write(code, data.str()); }); pt::ptree inputTree; try { pt::read_json(ss, inputTree); } catch (std::exception &e) { BOOST_LOG(warning) << "UploadCover: "sv << e.what(); outputTree.put("status", "false"); outputTree.put("error", e.what()); return; } auto key = inputTree.get("key", ""); if (key.empty()) { outputTree.put("error", "Cover key is required"); return; } auto url = inputTree.get("url", ""); const std::string coverdir = platf::appdata().string() + "/covers/"; file_handler::make_directory(coverdir); std::basic_string path = coverdir + http::url_escape(key) + ".png"; if (!url.empty()) { if (http::url_get_host(url) != "images.igdb.com") { outputTree.put("error", "Only images.igdb.com is allowed"); return; } if (!http::download_file(url, path)) { outputTree.put("error", "Failed to download cover"); return; } } else { auto data = SimpleWeb::Crypto::Base64::decode(inputTree.get<std::string>("data")); std::ofstream imgfile(path); imgfile.write(data.data(), (int) data.size()); } outputTree.put("path", path); } /** * @brief Get the configuration settings. * @param response The HTTP response object. * @param request The HTTP request object. */ void getConfig(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); pt::ptree outputTree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_json(data, outputTree); response->write(data.str()); }); outputTree.put("status", "true"); outputTree.put("platform", SUNSHINE_PLATFORM); outputTree.put("version", PROJECT_VER); auto vars = config::parse_config(file_handler::read_file(config::sunshine.config_file.c_str())); for (auto &[name, value] : vars) { outputTree.put(std::move(name), std::move(value)); } } /** * @brief Get the locale setting. This endpoint does not require authentication. * @param response The HTTP response object. * @param request The HTTP request object. */ void getLocale(resp_https_t response, req_https_t request) { // we need to return the locale whether authenticated or not print_req(request); pt::ptree outputTree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_json(data, outputTree); response->write(data.str()); }); outputTree.put("status", "true"); outputTree.put("locale", config::sunshine.locale); } /** * @brief Save the configuration settings. * @param response The HTTP response object. * @param request The HTTP request object. * The body for the post request should be JSON serialized in the following format: * @code{.json} * { * "key": "value" * } * @endcode * * @attention{It is recommended to ONLY save the config settings that differ from the default behavior.} */ void saveConfig(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); std::stringstream ss; std::stringstream configStream; ss << request->content.rdbuf(); pt::ptree outputTree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_json(data, outputTree); response->write(data.str()); }); pt::ptree inputTree; try { // TODO: Input Validation pt::read_json(ss, inputTree); for (const auto &[k, v] : inputTree) { std::string value = inputTree.get<std::string>(k); if (value.length() == 0 || value.compare("null") == 0) continue; configStream << k << " = " << value << std::endl; } file_handler::write_file(config::sunshine.config_file.c_str(), configStream.str()); } catch (std::exception &e) { BOOST_LOG(warning) << "SaveConfig: "sv << e.what(); outputTree.put("status", "false"); outputTree.put("error", e.what()); return; } } /** * @brief Restart Sunshine. * @param response The HTTP response object. * @param request The HTTP request object. */ void restart(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); // We may not return from this call platf::restart(); } /** * @brief Update existing credentials. * @param response The HTTP response object. * @param request The HTTP request object. * The body for the post request should be JSON serialized in the following format: * @code{.json} * { * "currentUsername": "Current Username", * "currentPassword": "Current Password", * "newUsername": "New Username", * "newPassword": "New Password", * "confirmNewPassword": "Confirm New Password" * } * @endcode */ void savePassword(resp_https_t response, req_https_t request) { if (!config::sunshine.username.empty() && !authenticate(response, request)) return; print_req(request); std::stringstream ss; std::stringstream configStream; ss << request->content.rdbuf(); pt::ptree inputTree, outputTree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_json(data, outputTree); response->write(data.str()); }); try { // TODO: Input Validation pt::read_json(ss, inputTree); auto username = inputTree.count("currentUsername") > 0 ? inputTree.get<std::string>("currentUsername") : ""; auto newUsername = inputTree.get<std::string>("newUsername"); auto password = inputTree.count("currentPassword") > 0 ? inputTree.get<std::string>("currentPassword") : ""; auto newPassword = inputTree.count("newPassword") > 0 ? inputTree.get<std::string>("newPassword") : ""; auto confirmPassword = inputTree.count("confirmNewPassword") > 0 ? inputTree.get<std::string>("confirmNewPassword") : ""; if (newUsername.length() == 0) newUsername = username; if (newUsername.length() == 0) { outputTree.put("status", false); outputTree.put("error", "Invalid Username"); } else { auto hash = util::hex(crypto::hash(password + config::sunshine.salt)).to_string(); if (config::sunshine.username.empty() || (boost::iequals(username, config::sunshine.username) && hash == config::sunshine.password)) { if (newPassword.empty() || newPassword != confirmPassword) { outputTree.put("status", false); outputTree.put("error", "Password Mismatch"); } else { http::save_user_creds(config::sunshine.credentials_file, newUsername, newPassword); http::reload_user_creds(config::sunshine.credentials_file); outputTree.put("status", true); } } else { outputTree.put("status", false); outputTree.put("error", "Invalid Current Credentials"); } } } catch (std::exception &e) { BOOST_LOG(warning) << "SavePassword: "sv << e.what(); outputTree.put("status", false); outputTree.put("error", e.what()); return; } } /** * @brief Send a pin code to the host. The pin is generated from the Moonlight client during the pairing process. * @param response The HTTP response object. * @param request The HTTP request object. * The body for the post request should be JSON serialized in the following format: * @code{.json} * { * "pin": "<pin>", * "name": "Friendly Client Name" * } * @endcode */ void savePin(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); std::stringstream ss; ss << request->content.rdbuf(); pt::ptree inputTree, outputTree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_json(data, outputTree); response->write(data.str()); }); try { // TODO: Input Validation pt::read_json(ss, inputTree); std::string pin = inputTree.get<std::string>("pin"); std::string name = inputTree.get<std::string>("name"); outputTree.put("status", nvhttp::pin(pin, name)); } catch (std::exception &e) { BOOST_LOG(warning) << "SavePin: "sv << e.what(); outputTree.put("status", false); outputTree.put("error", e.what()); return; } } /** * @brief Unpair all clients. * @param response The HTTP response object. * @param request The HTTP request object. */ void unpairAll(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); pt::ptree outputTree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_json(data, outputTree); response->write(data.str()); }); nvhttp::erase_all_clients(); proc::proc.terminate(); outputTree.put("status", true); } /** * @brief Unpair a client. * @param response The HTTP response object. * @param request The HTTP request object. * The body for the post request should be JSON serialized in the following format: * @code{.json} * { * "uuid": "<uuid>" * } * @endcode */ void unpair(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); std::stringstream ss; ss << request->content.rdbuf(); pt::ptree inputTree, outputTree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_json(data, outputTree); response->write(data.str()); }); try { // TODO: Input Validation pt::read_json(ss, inputTree); std::string uuid = inputTree.get<std::string>("uuid"); outputTree.put("status", nvhttp::unpair_client(uuid)); } catch (std::exception &e) { BOOST_LOG(warning) << "Unpair: "sv << e.what(); outputTree.put("status", false); outputTree.put("error", e.what()); return; } } /** * @brief Get the list of paired clients. * @param response The HTTP response object. * @param request The HTTP request object. */ void listClients(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); pt::ptree named_certs = nvhttp::get_all_clients(); pt::ptree outputTree; outputTree.put("status", false); auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_json(data, outputTree); response->write(data.str()); }); outputTree.add_child("named_certs", named_certs); outputTree.put("status", true); } /** * @brief Close the currently running application. * @param response The HTTP response object. * @param request The HTTP request object. */ void closeApp(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; print_req(request); pt::ptree outputTree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_json(data, outputTree); response->write(data.str()); }); proc::proc.terminate(); outputTree.put("status", true); } void start() { auto shutdown_event = mail::man->event<bool>(mail::shutdown); auto port_https = net::map_port(PORT_HTTPS); auto address_family = net::af_from_enum_string(config::sunshine.address_family); https_server_t server { config::nvhttp.cert, config::nvhttp.pkey }; server.default_resource["GET"] = not_found; server.resource["^/$"]["GET"] = getIndexPage; server.resource["^/pin/?$"]["GET"] = getPinPage; server.resource["^/apps/?$"]["GET"] = getAppsPage; server.resource["^/clients/?$"]["GET"] = getClientsPage; server.resource["^/config/?$"]["GET"] = getConfigPage; server.resource["^/password/?$"]["GET"] = getPasswordPage; server.resource["^/welcome/?$"]["GET"] = getWelcomePage; server.resource["^/troubleshooting/?$"]["GET"] = getTroubleshootingPage; server.resource["^/api/pin$"]["POST"] = savePin; server.resource["^/api/apps$"]["GET"] = getApps; server.resource["^/api/logs$"]["GET"] = getLogs; server.resource["^/api/apps$"]["POST"] = saveApp; server.resource["^/api/config$"]["GET"] = getConfig; server.resource["^/api/config$"]["POST"] = saveConfig; server.resource["^/api/configLocale$"]["GET"] = getLocale; server.resource["^/api/restart$"]["POST"] = restart; server.resource["^/api/password$"]["POST"] = savePassword; server.resource["^/api/apps/([0-9]+)$"]["DELETE"] = deleteApp; server.resource["^/api/clients/unpair-all$"]["POST"] = unpairAll; server.resource["^/api/clients/list$"]["GET"] = listClients; server.resource["^/api/clients/unpair$"]["POST"] = unpair; server.resource["^/api/apps/close$"]["POST"] = closeApp; server.resource["^/api/covers/upload$"]["POST"] = uploadCover; server.resource["^/images/sunshine.ico$"]["GET"] = getFaviconImage; server.resource["^/images/logo-sunshine-45.png$"]["GET"] = getSunshineLogoImage; server.resource["^/assets\\/.+$"]["GET"] = getNodeModules; server.config.reuse_address = true; server.config.address = net::af_to_any_address_string(address_family); server.config.port = port_https; auto accept_and_run = [&](auto *server) { try { server->start([](unsigned short port) { BOOST_LOG(info) << "Configuration UI available at [https://localhost:"sv << port << "]"; }); } catch (boost::system::system_error &err) { // It's possible the exception gets thrown after calling server->stop() from a different thread if (shutdown_event->peek()) { return; } BOOST_LOG(fatal) << "Couldn't start Configuration HTTPS server on port ["sv << port_https << "]: "sv << err.what(); shutdown_event->raise(true); return; } }; std::thread tcp { accept_and_run, &server }; // Wait for any event shutdown_event->view(); server.stop(); tcp.join(); } } // namespace confighttp
31,907
C++
.cpp
856
31.869159
142
0.64572
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,975
input.cpp
LizardByte_Sunshine/src/input.cpp
/** * @file src/input.cpp * @brief Definitions for gamepad, keyboard, and mouse input handling. */ // define uint32_t for <moonlight-common-c/src/Input.h> #include <cstdint> extern "C" { #include <moonlight-common-c/src/Input.h> #include <moonlight-common-c/src/Limelight.h> } #include <bitset> #include <chrono> #include <cmath> #include <list> #include <thread> #include <unordered_map> #include "config.h" #include "globals.h" #include "input.h" #include "logging.h" #include "platform/common.h" #include "thread_pool.h" #include "utility.h" #include <boost/endian/buffers.hpp> // Win32 WHEEL_DELTA constant #ifndef WHEEL_DELTA #define WHEEL_DELTA 120 #endif using namespace std::literals; namespace input { constexpr auto MAX_GAMEPADS = std::min((std::size_t) platf::MAX_GAMEPADS, sizeof(std::int16_t) * 8); #define DISABLE_LEFT_BUTTON_DELAY ((thread_pool_util::ThreadPool::task_id_t) 0x01) #define ENABLE_LEFT_BUTTON_DELAY nullptr constexpr auto VKEY_SHIFT = 0x10; constexpr auto VKEY_LSHIFT = 0xA0; constexpr auto VKEY_RSHIFT = 0xA1; constexpr auto VKEY_CONTROL = 0x11; constexpr auto VKEY_LCONTROL = 0xA2; constexpr auto VKEY_RCONTROL = 0xA3; constexpr auto VKEY_MENU = 0x12; constexpr auto VKEY_LMENU = 0xA4; constexpr auto VKEY_RMENU = 0xA5; enum class button_state_e { NONE, ///< No button state DOWN, ///< Button is down UP ///< Button is up }; template <std::size_t N> int alloc_id(std::bitset<N> &gamepad_mask) { for (int x = 0; x < gamepad_mask.size(); ++x) { if (!gamepad_mask[x]) { gamepad_mask[x] = true; return x; } } return -1; } template <std::size_t N> void free_id(std::bitset<N> &gamepad_mask, int id) { gamepad_mask[id] = false; } typedef uint32_t key_press_id_t; key_press_id_t make_kpid(uint16_t vk, uint8_t flags) { return (key_press_id_t) vk << 8 | flags; } uint16_t vk_from_kpid(key_press_id_t kpid) { return kpid >> 8; } uint8_t flags_from_kpid(key_press_id_t kpid) { return kpid & 0xFF; } /** * @brief Convert a little-endian netfloat to a native endianness float. * @param f Netfloat value. * @return The native endianness float value. */ float from_netfloat(netfloat f) { return boost::endian::endian_load<float, sizeof(float), boost::endian::order::little>(f); } /** * @brief Convert a little-endian netfloat to a native endianness float and clamps it. * @param f Netfloat value. * @param min The minimium value for clamping. * @param max The maximum value for clamping. * @return Clamped native endianess float value. */ float from_clamped_netfloat(netfloat f, float min, float max) { return std::clamp(from_netfloat(f), min, max); } static task_pool_util::TaskPool::task_id_t key_press_repeat_id {}; static std::unordered_map<key_press_id_t, bool> key_press {}; static std::array<std::uint8_t, 5> mouse_press {}; static platf::input_t platf_input; static std::bitset<platf::MAX_GAMEPADS> gamepadMask {}; void free_gamepad(platf::input_t &platf_input, int id) { platf::gamepad_update(platf_input, id, platf::gamepad_state_t {}); platf::free_gamepad(platf_input, id); free_id(gamepadMask, id); } struct gamepad_t { gamepad_t(): gamepad_state {}, back_timeout_id {}, id { -1 }, back_button_state { button_state_e::NONE } {} ~gamepad_t() { if (id >= 0) { task_pool.push([id = this->id]() { free_gamepad(platf_input, id); }); } } platf::gamepad_state_t gamepad_state; thread_pool_util::ThreadPool::task_id_t back_timeout_id; int id; // When emulating the HOME button, we may need to artificially release the back button. // Afterwards, the gamepad state on sunshine won't match the state on Moonlight. // To prevent Sunshine from sending erroneous input data to the active application, // Sunshine forces the button to be in a specific state until the gamepad state matches that of // Moonlight once more. button_state_e back_button_state; }; struct input_t { enum shortkey_e { CTRL = 0x1, ///< Control key ALT = 0x2, ///< Alt key SHIFT = 0x4, ///< Shift key SHORTCUT = CTRL | ALT | SHIFT ///< Shortcut combination }; input_t( safe::mail_raw_t::event_t<input::touch_port_t> touch_port_event, platf::feedback_queue_t feedback_queue): shortcutFlags {}, gamepads(MAX_GAMEPADS), client_context { platf::allocate_client_input_context(platf_input) }, touch_port_event { std::move(touch_port_event) }, feedback_queue { std::move(feedback_queue) }, mouse_left_button_timeout {}, touch_port { { 0, 0, 0, 0 }, 0, 0, 1.0f }, accumulated_vscroll_delta {}, accumulated_hscroll_delta {} {} // Keep track of alt+ctrl+shift key combo int shortcutFlags; std::vector<gamepad_t> gamepads; std::unique_ptr<platf::client_input_t> client_context; safe::mail_raw_t::event_t<input::touch_port_t> touch_port_event; platf::feedback_queue_t feedback_queue; std::list<std::vector<uint8_t>> input_queue; std::mutex input_queue_lock; thread_pool_util::ThreadPool::task_id_t mouse_left_button_timeout; input::touch_port_t touch_port; int32_t accumulated_vscroll_delta; int32_t accumulated_hscroll_delta; }; /** * @brief Apply shortcut based on VKEY * @param keyCode The VKEY code * @return 0 if no shortcut applied, > 0 if shortcut applied. */ inline int apply_shortcut(short keyCode) { constexpr auto VK_F1 = 0x70; constexpr auto VK_F13 = 0x7C; BOOST_LOG(debug) << "Apply Shortcut: 0x"sv << util::hex((std::uint8_t) keyCode).to_string_view(); if (keyCode >= VK_F1 && keyCode <= VK_F13) { mail::man->event<int>(mail::switch_display)->raise(keyCode - VK_F1); return 1; } switch (keyCode) { case 0x4E /* VKEY_N */: display_cursor = !display_cursor; return 1; } return 0; } void print(PNV_REL_MOUSE_MOVE_PACKET packet) { BOOST_LOG(debug) << "--begin relative mouse move packet--"sv << std::endl << "deltaX ["sv << util::endian::big(packet->deltaX) << ']' << std::endl << "deltaY ["sv << util::endian::big(packet->deltaY) << ']' << std::endl << "--end relative mouse move packet--"sv; } void print(PNV_ABS_MOUSE_MOVE_PACKET packet) { BOOST_LOG(debug) << "--begin absolute mouse move packet--"sv << std::endl << "x ["sv << util::endian::big(packet->x) << ']' << std::endl << "y ["sv << util::endian::big(packet->y) << ']' << std::endl << "width ["sv << util::endian::big(packet->width) << ']' << std::endl << "height ["sv << util::endian::big(packet->height) << ']' << std::endl << "--end absolute mouse move packet--"sv; } void print(PNV_MOUSE_BUTTON_PACKET packet) { BOOST_LOG(debug) << "--begin mouse button packet--"sv << std::endl << "action ["sv << util::hex(packet->header.magic).to_string_view() << ']' << std::endl << "button ["sv << util::hex(packet->button).to_string_view() << ']' << std::endl << "--end mouse button packet--"sv; } void print(PNV_SCROLL_PACKET packet) { BOOST_LOG(debug) << "--begin mouse scroll packet--"sv << std::endl << "scrollAmt1 ["sv << util::endian::big(packet->scrollAmt1) << ']' << std::endl << "--end mouse scroll packet--"sv; } void print(PSS_HSCROLL_PACKET packet) { BOOST_LOG(debug) << "--begin mouse hscroll packet--"sv << std::endl << "scrollAmount ["sv << util::endian::big(packet->scrollAmount) << ']' << std::endl << "--end mouse hscroll packet--"sv; } void print(PNV_KEYBOARD_PACKET packet) { BOOST_LOG(debug) << "--begin keyboard packet--"sv << std::endl << "keyAction ["sv << util::hex(packet->header.magic).to_string_view() << ']' << std::endl << "keyCode ["sv << util::hex(packet->keyCode).to_string_view() << ']' << std::endl << "modifiers ["sv << util::hex(packet->modifiers).to_string_view() << ']' << std::endl << "flags ["sv << util::hex(packet->flags).to_string_view() << ']' << std::endl << "--end keyboard packet--"sv; } void print(PNV_UNICODE_PACKET packet) { std::string text(packet->text, util::endian::big(packet->header.size) - sizeof(packet->header.magic)); BOOST_LOG(debug) << "--begin unicode packet--"sv << std::endl << "text ["sv << text << ']' << std::endl << "--end unicode packet--"sv; } void print(PNV_MULTI_CONTROLLER_PACKET packet) { // Moonlight spams controller packet even when not necessary BOOST_LOG(verbose) << "--begin controller packet--"sv << std::endl << "controllerNumber ["sv << packet->controllerNumber << ']' << std::endl << "activeGamepadMask ["sv << util::hex(packet->activeGamepadMask).to_string_view() << ']' << std::endl << "buttonFlags ["sv << util::hex((uint32_t) packet->buttonFlags | (packet->buttonFlags2 << 16)).to_string_view() << ']' << std::endl << "leftTrigger ["sv << util::hex(packet->leftTrigger).to_string_view() << ']' << std::endl << "rightTrigger ["sv << util::hex(packet->rightTrigger).to_string_view() << ']' << std::endl << "leftStickX ["sv << packet->leftStickX << ']' << std::endl << "leftStickY ["sv << packet->leftStickY << ']' << std::endl << "rightStickX ["sv << packet->rightStickX << ']' << std::endl << "rightStickY ["sv << packet->rightStickY << ']' << std::endl << "--end controller packet--"sv; } /** * @brief Prints a touch packet. * @param packet The touch packet. */ void print(PSS_TOUCH_PACKET packet) { BOOST_LOG(debug) << "--begin touch packet--"sv << std::endl << "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl << "pointerId ["sv << util::hex(packet->pointerId).to_string_view() << ']' << std::endl << "x ["sv << from_netfloat(packet->x) << ']' << std::endl << "y ["sv << from_netfloat(packet->y) << ']' << std::endl << "pressureOrDistance ["sv << from_netfloat(packet->pressureOrDistance) << ']' << std::endl << "contactAreaMajor ["sv << from_netfloat(packet->contactAreaMajor) << ']' << std::endl << "contactAreaMinor ["sv << from_netfloat(packet->contactAreaMinor) << ']' << std::endl << "rotation ["sv << (uint32_t) packet->rotation << ']' << std::endl << "--end touch packet--"sv; } /** * @brief Prints a pen packet. * @param packet The pen packet. */ void print(PSS_PEN_PACKET packet) { BOOST_LOG(debug) << "--begin pen packet--"sv << std::endl << "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl << "toolType ["sv << util::hex(packet->toolType).to_string_view() << ']' << std::endl << "penButtons ["sv << util::hex(packet->penButtons).to_string_view() << ']' << std::endl << "x ["sv << from_netfloat(packet->x) << ']' << std::endl << "y ["sv << from_netfloat(packet->y) << ']' << std::endl << "pressureOrDistance ["sv << from_netfloat(packet->pressureOrDistance) << ']' << std::endl << "contactAreaMajor ["sv << from_netfloat(packet->contactAreaMajor) << ']' << std::endl << "contactAreaMinor ["sv << from_netfloat(packet->contactAreaMinor) << ']' << std::endl << "rotation ["sv << (uint32_t) packet->rotation << ']' << std::endl << "tilt ["sv << (uint32_t) packet->tilt << ']' << std::endl << "--end pen packet--"sv; } /** * @brief Prints a controller arrival packet. * @param packet The controller arrival packet. */ void print(PSS_CONTROLLER_ARRIVAL_PACKET packet) { BOOST_LOG(debug) << "--begin controller arrival packet--"sv << std::endl << "controllerNumber ["sv << (uint32_t) packet->controllerNumber << ']' << std::endl << "type ["sv << util::hex(packet->type).to_string_view() << ']' << std::endl << "capabilities ["sv << util::hex(packet->capabilities).to_string_view() << ']' << std::endl << "supportedButtonFlags ["sv << util::hex(packet->supportedButtonFlags).to_string_view() << ']' << std::endl << "--end controller arrival packet--"sv; } /** * @brief Prints a controller touch packet. * @param packet The controller touch packet. */ void print(PSS_CONTROLLER_TOUCH_PACKET packet) { BOOST_LOG(debug) << "--begin controller touch packet--"sv << std::endl << "controllerNumber ["sv << (uint32_t) packet->controllerNumber << ']' << std::endl << "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl << "pointerId ["sv << util::hex(packet->pointerId).to_string_view() << ']' << std::endl << "x ["sv << from_netfloat(packet->x) << ']' << std::endl << "y ["sv << from_netfloat(packet->y) << ']' << std::endl << "pressure ["sv << from_netfloat(packet->pressure) << ']' << std::endl << "--end controller touch packet--"sv; } /** * @brief Prints a controller motion packet. * @param packet The controller motion packet. */ void print(PSS_CONTROLLER_MOTION_PACKET packet) { BOOST_LOG(verbose) << "--begin controller motion packet--"sv << std::endl << "controllerNumber ["sv << util::hex(packet->controllerNumber).to_string_view() << ']' << std::endl << "motionType ["sv << util::hex(packet->motionType).to_string_view() << ']' << std::endl << "x ["sv << from_netfloat(packet->x) << ']' << std::endl << "y ["sv << from_netfloat(packet->y) << ']' << std::endl << "z ["sv << from_netfloat(packet->z) << ']' << std::endl << "--end controller motion packet--"sv; } /** * @brief Prints a controller battery packet. * @param packet The controller battery packet. */ void print(PSS_CONTROLLER_BATTERY_PACKET packet) { BOOST_LOG(verbose) << "--begin controller battery packet--"sv << std::endl << "controllerNumber ["sv << util::hex(packet->controllerNumber).to_string_view() << ']' << std::endl << "batteryState ["sv << util::hex(packet->batteryState).to_string_view() << ']' << std::endl << "batteryPercentage ["sv << util::hex(packet->batteryPercentage).to_string_view() << ']' << std::endl << "--end controller battery packet--"sv; } void print(void *payload) { auto header = (PNV_INPUT_HEADER) payload; switch (util::endian::little(header->magic)) { case MOUSE_MOVE_REL_MAGIC_GEN5: print((PNV_REL_MOUSE_MOVE_PACKET) payload); break; case MOUSE_MOVE_ABS_MAGIC: print((PNV_ABS_MOUSE_MOVE_PACKET) payload); break; case MOUSE_BUTTON_DOWN_EVENT_MAGIC_GEN5: case MOUSE_BUTTON_UP_EVENT_MAGIC_GEN5: print((PNV_MOUSE_BUTTON_PACKET) payload); break; case SCROLL_MAGIC_GEN5: print((PNV_SCROLL_PACKET) payload); break; case SS_HSCROLL_MAGIC: print((PSS_HSCROLL_PACKET) payload); break; case KEY_DOWN_EVENT_MAGIC: case KEY_UP_EVENT_MAGIC: print((PNV_KEYBOARD_PACKET) payload); break; case UTF8_TEXT_EVENT_MAGIC: print((PNV_UNICODE_PACKET) payload); break; case MULTI_CONTROLLER_MAGIC_GEN5: print((PNV_MULTI_CONTROLLER_PACKET) payload); break; case SS_TOUCH_MAGIC: print((PSS_TOUCH_PACKET) payload); break; case SS_PEN_MAGIC: print((PSS_PEN_PACKET) payload); break; case SS_CONTROLLER_ARRIVAL_MAGIC: print((PSS_CONTROLLER_ARRIVAL_PACKET) payload); break; case SS_CONTROLLER_TOUCH_MAGIC: print((PSS_CONTROLLER_TOUCH_PACKET) payload); break; case SS_CONTROLLER_MOTION_MAGIC: print((PSS_CONTROLLER_MOTION_PACKET) payload); break; case SS_CONTROLLER_BATTERY_MAGIC: print((PSS_CONTROLLER_BATTERY_PACKET) payload); break; } } void passthrough(std::shared_ptr<input_t> &input, PNV_REL_MOUSE_MOVE_PACKET packet) { if (!config::input.mouse) { return; } input->mouse_left_button_timeout = DISABLE_LEFT_BUTTON_DELAY; platf::move_mouse(platf_input, util::endian::big(packet->deltaX), util::endian::big(packet->deltaY)); } /** * @brief Converts client coordinates on the specified surface into screen coordinates. * @param input The input context. * @param val The cartesian coordinate pair to convert. * @param size The size of the client's surface containing the value. * @return The host-relative coordinate pair if a touchport is available. */ std::optional<std::pair<float, float>> client_to_touchport(std::shared_ptr<input_t> &input, const std::pair<float, float> &val, const std::pair<float, float> &size) { auto &touch_port_event = input->touch_port_event; auto &touch_port = input->touch_port; if (touch_port_event->peek()) { touch_port = *touch_port_event->pop(); } if (!touch_port) { BOOST_LOG(verbose) << "Ignoring early absolute input without a touch port"sv; return std::nullopt; } auto scalarX = touch_port.width / size.first; auto scalarY = touch_port.height / size.second; float x = std::clamp(val.first, 0.0f, size.first) * scalarX; float y = std::clamp(val.second, 0.0f, size.second) * scalarY; auto offsetX = touch_port.client_offsetX; auto offsetY = touch_port.client_offsetY; x = std::clamp(x, offsetX, (size.first * scalarX) - offsetX); y = std::clamp(y, offsetY, (size.second * scalarY) - offsetY); return std::pair { (x - offsetX) * touch_port.scalar_inv, (y - offsetY) * touch_port.scalar_inv }; } /** * @brief Multiply a polar coordinate pair by a cartesian scaling factor. * @param r The radial coordinate. * @param angle The angular coordinate (radians). * @param scalar The scalar cartesian coordinate pair. * @return The scaled radial coordinate. */ float multiply_polar_by_cartesian_scalar(float r, float angle, const std::pair<float, float> &scalar) { // Convert polar to cartesian coordinates float x = r * std::cos(angle); float y = r * std::sin(angle); // Scale the values x *= scalar.first; y *= scalar.second; // Convert the result back to a polar radial coordinate return std::sqrt(std::pow(x, 2) + std::pow(y, 2)); } std::pair<float, float> scale_client_contact_area(const std::pair<float, float> &val, uint16_t rotation, const std::pair<float, float> &scalar) { // If the rotation is unknown, we'll just scale both axes equally by using // a 45-degree angle for our scaling calculations float angle = rotation == LI_ROT_UNKNOWN ? (M_PI / 4) : (rotation * (M_PI / 180)); // If we have a major but not a minor axis, treat the touch as circular float major = val.first; float minor = val.second != 0.0f ? val.second : val.first; // The minor axis is perpendicular to major axis so the angle must be rotated by 90 degrees return { multiply_polar_by_cartesian_scalar(major, angle, scalar), multiply_polar_by_cartesian_scalar(minor, angle + (M_PI / 2), scalar) }; } void passthrough(std::shared_ptr<input_t> &input, PNV_ABS_MOUSE_MOVE_PACKET packet) { if (!config::input.mouse) { return; } if (input->mouse_left_button_timeout == DISABLE_LEFT_BUTTON_DELAY) { input->mouse_left_button_timeout = ENABLE_LEFT_BUTTON_DELAY; } float x = util::endian::big(packet->x); float y = util::endian::big(packet->y); // Prevent divide by zero // Don't expect it to happen, but just in case if (!packet->width || !packet->height) { BOOST_LOG(warning) << "Moonlight passed invalid dimensions"sv; return; } auto width = (float) util::endian::big(packet->width); auto height = (float) util::endian::big(packet->height); auto tpcoords = client_to_touchport(input, { x, y }, { width, height }); if (!tpcoords) { return; } auto &touch_port = input->touch_port; platf::touch_port_t abs_port { touch_port.offset_x, touch_port.offset_y, touch_port.env_width, touch_port.env_height }; platf::abs_mouse(platf_input, abs_port, tpcoords->first, tpcoords->second); } void passthrough(std::shared_ptr<input_t> &input, PNV_MOUSE_BUTTON_PACKET packet) { if (!config::input.mouse) { return; } auto release = util::endian::little(packet->header.magic) == MOUSE_BUTTON_UP_EVENT_MAGIC_GEN5; auto button = util::endian::big(packet->button); if (button > 0 && button < mouse_press.size()) { if (mouse_press[button] != release) { // button state is already what we want return; } mouse_press[button] = !release; } /** * When Moonlight sends mouse input through absolute coordinates, * it's possible that BUTTON_RIGHT is pressed down immediately after releasing BUTTON_LEFT. * As a result, Sunshine will left-click on hyperlinks in the browser before right-clicking * * This can be solved by delaying BUTTON_LEFT, however, any delay on input is undesirable during gaming * As a compromise, Sunshine will only put delays on BUTTON_LEFT when * absolute mouse coordinates have been sent. * * Try to make sure BUTTON_RIGHT gets called before BUTTON_LEFT is released. * * input->mouse_left_button_timeout can only be nullptr * when the last mouse coordinates were absolute */ if (button == BUTTON_LEFT && release && !input->mouse_left_button_timeout) { auto f = [=]() { auto left_released = mouse_press[BUTTON_LEFT]; if (left_released) { // Already released left button return; } platf::button_mouse(platf_input, BUTTON_LEFT, release); mouse_press[BUTTON_LEFT] = false; input->mouse_left_button_timeout = nullptr; }; input->mouse_left_button_timeout = task_pool.pushDelayed(std::move(f), 10ms).task_id; return; } if ( button == BUTTON_RIGHT && !release && input->mouse_left_button_timeout > DISABLE_LEFT_BUTTON_DELAY) { platf::button_mouse(platf_input, BUTTON_RIGHT, false); platf::button_mouse(platf_input, BUTTON_RIGHT, true); mouse_press[BUTTON_RIGHT] = false; return; } platf::button_mouse(platf_input, button, release); } short map_keycode(short keycode) { auto it = config::input.keybindings.find(keycode); if (it != std::end(config::input.keybindings)) { return it->second; } return keycode; } /** * @brief Update flags for keyboard shortcut combo's */ inline void update_shortcutFlags(int *flags, short keyCode, bool release) { switch (keyCode) { case VKEY_SHIFT: case VKEY_LSHIFT: case VKEY_RSHIFT: if (release) { *flags &= ~input_t::SHIFT; } else { *flags |= input_t::SHIFT; } break; case VKEY_CONTROL: case VKEY_LCONTROL: case VKEY_RCONTROL: if (release) { *flags &= ~input_t::CTRL; } else { *flags |= input_t::CTRL; } break; case VKEY_MENU: case VKEY_LMENU: case VKEY_RMENU: if (release) { *flags &= ~input_t::ALT; } else { *flags |= input_t::ALT; } break; } } bool is_modifier(uint16_t keyCode) { switch (keyCode) { case VKEY_SHIFT: case VKEY_LSHIFT: case VKEY_RSHIFT: case VKEY_CONTROL: case VKEY_LCONTROL: case VKEY_RCONTROL: case VKEY_MENU: case VKEY_LMENU: case VKEY_RMENU: return true; default: return false; } } void send_key_and_modifiers(uint16_t key_code, bool release, uint8_t flags, uint8_t synthetic_modifiers) { if (!release) { // Press any synthetic modifiers required for this key if (synthetic_modifiers & MODIFIER_SHIFT) { platf::keyboard_update(platf_input, VKEY_SHIFT, false, flags); } if (synthetic_modifiers & MODIFIER_CTRL) { platf::keyboard_update(platf_input, VKEY_CONTROL, false, flags); } if (synthetic_modifiers & MODIFIER_ALT) { platf::keyboard_update(platf_input, VKEY_MENU, false, flags); } } platf::keyboard_update(platf_input, map_keycode(key_code), release, flags); if (!release) { // Raise any synthetic modifier keys we pressed if (synthetic_modifiers & MODIFIER_SHIFT) { platf::keyboard_update(platf_input, VKEY_SHIFT, true, flags); } if (synthetic_modifiers & MODIFIER_CTRL) { platf::keyboard_update(platf_input, VKEY_CONTROL, true, flags); } if (synthetic_modifiers & MODIFIER_ALT) { platf::keyboard_update(platf_input, VKEY_MENU, true, flags); } } } void repeat_key(uint16_t key_code, uint8_t flags, uint8_t synthetic_modifiers) { // If key no longer pressed, stop repeating if (!key_press[make_kpid(key_code, flags)]) { key_press_repeat_id = nullptr; return; } send_key_and_modifiers(key_code, false, flags, synthetic_modifiers); key_press_repeat_id = task_pool.pushDelayed(repeat_key, config::input.key_repeat_period, key_code, flags, synthetic_modifiers).task_id; } void passthrough(std::shared_ptr<input_t> &input, PNV_KEYBOARD_PACKET packet) { if (!config::input.keyboard) { return; } auto release = util::endian::little(packet->header.magic) == KEY_UP_EVENT_MAGIC; auto keyCode = packet->keyCode & 0x00FF; // Set synthetic modifier flags if the keyboard packet is requesting modifier // keys that are not current pressed. uint8_t synthetic_modifiers = 0; if (!release && !is_modifier(keyCode)) { if (!(input->shortcutFlags & input_t::SHIFT) && (packet->modifiers & MODIFIER_SHIFT)) { synthetic_modifiers |= MODIFIER_SHIFT; } if (!(input->shortcutFlags & input_t::CTRL) && (packet->modifiers & MODIFIER_CTRL)) { synthetic_modifiers |= MODIFIER_CTRL; } if (!(input->shortcutFlags & input_t::ALT) && (packet->modifiers & MODIFIER_ALT)) { synthetic_modifiers |= MODIFIER_ALT; } } auto &pressed = key_press[make_kpid(keyCode, packet->flags)]; if (!pressed) { if (!release) { // A new key has been pressed down, we need to check for key combo's // If a key-combo has been pressed down, don't pass it through if (input->shortcutFlags == input_t::SHORTCUT && apply_shortcut(keyCode) > 0) { return; } if (key_press_repeat_id) { task_pool.cancel(key_press_repeat_id); } if (config::input.key_repeat_delay.count() > 0) { key_press_repeat_id = task_pool.pushDelayed(repeat_key, config::input.key_repeat_delay, keyCode, packet->flags, synthetic_modifiers).task_id; } } else { // Already released return; } } else if (!release) { // Already pressed down key return; } pressed = !release; send_key_and_modifiers(keyCode, release, packet->flags, synthetic_modifiers); update_shortcutFlags(&input->shortcutFlags, map_keycode(keyCode), release); } /** * @brief Called to pass a vertical scroll message the platform backend. * @param input The input context pointer. * @param packet The scroll packet. */ void passthrough(std::shared_ptr<input_t> &input, PNV_SCROLL_PACKET packet) { if (!config::input.mouse) { return; } if (config::input.high_resolution_scrolling) { platf::scroll(platf_input, util::endian::big(packet->scrollAmt1)); } else { input->accumulated_vscroll_delta += util::endian::big(packet->scrollAmt1); auto full_ticks = input->accumulated_vscroll_delta / WHEEL_DELTA; if (full_ticks) { // Send any full ticks that have accumulated and store the rest platf::scroll(platf_input, full_ticks * WHEEL_DELTA); input->accumulated_vscroll_delta -= full_ticks * WHEEL_DELTA; } } } /** * @brief Called to pass a horizontal scroll message the platform backend. * @param input The input context pointer. * @param packet The scroll packet. */ void passthrough(std::shared_ptr<input_t> &input, PSS_HSCROLL_PACKET packet) { if (!config::input.mouse) { return; } if (config::input.high_resolution_scrolling) { platf::hscroll(platf_input, util::endian::big(packet->scrollAmount)); } else { input->accumulated_hscroll_delta += util::endian::big(packet->scrollAmount); auto full_ticks = input->accumulated_hscroll_delta / WHEEL_DELTA; if (full_ticks) { // Send any full ticks that have accumulated and store the rest platf::hscroll(platf_input, full_ticks * WHEEL_DELTA); input->accumulated_hscroll_delta -= full_ticks * WHEEL_DELTA; } } } void passthrough(PNV_UNICODE_PACKET packet) { if (!config::input.keyboard) { return; } auto size = util::endian::big(packet->header.size) - sizeof(packet->header.magic); platf::unicode(platf_input, packet->text, size); } /** * @brief Called to pass a controller arrival message to the platform backend. * @param input The input context pointer. * @param packet The controller arrival packet. */ void passthrough(std::shared_ptr<input_t> &input, PSS_CONTROLLER_ARRIVAL_PACKET packet) { if (!config::input.controller) { return; } if (packet->controllerNumber < 0 || packet->controllerNumber >= input->gamepads.size()) { BOOST_LOG(warning) << "ControllerNumber out of range ["sv << packet->controllerNumber << ']'; return; } if (input->gamepads[packet->controllerNumber].id >= 0) { BOOST_LOG(warning) << "ControllerNumber already allocated ["sv << packet->controllerNumber << ']'; return; } platf::gamepad_arrival_t arrival { packet->type, util::endian::little(packet->capabilities), util::endian::little(packet->supportedButtonFlags), }; auto id = alloc_id(gamepadMask); if (id < 0) { return; } // Allocate a new gamepad if (platf::alloc_gamepad(platf_input, { id, packet->controllerNumber }, arrival, input->feedback_queue)) { free_id(gamepadMask, id); return; } input->gamepads[packet->controllerNumber].id = id; } /** * @brief Called to pass a touch message to the platform backend. * @param input The input context pointer. * @param packet The touch packet. */ void passthrough(std::shared_ptr<input_t> &input, PSS_TOUCH_PACKET packet) { if (!config::input.mouse) { return; } // Convert the client normalized coordinates to touchport coordinates auto coords = client_to_touchport(input, { from_clamped_netfloat(packet->x, 0.0f, 1.0f) * 65535.f, from_clamped_netfloat(packet->y, 0.0f, 1.0f) * 65535.f }, { 65535.f, 65535.f }); if (!coords) { return; } auto &touch_port = input->touch_port; platf::touch_port_t abs_port { touch_port.offset_x, touch_port.offset_y, touch_port.env_width, touch_port.env_height }; // Renormalize the coordinates coords->first /= abs_port.width; coords->second /= abs_port.height; // Normalize rotation value to 0-359 degree range auto rotation = util::endian::little(packet->rotation); if (rotation != LI_ROT_UNKNOWN) { rotation %= 360; } // Normalize the contact area based on the touchport auto contact_area = scale_client_contact_area( { from_clamped_netfloat(packet->contactAreaMajor, 0.0f, 1.0f) * 65535.f, from_clamped_netfloat(packet->contactAreaMinor, 0.0f, 1.0f) * 65535.f }, rotation, { abs_port.width / 65535.f, abs_port.height / 65535.f }); platf::touch_input_t touch { packet->eventType, rotation, util::endian::little(packet->pointerId), coords->first, coords->second, from_clamped_netfloat(packet->pressureOrDistance, 0.0f, 1.0f), contact_area.first, contact_area.second, }; platf::touch_update(input->client_context.get(), abs_port, touch); } /** * @brief Called to pass a pen message to the platform backend. * @param input The input context pointer. * @param packet The pen packet. */ void passthrough(std::shared_ptr<input_t> &input, PSS_PEN_PACKET packet) { if (!config::input.mouse) { return; } // Convert the client normalized coordinates to touchport coordinates auto coords = client_to_touchport(input, { from_clamped_netfloat(packet->x, 0.0f, 1.0f) * 65535.f, from_clamped_netfloat(packet->y, 0.0f, 1.0f) * 65535.f }, { 65535.f, 65535.f }); if (!coords) { return; } auto &touch_port = input->touch_port; platf::touch_port_t abs_port { touch_port.offset_x, touch_port.offset_y, touch_port.env_width, touch_port.env_height }; // Renormalize the coordinates coords->first /= abs_port.width; coords->second /= abs_port.height; // Normalize rotation value to 0-359 degree range auto rotation = util::endian::little(packet->rotation); if (rotation != LI_ROT_UNKNOWN) { rotation %= 360; } // Normalize the contact area based on the touchport auto contact_area = scale_client_contact_area( { from_clamped_netfloat(packet->contactAreaMajor, 0.0f, 1.0f) * 65535.f, from_clamped_netfloat(packet->contactAreaMinor, 0.0f, 1.0f) * 65535.f }, rotation, { abs_port.width / 65535.f, abs_port.height / 65535.f }); platf::pen_input_t pen { packet->eventType, packet->toolType, packet->penButtons, packet->tilt, rotation, coords->first, coords->second, from_clamped_netfloat(packet->pressureOrDistance, 0.0f, 1.0f), contact_area.first, contact_area.second, }; platf::pen_update(input->client_context.get(), abs_port, pen); } /** * @brief Called to pass a controller touch message to the platform backend. * @param input The input context pointer. * @param packet The controller touch packet. */ void passthrough(std::shared_ptr<input_t> &input, PSS_CONTROLLER_TOUCH_PACKET packet) { if (!config::input.controller) { return; } if (packet->controllerNumber < 0 || packet->controllerNumber >= input->gamepads.size()) { BOOST_LOG(warning) << "ControllerNumber out of range ["sv << packet->controllerNumber << ']'; return; } auto &gamepad = input->gamepads[packet->controllerNumber]; if (gamepad.id < 0) { BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv; return; } platf::gamepad_touch_t touch { { gamepad.id, packet->controllerNumber }, packet->eventType, util::endian::little(packet->pointerId), from_clamped_netfloat(packet->x, 0.0f, 1.0f), from_clamped_netfloat(packet->y, 0.0f, 1.0f), from_clamped_netfloat(packet->pressure, 0.0f, 1.0f), }; platf::gamepad_touch(platf_input, touch); } /** * @brief Called to pass a controller motion message to the platform backend. * @param input The input context pointer. * @param packet The controller motion packet. */ void passthrough(std::shared_ptr<input_t> &input, PSS_CONTROLLER_MOTION_PACKET packet) { if (!config::input.controller) { return; } if (packet->controllerNumber < 0 || packet->controllerNumber >= input->gamepads.size()) { BOOST_LOG(warning) << "ControllerNumber out of range ["sv << packet->controllerNumber << ']'; return; } auto &gamepad = input->gamepads[packet->controllerNumber]; if (gamepad.id < 0) { BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv; return; } platf::gamepad_motion_t motion { { gamepad.id, packet->controllerNumber }, packet->motionType, from_netfloat(packet->x), from_netfloat(packet->y), from_netfloat(packet->z), }; platf::gamepad_motion(platf_input, motion); } /** * @brief Called to pass a controller battery message to the platform backend. * @param input The input context pointer. * @param packet The controller battery packet. */ void passthrough(std::shared_ptr<input_t> &input, PSS_CONTROLLER_BATTERY_PACKET packet) { if (!config::input.controller) { return; } if (packet->controllerNumber < 0 || packet->controllerNumber >= input->gamepads.size()) { BOOST_LOG(warning) << "ControllerNumber out of range ["sv << packet->controllerNumber << ']'; return; } auto &gamepad = input->gamepads[packet->controllerNumber]; if (gamepad.id < 0) { BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv; return; } platf::gamepad_battery_t battery { { gamepad.id, packet->controllerNumber }, packet->batteryState, packet->batteryPercentage }; platf::gamepad_battery(platf_input, battery); } void passthrough(std::shared_ptr<input_t> &input, PNV_MULTI_CONTROLLER_PACKET packet) { if (!config::input.controller) { return; } if (packet->controllerNumber < 0 || packet->controllerNumber >= input->gamepads.size()) { BOOST_LOG(warning) << "ControllerNumber out of range ["sv << packet->controllerNumber << ']'; return; } auto &gamepad = input->gamepads[packet->controllerNumber]; // If this is an event for a new gamepad, create the gamepad now. Ideally, the client would // send a controller arrival instead of this but it's still supported for legacy clients. if ((packet->activeGamepadMask & (1 << packet->controllerNumber)) && gamepad.id < 0) { auto id = alloc_id(gamepadMask); if (id < 0) { return; } if (platf::alloc_gamepad(platf_input, { id, (uint8_t) packet->controllerNumber }, {}, input->feedback_queue)) { free_id(gamepadMask, id); return; } gamepad.id = id; } else if (!(packet->activeGamepadMask & (1 << packet->controllerNumber)) && gamepad.id >= 0) { // If this is the final event for a gamepad being removed, free the gamepad and return. free_gamepad(platf_input, gamepad.id); gamepad.id = -1; return; } // If this gamepad has not been initialized, ignore it. // This could happen when platf::alloc_gamepad fails if (gamepad.id < 0) { BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv; return; } std::uint16_t bf = packet->buttonFlags; std::uint32_t bf2 = packet->buttonFlags2; platf::gamepad_state_t gamepad_state { bf | (bf2 << 16), packet->leftTrigger, packet->rightTrigger, packet->leftStickX, packet->leftStickY, packet->rightStickX, packet->rightStickY }; auto bf_new = gamepad_state.buttonFlags; switch (gamepad.back_button_state) { case button_state_e::UP: if (!(platf::BACK & bf_new)) { gamepad.back_button_state = button_state_e::NONE; } gamepad_state.buttonFlags &= ~platf::BACK; break; case button_state_e::DOWN: if (platf::BACK & bf_new) { gamepad.back_button_state = button_state_e::NONE; } gamepad_state.buttonFlags |= platf::BACK; break; case button_state_e::NONE: break; } bf = gamepad_state.buttonFlags ^ gamepad.gamepad_state.buttonFlags; bf_new = gamepad_state.buttonFlags; if (platf::BACK & bf) { if (platf::BACK & bf_new) { // Don't emulate home button if timeout < 0 if (config::input.back_button_timeout >= 0ms) { auto f = [input, controller = packet->controllerNumber]() { auto &gamepad = input->gamepads[controller]; auto &state = gamepad.gamepad_state; // Force the back button up gamepad.back_button_state = button_state_e::UP; state.buttonFlags &= ~platf::BACK; platf::gamepad_update(platf_input, gamepad.id, state); // Press Home button state.buttonFlags |= platf::HOME; platf::gamepad_update(platf_input, gamepad.id, state); // Sleep for a short time to allow the input to be detected std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Release Home button state.buttonFlags &= ~platf::HOME; platf::gamepad_update(platf_input, gamepad.id, state); gamepad.back_timeout_id = nullptr; }; gamepad.back_timeout_id = task_pool.pushDelayed(std::move(f), config::input.back_button_timeout).task_id; } } else if (gamepad.back_timeout_id) { task_pool.cancel(gamepad.back_timeout_id); gamepad.back_timeout_id = nullptr; } } platf::gamepad_update(platf_input, gamepad.id, gamepad_state); gamepad.gamepad_state = gamepad_state; } enum class batch_result_e { batched, ///< This entry was batched with the source entry not_batchable, ///< Not eligible to batch but continue attempts to batch terminate_batch, ///< Stop trying to batch with this entry }; /** * @brief Batch two relative mouse messages. * @param dest The original packet to batch into. * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ batch_result_e batch(PNV_REL_MOUSE_MOVE_PACKET dest, PNV_REL_MOUSE_MOVE_PACKET src) { short deltaX, deltaY; // Batching is safe as long as the result doesn't overflow a 16-bit integer if (!__builtin_add_overflow(util::endian::big(dest->deltaX), util::endian::big(src->deltaX), &deltaX)) { return batch_result_e::terminate_batch; } if (!__builtin_add_overflow(util::endian::big(dest->deltaY), util::endian::big(src->deltaY), &deltaY)) { return batch_result_e::terminate_batch; } // Take the sum of deltas dest->deltaX = util::endian::big(deltaX); dest->deltaY = util::endian::big(deltaY); return batch_result_e::batched; } /** * @brief Batch two absolute mouse messages. * @param dest The original packet to batch into. * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ batch_result_e batch(PNV_ABS_MOUSE_MOVE_PACKET dest, PNV_ABS_MOUSE_MOVE_PACKET src) { // Batching must only happen if the reference width and height don't change if (dest->width != src->width || dest->height != src->height) { return batch_result_e::terminate_batch; } // Take the latest absolute position *dest = *src; return batch_result_e::batched; } /** * @brief Batch two vertical scroll messages. * @param dest The original packet to batch into. * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ batch_result_e batch(PNV_SCROLL_PACKET dest, PNV_SCROLL_PACKET src) { short scrollAmt; // Batching is safe as long as the result doesn't overflow a 16-bit integer if (!__builtin_add_overflow(util::endian::big(dest->scrollAmt1), util::endian::big(src->scrollAmt1), &scrollAmt)) { return batch_result_e::terminate_batch; } // Take the sum of delta dest->scrollAmt1 = util::endian::big(scrollAmt); dest->scrollAmt2 = util::endian::big(scrollAmt); return batch_result_e::batched; } /** * @brief Batch two horizontal scroll messages. * @param dest The original packet to batch into. * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ batch_result_e batch(PSS_HSCROLL_PACKET dest, PSS_HSCROLL_PACKET src) { short scrollAmt; // Batching is safe as long as the result doesn't overflow a 16-bit integer if (!__builtin_add_overflow(util::endian::big(dest->scrollAmount), util::endian::big(src->scrollAmount), &scrollAmt)) { return batch_result_e::terminate_batch; } // Take the sum of delta dest->scrollAmount = util::endian::big(scrollAmt); return batch_result_e::batched; } /** * @brief Batch two controller state messages. * @param dest The original packet to batch into. * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ batch_result_e batch(PNV_MULTI_CONTROLLER_PACKET dest, PNV_MULTI_CONTROLLER_PACKET src) { // Do not allow batching if the active controllers change if (dest->activeGamepadMask != src->activeGamepadMask) { return batch_result_e::terminate_batch; } // We can only batch entries for the same controller, but allow batching attempts to continue // in case we have more packets for this controller later in the queue. if (dest->controllerNumber != src->controllerNumber) { return batch_result_e::not_batchable; } // Do not allow batching if the button state changes on this controller if (dest->buttonFlags != src->buttonFlags || dest->buttonFlags2 != src->buttonFlags2) { return batch_result_e::terminate_batch; } // Take the latest state *dest = *src; return batch_result_e::batched; } /** * @brief Batch two touch messages. * @param dest The original packet to batch into. * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ batch_result_e batch(PSS_TOUCH_PACKET dest, PSS_TOUCH_PACKET src) { // Only batch hover or move events if (dest->eventType != LI_TOUCH_EVENT_MOVE && dest->eventType != LI_TOUCH_EVENT_HOVER) { return batch_result_e::terminate_batch; } // Don't batch beyond state changing events if (src->eventType != LI_TOUCH_EVENT_MOVE && src->eventType != LI_TOUCH_EVENT_HOVER) { return batch_result_e::terminate_batch; } // Batched events must be the same pointer ID if (dest->pointerId != src->pointerId) { return batch_result_e::not_batchable; } // The pointer must be in the same state if (dest->eventType != src->eventType) { return batch_result_e::terminate_batch; } // Take the latest state *dest = *src; return batch_result_e::batched; } /** * @brief Batch two pen messages. * @param dest The original packet to batch into. * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ batch_result_e batch(PSS_PEN_PACKET dest, PSS_PEN_PACKET src) { // Only batch hover or move events if (dest->eventType != LI_TOUCH_EVENT_MOVE && dest->eventType != LI_TOUCH_EVENT_HOVER) { return batch_result_e::terminate_batch; } // Batched events must be the same type if (dest->eventType != src->eventType) { return batch_result_e::terminate_batch; } // Do not allow batching if the button state changes if (dest->penButtons != src->penButtons) { return batch_result_e::terminate_batch; } // Do not batch beyond tool changes if (dest->toolType != src->toolType) { return batch_result_e::terminate_batch; } // Take the latest state *dest = *src; return batch_result_e::batched; } /** * @brief Batch two controller touch messages. * @param dest The original packet to batch into. * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ batch_result_e batch(PSS_CONTROLLER_TOUCH_PACKET dest, PSS_CONTROLLER_TOUCH_PACKET src) { // Only batch hover or move events if (dest->eventType != LI_TOUCH_EVENT_MOVE && dest->eventType != LI_TOUCH_EVENT_HOVER) { return batch_result_e::terminate_batch; } // We can only batch entries for the same controller, but allow batching attempts to continue // in case we have more packets for this controller later in the queue. if (dest->controllerNumber != src->controllerNumber) { return batch_result_e::not_batchable; } // Don't batch beyond state changing events if (src->eventType != LI_TOUCH_EVENT_MOVE && src->eventType != LI_TOUCH_EVENT_HOVER) { return batch_result_e::terminate_batch; } // Batched events must be the same pointer ID if (dest->pointerId != src->pointerId) { return batch_result_e::not_batchable; } // The pointer must be in the same state if (dest->eventType != src->eventType) { return batch_result_e::terminate_batch; } // Take the latest state *dest = *src; return batch_result_e::batched; } /** * @brief Batch two controller motion messages. * @param dest The original packet to batch into. * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ batch_result_e batch(PSS_CONTROLLER_MOTION_PACKET dest, PSS_CONTROLLER_MOTION_PACKET src) { // We can only batch entries for the same controller, but allow batching attempts to continue // in case we have more packets for this controller later in the queue. if (dest->controllerNumber != src->controllerNumber) { return batch_result_e::not_batchable; } // Batched events must be the same sensor if (dest->motionType != src->motionType) { return batch_result_e::not_batchable; } // Take the latest state *dest = *src; return batch_result_e::batched; } /** * @brief Batch two input messages. * @param dest The original packet to batch into. * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ batch_result_e batch(PNV_INPUT_HEADER dest, PNV_INPUT_HEADER src) { // We can only batch if the packet types are the same if (dest->magic != src->magic) { return batch_result_e::terminate_batch; } // We can only batch certain message types switch (util::endian::little(dest->magic)) { case MOUSE_MOVE_REL_MAGIC_GEN5: return batch((PNV_REL_MOUSE_MOVE_PACKET) dest, (PNV_REL_MOUSE_MOVE_PACKET) src); case MOUSE_MOVE_ABS_MAGIC: return batch((PNV_ABS_MOUSE_MOVE_PACKET) dest, (PNV_ABS_MOUSE_MOVE_PACKET) src); case SCROLL_MAGIC_GEN5: return batch((PNV_SCROLL_PACKET) dest, (PNV_SCROLL_PACKET) src); case SS_HSCROLL_MAGIC: return batch((PSS_HSCROLL_PACKET) dest, (PSS_HSCROLL_PACKET) src); case MULTI_CONTROLLER_MAGIC_GEN5: return batch((PNV_MULTI_CONTROLLER_PACKET) dest, (PNV_MULTI_CONTROLLER_PACKET) src); case SS_TOUCH_MAGIC: return batch((PSS_TOUCH_PACKET) dest, (PSS_TOUCH_PACKET) src); case SS_PEN_MAGIC: return batch((PSS_PEN_PACKET) dest, (PSS_PEN_PACKET) src); case SS_CONTROLLER_TOUCH_MAGIC: return batch((PSS_CONTROLLER_TOUCH_PACKET) dest, (PSS_CONTROLLER_TOUCH_PACKET) src); case SS_CONTROLLER_MOTION_MAGIC: return batch((PSS_CONTROLLER_MOTION_PACKET) dest, (PSS_CONTROLLER_MOTION_PACKET) src); default: // Not a batchable message type return batch_result_e::terminate_batch; } } /** * @brief Called on a thread pool thread to process an input message. * @param input The input context pointer. */ void passthrough_next_message(std::shared_ptr<input_t> input) { // 'entry' backs the 'payload' pointer, so they must remain in scope together std::vector<uint8_t> entry; PNV_INPUT_HEADER payload; // Lock the input queue while batching, but release it before sending // the input to the OS. This avoids potentially lengthy lock contention // in the control stream thread while input is being processed by the OS. { std::lock_guard<std::mutex> lg(input->input_queue_lock); // If all entries have already been processed, nothing to do if (input->input_queue.empty()) { return; } // Pop off the first entry, which we will send entry = input->input_queue.front(); payload = (PNV_INPUT_HEADER) entry.data(); input->input_queue.pop_front(); // Try to batch with remaining items on the queue auto i = input->input_queue.begin(); while (i != input->input_queue.end()) { auto batchable_entry = *i; auto batchable_payload = (PNV_INPUT_HEADER) batchable_entry.data(); auto batch_result = batch(payload, batchable_payload); if (batch_result == batch_result_e::terminate_batch) { // Stop batching break; } else if (batch_result == batch_result_e::batched) { // Erase this entry since it was batched i = input->input_queue.erase(i); } else { // We couldn't batch this entry, but try to batch later entries. i++; } } } // Print the final input packet input::print((void *) payload); // Send the batched input to the OS switch (util::endian::little(payload->magic)) { case MOUSE_MOVE_REL_MAGIC_GEN5: passthrough(input, (PNV_REL_MOUSE_MOVE_PACKET) payload); break; case MOUSE_MOVE_ABS_MAGIC: passthrough(input, (PNV_ABS_MOUSE_MOVE_PACKET) payload); break; case MOUSE_BUTTON_DOWN_EVENT_MAGIC_GEN5: case MOUSE_BUTTON_UP_EVENT_MAGIC_GEN5: passthrough(input, (PNV_MOUSE_BUTTON_PACKET) payload); break; case SCROLL_MAGIC_GEN5: passthrough(input, (PNV_SCROLL_PACKET) payload); break; case SS_HSCROLL_MAGIC: passthrough(input, (PSS_HSCROLL_PACKET) payload); break; case KEY_DOWN_EVENT_MAGIC: case KEY_UP_EVENT_MAGIC: passthrough(input, (PNV_KEYBOARD_PACKET) payload); break; case UTF8_TEXT_EVENT_MAGIC: passthrough((PNV_UNICODE_PACKET) payload); break; case MULTI_CONTROLLER_MAGIC_GEN5: passthrough(input, (PNV_MULTI_CONTROLLER_PACKET) payload); break; case SS_TOUCH_MAGIC: passthrough(input, (PSS_TOUCH_PACKET) payload); break; case SS_PEN_MAGIC: passthrough(input, (PSS_PEN_PACKET) payload); break; case SS_CONTROLLER_ARRIVAL_MAGIC: passthrough(input, (PSS_CONTROLLER_ARRIVAL_PACKET) payload); break; case SS_CONTROLLER_TOUCH_MAGIC: passthrough(input, (PSS_CONTROLLER_TOUCH_PACKET) payload); break; case SS_CONTROLLER_MOTION_MAGIC: passthrough(input, (PSS_CONTROLLER_MOTION_PACKET) payload); break; case SS_CONTROLLER_BATTERY_MAGIC: passthrough(input, (PSS_CONTROLLER_BATTERY_PACKET) payload); break; } } /** * @brief Called on the control stream thread to queue an input message. * @param input The input context pointer. * @param input_data The input message. */ void passthrough(std::shared_ptr<input_t> &input, std::vector<std::uint8_t> &&input_data) { { std::lock_guard<std::mutex> lg(input->input_queue_lock); input->input_queue.push_back(std::move(input_data)); } task_pool.push(passthrough_next_message, input); } void reset(std::shared_ptr<input_t> &input) { task_pool.cancel(key_press_repeat_id); task_pool.cancel(input->mouse_left_button_timeout); // Ensure input is synchronous, by using the task_pool task_pool.push([]() { for (int x = 0; x < mouse_press.size(); ++x) { if (mouse_press[x]) { platf::button_mouse(platf_input, x, true); mouse_press[x] = false; } } for (auto &kp : key_press) { if (!kp.second) { // already released continue; } platf::keyboard_update(platf_input, vk_from_kpid(kp.first) & 0x00FF, true, flags_from_kpid(kp.first)); key_press[kp.first] = false; } }); } class deinit_t: public platf::deinit_t { public: ~deinit_t() override { platf_input.reset(); } }; [[nodiscard]] std::unique_ptr<platf::deinit_t> init() { platf_input = platf::input(); return std::make_unique<deinit_t>(); } bool probe_gamepads() { auto input = static_cast<platf::input_t *>(platf_input.get()); const auto gamepads = platf::supported_gamepads(input); for (auto &gamepad : gamepads) { if (gamepad.is_enabled && gamepad.name != "auto") { return false; } } return true; } std::shared_ptr<input_t> alloc(safe::mail_t mail) { auto input = std::make_shared<input_t>( mail->event<input::touch_port_t>(mail::touch_port), mail->queue<platf::gamepad_feedback_msg_t>(mail::gamepad_feedback)); // Workaround to ensure new frames will be captured when a client connects task_pool.pushDelayed([]() { platf::move_mouse(platf_input, 1, 1); platf::move_mouse(platf_input, -1, -1); }, 100ms); return input; } } // namespace input
57,366
C++
.cpp
1,481
32.896691
151
0.642155
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,976
main.cpp
LizardByte_Sunshine/src/main.cpp
/** * @file src/main.cpp * @brief Definitions for the main entry point for Sunshine. */ // standard includes #include <codecvt> #include <csignal> #include <fstream> #include <iostream> // local includes #include "confighttp.h" #include "entry_handler.h" #include "globals.h" #include "httpcommon.h" #include "logging.h" #include "main.h" #include "nvhttp.h" #include "process.h" #include "system_tray.h" #include "upnp.h" #include "version.h" #include "video.h" extern "C" { #include "rswrapper.h" } using namespace std::literals; std::map<int, std::function<void()>> signal_handlers; void on_signal_forwarder(int sig) { signal_handlers.at(sig)(); } template <class FN> void on_signal(int sig, FN &&fn) { signal_handlers.emplace(sig, std::forward<FN>(fn)); std::signal(sig, on_signal_forwarder); } std::map<std::string_view, std::function<int(const char *name, int argc, char **argv)>> cmd_to_func { { "creds"sv, [](const char *name, int argc, char **argv) { return args::creds(name, argc, argv); } }, { "help"sv, [](const char *name, int argc, char **argv) { return args::help(name); } }, { "version"sv, [](const char *name, int argc, char **argv) { return args::version(); } }, #ifdef _WIN32 { "restore-nvprefs-undo"sv, [](const char *name, int argc, char **argv) { return args::restore_nvprefs_undo(); } }, #endif }; #ifdef _WIN32 LRESULT CALLBACK SessionMonitorWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CLOSE: DestroyWindow(hwnd); return 0; case WM_DESTROY: PostQuitMessage(0); return 0; case WM_ENDSESSION: { // Terminate ourselves with a blocking exit call std::cout << "Received WM_ENDSESSION"sv << std::endl; lifetime::exit_sunshine(0, false); return 0; } default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } } WINAPI BOOL ConsoleCtrlHandler(DWORD type) { if (type == CTRL_CLOSE_EVENT) { BOOST_LOG(info) << "Console closed handler called"; lifetime::exit_sunshine(0, false); } return FALSE; } #endif int main(int argc, char *argv[]) { lifetime::argv = argv; task_pool_util::TaskPool::task_id_t force_shutdown = nullptr; #ifdef _WIN32 setlocale(LC_ALL, "C"); #endif #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // Use UTF-8 conversion for the default C++ locale (used by boost::log) std::locale::global(std::locale(std::locale(), new std::codecvt_utf8<wchar_t>)); #pragma GCC diagnostic pop mail::man = std::make_shared<safe::mail_raw_t>(); if (config::parse(argc, argv)) { return 0; } auto log_deinit_guard = logging::init(config::sunshine.min_log_level, config::sunshine.log_file); if (!log_deinit_guard) { BOOST_LOG(error) << "Logging failed to initialize"sv; } // logging can begin at this point // if anything is logged prior to this point, it will appear in stdout, but not in the log viewer in the UI // the version should be printed to the log before anything else BOOST_LOG(info) << PROJECT_NAME << " version: " << PROJECT_VER; // Log publisher metadata log_publisher_data(); if (!config::sunshine.cmd.name.empty()) { auto fn = cmd_to_func.find(config::sunshine.cmd.name); if (fn == std::end(cmd_to_func)) { BOOST_LOG(fatal) << "Unknown command: "sv << config::sunshine.cmd.name; BOOST_LOG(info) << "Possible commands:"sv; for (auto &[key, _] : cmd_to_func) { BOOST_LOG(info) << '\t' << key; } return 7; } return fn->second(argv[0], config::sunshine.cmd.argc, config::sunshine.cmd.argv); } #ifdef WIN32 // Modify relevant NVIDIA control panel settings if the system has corresponding gpu if (nvprefs_instance.load()) { // Restore global settings to the undo file left by improper termination of sunshine.exe nvprefs_instance.restore_from_and_delete_undo_file_if_exists(); // Modify application settings for sunshine.exe nvprefs_instance.modify_application_profile(); // Modify global settings, undo file is produced in the process to restore after improper termination nvprefs_instance.modify_global_profile(); // Unload dynamic library to survive driver re-installation nvprefs_instance.unload(); } // Wait as long as possible to terminate Sunshine.exe during logoff/shutdown SetProcessShutdownParameters(0x100, SHUTDOWN_NORETRY); // We must create a hidden window to receive shutdown notifications since we load gdi32.dll std::promise<HWND> session_monitor_hwnd_promise; auto session_monitor_hwnd_future = session_monitor_hwnd_promise.get_future(); std::promise<void> session_monitor_join_thread_promise; auto session_monitor_join_thread_future = session_monitor_join_thread_promise.get_future(); std::thread session_monitor_thread([&]() { session_monitor_join_thread_promise.set_value_at_thread_exit(); WNDCLASSA wnd_class {}; wnd_class.lpszClassName = "SunshineSessionMonitorClass"; wnd_class.lpfnWndProc = SessionMonitorWindowProc; if (!RegisterClassA(&wnd_class)) { session_monitor_hwnd_promise.set_value(NULL); BOOST_LOG(error) << "Failed to register session monitor window class"sv << std::endl; return; } auto wnd = CreateWindowExA( 0, wnd_class.lpszClassName, "Sunshine Session Monitor Window", 0, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr, nullptr, nullptr); session_monitor_hwnd_promise.set_value(wnd); if (!wnd) { BOOST_LOG(error) << "Failed to create session monitor window"sv << std::endl; return; } ShowWindow(wnd, SW_HIDE); // Run the message loop for our window MSG msg {}; while (GetMessage(&msg, nullptr, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } }); auto session_monitor_join_thread_guard = util::fail_guard([&]() { if (session_monitor_hwnd_future.wait_for(1s) == std::future_status::ready) { if (HWND session_monitor_hwnd = session_monitor_hwnd_future.get()) { PostMessage(session_monitor_hwnd, WM_CLOSE, 0, 0); } if (session_monitor_join_thread_future.wait_for(1s) == std::future_status::ready) { session_monitor_thread.join(); return; } else { BOOST_LOG(warning) << "session_monitor_join_thread_future reached timeout"; } } else { BOOST_LOG(warning) << "session_monitor_hwnd_future reached timeout"; } session_monitor_thread.detach(); }); #endif task_pool.start(1); #if defined SUNSHINE_TRAY && SUNSHINE_TRAY >= 1 // create tray thread and detach it system_tray::run_tray(); #endif // Create signal handler after logging has been initialized auto shutdown_event = mail::man->event<bool>(mail::shutdown); on_signal(SIGINT, [&force_shutdown, shutdown_event]() { BOOST_LOG(info) << "Interrupt handler called"sv; auto task = []() { BOOST_LOG(fatal) << "10 seconds passed, yet Sunshine's still running: Forcing shutdown"sv; logging::log_flush(); lifetime::debug_trap(); }; force_shutdown = task_pool.pushDelayed(task, 10s).task_id; shutdown_event->raise(true); }); on_signal(SIGTERM, [&force_shutdown, shutdown_event]() { BOOST_LOG(info) << "Terminate handler called"sv; auto task = []() { BOOST_LOG(fatal) << "10 seconds passed, yet Sunshine's still running: Forcing shutdown"sv; logging::log_flush(); lifetime::debug_trap(); }; force_shutdown = task_pool.pushDelayed(task, 10s).task_id; shutdown_event->raise(true); }); #ifdef _WIN32 // Terminate gracefully on Windows when console window is closed SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); #endif proc::refresh(config::stream.file_apps); // If any of the following fail, we log an error and continue event though sunshine will not function correctly. // This allows access to the UI to fix configuration problems or view the logs. auto platf_deinit_guard = platf::init(); if (!platf_deinit_guard) { BOOST_LOG(error) << "Platform failed to initialize"sv; } auto proc_deinit_guard = proc::init(); if (!proc_deinit_guard) { BOOST_LOG(error) << "Proc failed to initialize"sv; } reed_solomon_init(); auto input_deinit_guard = input::init(); if (input::probe_gamepads()) { BOOST_LOG(warning) << "No gamepad input is available"sv; } if (video::probe_encoders()) { BOOST_LOG(error) << "Video failed to find working encoder"sv; } if (http::init()) { BOOST_LOG(fatal) << "HTTP interface failed to initialize"sv; #ifdef _WIN32 BOOST_LOG(fatal) << "To relaunch Sunshine successfully, use the shortcut in the Start Menu. Do not run Sunshine.exe manually."sv; std::this_thread::sleep_for(10s); #endif return -1; } std::unique_ptr<platf::deinit_t> mDNS; auto sync_mDNS = std::async(std::launch::async, [&mDNS]() { mDNS = platf::publish::start(); }); std::unique_ptr<platf::deinit_t> upnp_unmap; auto sync_upnp = std::async(std::launch::async, [&upnp_unmap]() { upnp_unmap = upnp::start(); }); // FIXME: Temporary workaround: Simple-Web_server needs to be updated or replaced if (shutdown_event->peek()) { return lifetime::desired_exit_code; } std::thread httpThread { nvhttp::start }; std::thread configThread { confighttp::start }; #ifdef _WIN32 // If we're using the default port and GameStream is enabled, warn the user if (config::sunshine.port == 47989 && is_gamestream_enabled()) { BOOST_LOG(fatal) << "GameStream is still enabled in GeForce Experience! This *will* cause streaming problems with Sunshine!"sv; BOOST_LOG(fatal) << "Disable GameStream on the SHIELD tab in GeForce Experience or change the Port setting on the Advanced tab in the Sunshine Web UI."sv; } #endif rtsp_stream::rtpThread(); httpThread.join(); configThread.join(); task_pool.stop(); task_pool.join(); // stop system tray #if defined SUNSHINE_TRAY && SUNSHINE_TRAY >= 1 system_tray::end_tray(); #endif #ifdef WIN32 // Restore global NVIDIA control panel settings if (nvprefs_instance.owning_undo_file() && nvprefs_instance.load()) { nvprefs_instance.restore_global_profile(); nvprefs_instance.unload(); } #endif return lifetime::desired_exit_code; }
10,408
C++
.cpp
283
32.791519
158
0.692117
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,977
stream.cpp
LizardByte_Sunshine/src/stream.cpp
/** * @file src/stream.cpp * @brief Definitions for the streaming protocols. */ #include "process.h" #include <future> #include <queue> #include <fstream> #include <openssl/err.h> #include <boost/endian/arithmetic.hpp> extern "C" { // clang-format off #include <moonlight-common-c/src/Limelight-internal.h> #include "rswrapper.h" // clang-format on } #include "config.h" #include "globals.h" #include "input.h" #include "logging.h" #include "network.h" #include "stream.h" #include "sync.h" #include "system_tray.h" #include "thread_safe.h" #include "utility.h" #include "platform/common.h" #define IDX_START_A 0 #define IDX_START_B 1 #define IDX_INVALIDATE_REF_FRAMES 2 #define IDX_LOSS_STATS 3 #define IDX_INPUT_DATA 5 #define IDX_RUMBLE_DATA 6 #define IDX_TERMINATION 7 #define IDX_PERIODIC_PING 8 #define IDX_REQUEST_IDR_FRAME 9 #define IDX_ENCRYPTED 10 #define IDX_HDR_MODE 11 #define IDX_RUMBLE_TRIGGER_DATA 12 #define IDX_SET_MOTION_EVENT 13 #define IDX_SET_RGB_LED 14 static const short packetTypes[] = { 0x0305, // Start A 0x0307, // Start B 0x0301, // Invalidate reference frames 0x0201, // Loss Stats 0x0204, // Frame Stats (unused) 0x0206, // Input data 0x010b, // Rumble data 0x0109, // Termination 0x0200, // Periodic Ping 0x0302, // IDR frame 0x0001, // fully encrypted 0x010e, // HDR mode 0x5500, // Rumble triggers (Sunshine protocol extension) 0x5501, // Set motion event (Sunshine protocol extension) 0x5502, // Set RGB LED (Sunshine protocol extension) }; namespace asio = boost::asio; namespace sys = boost::system; using asio::ip::tcp; using asio::ip::udp; using namespace std::literals; namespace stream { enum class socket_e : int { video, ///< Video audio ///< Audio }; #pragma pack(push, 1) struct video_short_frame_header_t { uint8_t * payload() { return (uint8_t *) (this + 1); } std::uint8_t headerType; // Always 0x01 for short headers // Sunshine extension // Frame processing latency, in 1/10 ms units // zero when the frame is repeated or there is no backend implementation boost::endian::little_uint16_at frame_processing_latency; // Currently known values: // 1 = Normal P-frame // 2 = IDR-frame // 4 = P-frame with intra-refresh blocks // 5 = P-frame after reference frame invalidation std::uint8_t frameType; // Length of the final packet payload for codecs that cannot handle // zero padding, such as AV1 (Sunshine extension). boost::endian::little_uint16_at lastPayloadLen; std::uint8_t unknown[2]; }; static_assert( sizeof(video_short_frame_header_t) == 8, "Short frame header must be 8 bytes"); struct video_packet_raw_t { uint8_t * payload() { return (uint8_t *) (this + 1); } RTP_PACKET rtp; char reserved[4]; NV_VIDEO_PACKET packet; }; struct video_packet_enc_prefix_t { std::uint8_t iv[12]; // 12-byte IV is ideal for AES-GCM std::uint32_t frameNumber; std::uint8_t tag[16]; }; struct audio_packet_t { RTP_PACKET rtp; }; struct control_header_v2 { std::uint16_t type; std::uint16_t payloadLength; uint8_t * payload() { return (uint8_t *) (this + 1); } }; struct control_terminate_t { control_header_v2 header; std::uint32_t ec; }; struct control_rumble_t { control_header_v2 header; std::uint32_t useless; std::uint16_t id; std::uint16_t lowfreq; std::uint16_t highfreq; }; struct control_rumble_triggers_t { control_header_v2 header; std::uint16_t id; std::uint16_t left; std::uint16_t right; }; struct control_set_motion_event_t { control_header_v2 header; std::uint16_t id; std::uint16_t reportrate; std::uint8_t type; }; struct control_set_rgb_led_t { control_header_v2 header; std::uint16_t id; std::uint8_t r; std::uint8_t g; std::uint8_t b; }; struct control_hdr_mode_t { control_header_v2 header; std::uint8_t enabled; // Sunshine protocol extension SS_HDR_METADATA metadata; }; typedef struct control_encrypted_t { std::uint16_t encryptedHeaderType; // Always LE 0x0001 std::uint16_t length; // sizeof(seq) + 16 byte tag + secondary header and data // seq is accepted as an arbitrary value in Moonlight std::uint32_t seq; // Monotonically increasing sequence number (used as IV for AES-GCM) uint8_t * payload() { return (uint8_t *) (this + 1); } // encrypted control_header_v2 and payload data follow } *control_encrypted_p; struct audio_fec_packet_t { RTP_PACKET rtp; AUDIO_FEC_HEADER fecHeader; }; #pragma pack(pop) constexpr std::size_t round_to_pkcs7_padded(std::size_t size) { return ((size + 15) / 16) * 16; } constexpr std::size_t MAX_AUDIO_PACKET_SIZE = 1400; using audio_aes_t = std::array<char, round_to_pkcs7_padded(MAX_AUDIO_PACKET_SIZE)>; using av_session_id_t = std::variant<asio::ip::address, std::string>; // IP address or SS-Ping-Payload from RTSP handshake using message_queue_t = std::shared_ptr<safe::queue_t<std::pair<udp::endpoint, std::string>>>; using message_queue_queue_t = std::shared_ptr<safe::queue_t<std::tuple<socket_e, av_session_id_t, message_queue_t>>>; // return bytes written on success // return -1 on error static inline int encode_audio(bool encrypted, const audio::buffer_t &plaintext, uint8_t *destination, crypto::aes_t &iv, crypto::cipher::cbc_t &cbc) { // If encryption isn't enabled if (!encrypted) { std::copy(std::begin(plaintext), std::end(plaintext), destination); return plaintext.size(); } return cbc.encrypt(std::string_view { (char *) std::begin(plaintext), plaintext.size() }, destination, &iv); } static inline void while_starting_do_nothing(std::atomic<session::state_e> &state) { while (state.load(std::memory_order_acquire) == session::state_e::STARTING) { std::this_thread::sleep_for(1ms); } } class control_server_t { public: int bind(net::af_e address_family, std::uint16_t port) { _host = net::host_create(address_family, _addr, port); return !(bool) _host; } // Get session associated with address. // If none are found, try to find a session not yet claimed. (It will be marked by a port of value 0 // If none of those are found, return nullptr session_t * get_session(const net::peer_t peer, uint32_t connect_data); // Circular dependency: // iterate refers to session // session refers to broadcast_ctx_t // broadcast_ctx_t refers to control_server_t // Therefore, iterate is implemented further down the source file void iterate(std::chrono::milliseconds timeout); /** * @brief Call the handler for a given control stream message. * @param type The message type. * @param session The session the message was received on. * @param payload The payload of the message. * @param reinjected `true` if this message is being reprocessed after decryption. */ void call(std::uint16_t type, session_t *session, const std::string_view &payload, bool reinjected); void map(uint16_t type, std::function<void(session_t *, const std::string_view &)> cb) { _map_type_cb.emplace(type, std::move(cb)); } int send(const std::string_view &payload, net::peer_t peer) { auto packet = enet_packet_create(payload.data(), payload.size(), ENET_PACKET_FLAG_RELIABLE); if (enet_peer_send(peer, 0, packet)) { enet_packet_destroy(packet); return -1; } return 0; } void flush() { enet_host_flush(_host.get()); } // Callbacks std::unordered_map<std::uint16_t, std::function<void(session_t *, const std::string_view &)>> _map_type_cb; // All active sessions (including those still waiting for a peer to connect) sync_util::sync_t<std::vector<session_t *>> _sessions; // ENet peer to session mapping for sessions with a peer connected sync_util::sync_t<std::map<net::peer_t, session_t *>> _peer_to_session; ENetAddress _addr; net::host_t _host; }; struct broadcast_ctx_t { message_queue_queue_t message_queue_queue; std::thread recv_thread; std::thread video_thread; std::thread audio_thread; std::thread control_thread; asio::io_service io; udp::socket video_sock { io }; udp::socket audio_sock { io }; control_server_t control_server; }; struct session_t { config_t config; safe::mail_t mail; std::shared_ptr<input::input_t> input; std::thread audioThread; std::thread videoThread; std::chrono::steady_clock::time_point pingTimeout; safe::shared_t<broadcast_ctx_t>::ptr_t broadcast_ref; boost::asio::ip::address localAddress; struct { std::string ping_payload; int lowseq; udp::endpoint peer; std::optional<crypto::cipher::gcm_t> cipher; std::uint64_t gcm_iv_counter; safe::mail_raw_t::event_t<bool> idr_events; safe::mail_raw_t::event_t<std::pair<int64_t, int64_t>> invalidate_ref_frames_events; std::unique_ptr<platf::deinit_t> qos; } video; struct { crypto::cipher::cbc_t cipher; std::string ping_payload; std::uint16_t sequenceNumber; // avRiKeyId == util::endian::big(First (sizeof(avRiKeyId)) bytes of launch_session->iv) std::uint32_t avRiKeyId; std::uint32_t timestamp; udp::endpoint peer; util::buffer_t<char> shards; util::buffer_t<uint8_t *> shards_p; audio_fec_packet_t fec_packet; std::unique_ptr<platf::deinit_t> qos; } audio; struct { crypto::cipher::gcm_t cipher; crypto::aes_t legacy_input_enc_iv; // Only used when the client doesn't support full control stream encryption crypto::aes_t incoming_iv; crypto::aes_t outgoing_iv; std::uint32_t connect_data; // Used for new clients with ML_FF_SESSION_ID_V1 std::string expected_peer_address; // Only used for legacy clients without ML_FF_SESSION_ID_V1 net::peer_t peer; std::uint32_t seq; platf::feedback_queue_t feedback_queue; safe::mail_raw_t::event_t<video::hdr_info_t> hdr_queue; } control; std::uint32_t launch_session_id; safe::mail_raw_t::event_t<bool> shutdown_event; safe::signal_t controlEnd; std::atomic<session::state_e> state; }; /** * First part of cipher must be struct of type control_encrypted_t * * returns empty string_view on failure * returns string_view pointing to payload data */ template <std::size_t max_payload_size> static inline std::string_view encode_control(session_t *session, const std::string_view &plaintext, std::array<std::uint8_t, max_payload_size> &tagged_cipher) { static_assert( max_payload_size >= sizeof(control_encrypted_t) + sizeof(crypto::cipher::tag_size), "max_payload_size >= sizeof(control_encrypted_t) + sizeof(crypto::cipher::tag_size)"); if (session->config.controlProtocolType != 13) { return plaintext; } auto seq = session->control.seq++; auto &iv = session->control.outgoing_iv; if (session->config.encryptionFlagsEnabled & SS_ENC_CONTROL_V2) { // We use the deterministic IV construction algorithm specified in NIST SP 800-38D // Section 8.2.1. The sequence number is our "invocation" field and the 'CH' in the // high bytes is the "fixed" field. Because each client provides their own unique // key, our values in the fixed field need only uniquely identify each independent // use of the client's key with AES-GCM in our code. // // The sequence number is 32 bits long which allows for 2^32 control stream messages // to be sent to each client before the IV repeats. iv.resize(12); std::copy_n((uint8_t *) &seq, sizeof(seq), std::begin(iv)); iv[10] = 'H'; // Host originated iv[11] = 'C'; // Control stream } else { // Nvidia's old style encryption uses a 16-byte IV iv.resize(16); iv[0] = (std::uint8_t) seq; } auto packet = (control_encrypted_p) tagged_cipher.data(); auto bytes = session->control.cipher.encrypt(plaintext, packet->payload(), &iv); if (bytes <= 0) { BOOST_LOG(error) << "Couldn't encrypt control data"sv; return {}; } std::uint16_t packet_length = bytes + crypto::cipher::tag_size + sizeof(control_encrypted_t::seq); packet->encryptedHeaderType = util::endian::little(0x0001); packet->length = util::endian::little(packet_length); packet->seq = util::endian::little(seq); return std::string_view { (char *) tagged_cipher.data(), packet_length + sizeof(control_encrypted_t) - sizeof(control_encrypted_t::seq) }; } int start_broadcast(broadcast_ctx_t &ctx); void end_broadcast(broadcast_ctx_t &ctx); static auto broadcast = safe::make_shared<broadcast_ctx_t>(start_broadcast, end_broadcast); session_t * control_server_t::get_session(const net::peer_t peer, uint32_t connect_data) { { // Fast path - look up existing session by peer auto lg = _peer_to_session.lock(); auto it = _peer_to_session->find(peer); if (it != _peer_to_session->end()) { return it->second; } } // Slow path - process new session TUPLE_2D(peer_port, peer_addr, platf::from_sockaddr_ex((sockaddr *) &peer->address.address)); auto lg = _sessions.lock(); for (auto pos = std::begin(*_sessions); pos != std::end(*_sessions); ++pos) { auto session_p = *pos; // Skip sessions that are already established if (session_p->control.peer) { continue; } // Identify the connection by the unique connect data if the client supports it. // Only fall back to IP address matching for clients without session ID support. if (session_p->config.mlFeatureFlags & ML_FF_SESSION_ID_V1) { if (session_p->control.connect_data != connect_data) { continue; } else { BOOST_LOG(debug) << "Initialized new control stream session by connect data match [v2]"sv; } } else { if (session_p->control.expected_peer_address != peer_addr) { continue; } else { BOOST_LOG(debug) << "Initialized new control stream session by IP address match [v1]"sv; } } // Once the control stream connection is established, RTSP session state can be torn down rtsp_stream::launch_session_clear(session_p->launch_session_id); session_p->control.peer = peer; // Use the local address from the control connection as the source address // for other communications to the client. This is necessary to ensure // proper routing on multi-homed hosts. auto local_address = platf::from_sockaddr((sockaddr *) &peer->localAddress.address); session_p->localAddress = boost::asio::ip::make_address(local_address); BOOST_LOG(debug) << "Control local address ["sv << local_address << ']'; BOOST_LOG(debug) << "Control peer address ["sv << peer_addr << ':' << peer_port << ']'; // Insert this into the map for O(1) lookups in the future auto ptslg = _peer_to_session.lock(); _peer_to_session->emplace(peer, session_p); return session_p; } return nullptr; } /** * @brief Call the handler for a given control stream message. * @param type The message type. * @param session The session the message was received on. * @param payload The payload of the message. * @param reinjected `true` if this message is being reprocessed after decryption. */ void control_server_t::call(std::uint16_t type, session_t *session, const std::string_view &payload, bool reinjected) { // If we are using the encrypted control stream protocol, drop any messages that come off the wire unencrypted if (session->config.controlProtocolType == 13 && !reinjected && type != packetTypes[IDX_ENCRYPTED]) { BOOST_LOG(error) << "Dropping unencrypted message on encrypted control stream: "sv << util::hex(type).to_string_view(); return; } auto cb = _map_type_cb.find(type); if (cb == std::end(_map_type_cb)) { BOOST_LOG(debug) << "type [Unknown] { "sv << util::hex(type).to_string_view() << " }"sv << std::endl << "---data---"sv << std::endl << util::hex_vec(payload) << std::endl << "---end data---"sv; } else { cb->second(session, payload); } } void control_server_t::iterate(std::chrono::milliseconds timeout) { ENetEvent event; auto res = enet_host_service(_host.get(), &event, timeout.count()); if (res > 0) { auto session = get_session(event.peer, event.data); if (!session) { BOOST_LOG(warning) << "Rejected connection from ["sv << platf::from_sockaddr((sockaddr *) &event.peer->address.address) << "]: it's not properly set up"sv; enet_peer_disconnect_now(event.peer, 0); return; } session->pingTimeout = std::chrono::steady_clock::now() + config::stream.ping_timeout; switch (event.type) { case ENET_EVENT_TYPE_RECEIVE: { net::packet_t packet { event.packet }; auto type = *(std::uint16_t *) packet->data; std::string_view payload { (char *) packet->data + sizeof(type), packet->dataLength - sizeof(type) }; call(type, session, payload, false); } break; case ENET_EVENT_TYPE_CONNECT: BOOST_LOG(info) << "CLIENT CONNECTED"sv; break; case ENET_EVENT_TYPE_DISCONNECT: BOOST_LOG(info) << "CLIENT DISCONNECTED"sv; // No more clients to send video data to ^_^ if (session->state == session::state_e::RUNNING) { session::stop(*session); } break; case ENET_EVENT_TYPE_NONE: break; } } } namespace fec { using rs_t = util::safe_ptr<reed_solomon, [](reed_solomon *rs) { reed_solomon_release(rs); }>; struct fec_t { size_t data_shards; size_t nr_shards; size_t percentage; size_t blocksize; size_t prefixsize; util::buffer_t<char> shards; util::buffer_t<char> headers; util::buffer_t<uint8_t *> shards_p; std::vector<platf::buffer_descriptor_t> payload_buffers; char * data(size_t el) { return (char *) shards_p[el]; } char * prefix(size_t el) { return prefixsize ? &headers[el * prefixsize] : nullptr; } size_t size() const { return nr_shards; } }; static fec_t encode(const std::string_view &payload, size_t blocksize, size_t fecpercentage, size_t minparityshards, size_t prefixsize) { auto payload_size = payload.size(); auto pad = payload_size % blocksize != 0; auto aligned_data_shards = payload_size / blocksize; auto data_shards = aligned_data_shards + (pad ? 1 : 0); auto parity_shards = (data_shards * fecpercentage + 99) / 100; // increase the FEC percentage for this frame if the parity shard minimum is not met if (parity_shards < minparityshards && fecpercentage != 0) { parity_shards = minparityshards; fecpercentage = (100 * parity_shards) / data_shards; BOOST_LOG(verbose) << "Increasing FEC percentage to "sv << fecpercentage << " to meet parity shard minimum"sv << std::endl; } auto nr_shards = data_shards + parity_shards; // If we need to store a zero-padded data shard, allocate that first to // to keep the shards in order and reduce buffer fragmentation auto parity_shard_offset = pad ? 1 : 0; util::buffer_t<char> shards { (parity_shard_offset + parity_shards) * blocksize }; util::buffer_t<uint8_t *> shards_p { nr_shards }; std::vector<platf::buffer_descriptor_t> payload_buffers; payload_buffers.reserve(2); // Point into the payload buffer for all except the final padded data shard auto next = std::begin(payload); for (auto x = 0; x < aligned_data_shards; ++x) { shards_p[x] = (uint8_t *) next; next += blocksize; } payload_buffers.emplace_back(std::begin(payload), aligned_data_shards * blocksize); // If the last data shard needs to be zero-padded, we must use the shards buffer if (pad) { shards_p[aligned_data_shards] = (uint8_t *) &shards[0]; // GCC doesn't figure out that std::copy_n() can be replaced with memcpy() here // and ends up compiling a horribly slow element-by-element copy loop, so we // help it by using memcpy()/memset() directly. auto copy_len = std::min<size_t>(blocksize, std::end(payload) - next); std::memcpy(shards_p[aligned_data_shards], next, copy_len); if (copy_len < blocksize) { // Zero any additional space after the end of the payload std::memset(shards_p[aligned_data_shards] + copy_len, 0, blocksize - copy_len); } } // Add a payload buffer describing the shard buffer payload_buffers.emplace_back(std::begin(shards), shards.size()); if (fecpercentage != 0) { // Point into our allocated buffer for the parity shards for (auto x = 0; x < parity_shards; ++x) { shards_p[data_shards + x] = (uint8_t *) &shards[(parity_shard_offset + x) * blocksize]; } // packets = parity_shards + data_shards rs_t rs { reed_solomon_new(data_shards, parity_shards) }; reed_solomon_encode(rs.get(), shards_p.begin(), nr_shards, blocksize); } return { data_shards, nr_shards, fecpercentage, blocksize, prefixsize, std::move(shards), util::buffer_t<char> { nr_shards * prefixsize }, std::move(shards_p), std::move(payload_buffers), }; } } // namespace fec /** * @brief Combines two buffers and inserts new buffers at each slice boundary of the result. * @param insert_size The number of bytes to insert. * @param slice_size The number of bytes between insertions. * @param data1 The first data buffer. * @param data2 The second data buffer. */ std::vector<uint8_t> concat_and_insert(uint64_t insert_size, uint64_t slice_size, const std::string_view &data1, const std::string_view &data2) { auto data_size = data1.size() + data2.size(); auto pad = data_size % slice_size != 0; auto elements = data_size / slice_size + (pad ? 1 : 0); std::vector<uint8_t> result; result.resize(elements * insert_size + data_size); auto next = std::begin(data1); auto end = std::end(data1); for (auto x = 0; x < elements; ++x) { void *p = &result[x * (insert_size + slice_size)]; // For the last iteration, only copy to the end of the data if (x == elements - 1) { slice_size = data_size - (x * slice_size); } // Test if this slice will extend into the next buffer if (next + slice_size > end) { // Copy the first portion from the first buffer auto copy_len = end - next; std::copy(next, end, (char *) p + insert_size); // Copy the remaining portion from the second buffer next = std::begin(data2); end = std::end(data2); std::copy(next, next + (slice_size - copy_len), (char *) p + copy_len + insert_size); next += slice_size - copy_len; } else { std::copy(next, next + slice_size, (char *) p + insert_size); next += slice_size; } } return result; } std::vector<uint8_t> replace(const std::string_view &original, const std::string_view &old, const std::string_view &_new) { std::vector<uint8_t> replaced; replaced.reserve(original.size() + _new.size() - old.size()); auto begin = std::begin(original); auto end = std::end(original); auto next = std::search(begin, end, std::begin(old), std::end(old)); std::copy(begin, next, std::back_inserter(replaced)); if (next != end) { std::copy(std::begin(_new), std::end(_new), std::back_inserter(replaced)); std::copy(next + old.size(), end, std::back_inserter(replaced)); } return replaced; } /** * @brief Pass gamepad feedback data back to the client. * @param session The session object. * @param msg The message to pass. * @return 0 on success. */ int send_feedback_msg(session_t *session, platf::gamepad_feedback_msg_t &msg) { if (!session->control.peer) { BOOST_LOG(warning) << "Couldn't send gamepad feedback data, still waiting for PING from Moonlight"sv; // Still waiting for PING from Moonlight return -1; } std::string payload; if (msg.type == platf::gamepad_feedback_e::rumble) { control_rumble_t plaintext; plaintext.header.type = packetTypes[IDX_RUMBLE_DATA]; plaintext.header.payloadLength = sizeof(plaintext) - sizeof(control_header_v2); auto &data = msg.data.rumble; plaintext.useless = 0xC0FFEE; plaintext.id = util::endian::little(msg.id); plaintext.lowfreq = util::endian::little(data.lowfreq); plaintext.highfreq = util::endian::little(data.highfreq); BOOST_LOG(verbose) << "Rumble: "sv << msg.id << " :: "sv << util::hex(data.lowfreq).to_string_view() << " :: "sv << util::hex(data.highfreq).to_string_view(); std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size> encrypted_payload; payload = encode_control(session, util::view(plaintext), encrypted_payload); } else if (msg.type == platf::gamepad_feedback_e::rumble_triggers) { control_rumble_triggers_t plaintext; plaintext.header.type = packetTypes[IDX_RUMBLE_TRIGGER_DATA]; plaintext.header.payloadLength = sizeof(plaintext) - sizeof(control_header_v2); auto &data = msg.data.rumble_triggers; plaintext.id = util::endian::little(msg.id); plaintext.left = util::endian::little(data.left_trigger); plaintext.right = util::endian::little(data.right_trigger); BOOST_LOG(verbose) << "Rumble triggers: "sv << msg.id << " :: "sv << util::hex(data.left_trigger).to_string_view() << " :: "sv << util::hex(data.right_trigger).to_string_view(); std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size> encrypted_payload; payload = encode_control(session, util::view(plaintext), encrypted_payload); } else if (msg.type == platf::gamepad_feedback_e::set_motion_event_state) { control_set_motion_event_t plaintext; plaintext.header.type = packetTypes[IDX_SET_MOTION_EVENT]; plaintext.header.payloadLength = sizeof(plaintext) - sizeof(control_header_v2); auto &data = msg.data.motion_event_state; plaintext.id = util::endian::little(msg.id); plaintext.reportrate = util::endian::little(data.report_rate); plaintext.type = data.motion_type; BOOST_LOG(verbose) << "Motion event state: "sv << msg.id << " :: "sv << util::hex(data.report_rate).to_string_view() << " :: "sv << util::hex(data.motion_type).to_string_view(); std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size> encrypted_payload; payload = encode_control(session, util::view(plaintext), encrypted_payload); } else if (msg.type == platf::gamepad_feedback_e::set_rgb_led) { control_set_rgb_led_t plaintext; plaintext.header.type = packetTypes[IDX_SET_RGB_LED]; plaintext.header.payloadLength = sizeof(plaintext) - sizeof(control_header_v2); auto &data = msg.data.rgb_led; plaintext.id = util::endian::little(msg.id); plaintext.r = data.r; plaintext.g = data.g; plaintext.b = data.b; BOOST_LOG(verbose) << "RGB: "sv << msg.id << " :: "sv << util::hex(data.r).to_string_view() << util::hex(data.g).to_string_view() << util::hex(data.b).to_string_view(); std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size> encrypted_payload; payload = encode_control(session, util::view(plaintext), encrypted_payload); } else { BOOST_LOG(error) << "Unknown gamepad feedback message type"sv; return -1; } if (session->broadcast_ref->control_server.send(payload, session->control.peer)) { TUPLE_2D(port, addr, platf::from_sockaddr_ex((sockaddr *) &session->control.peer->address.address)); BOOST_LOG(warning) << "Couldn't send gamepad feedback to ["sv << addr << ':' << port << ']'; return -1; } return 0; } int send_hdr_mode(session_t *session, video::hdr_info_t hdr_info) { if (!session->control.peer) { BOOST_LOG(warning) << "Couldn't send HDR mode, still waiting for PING from Moonlight"sv; // Still waiting for PING from Moonlight return -1; } control_hdr_mode_t plaintext {}; plaintext.header.type = packetTypes[IDX_HDR_MODE]; plaintext.header.payloadLength = sizeof(control_hdr_mode_t) - sizeof(control_header_v2); plaintext.enabled = hdr_info->enabled; plaintext.metadata = hdr_info->metadata; std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size> encrypted_payload; auto payload = encode_control(session, util::view(plaintext), encrypted_payload); if (session->broadcast_ref->control_server.send(payload, session->control.peer)) { TUPLE_2D(port, addr, platf::from_sockaddr_ex((sockaddr *) &session->control.peer->address.address)); BOOST_LOG(warning) << "Couldn't send HDR mode to ["sv << addr << ':' << port << ']'; return -1; } BOOST_LOG(debug) << "Sent HDR mode: " << hdr_info->enabled; return 0; } void controlBroadcastThread(control_server_t *server) { server->map(packetTypes[IDX_PERIODIC_PING], [](session_t *session, const std::string_view &payload) { BOOST_LOG(verbose) << "type [IDX_PERIODIC_PING]"sv; }); server->map(packetTypes[IDX_START_A], [&](session_t *session, const std::string_view &payload) { BOOST_LOG(debug) << "type [IDX_START_A]"sv; }); server->map(packetTypes[IDX_START_B], [&](session_t *session, const std::string_view &payload) { BOOST_LOG(debug) << "type [IDX_START_B]"sv; }); server->map(packetTypes[IDX_LOSS_STATS], [&](session_t *session, const std::string_view &payload) { int32_t *stats = (int32_t *) payload.data(); auto count = stats[0]; std::chrono::milliseconds t { stats[1] }; auto lastGoodFrame = stats[3]; BOOST_LOG(verbose) << "type [IDX_LOSS_STATS]"sv << std::endl << "---begin stats---" << std::endl << "loss count since last report [" << count << ']' << std::endl << "time in milli since last report [" << t.count() << ']' << std::endl << "last good frame [" << lastGoodFrame << ']' << std::endl << "---end stats---"; }); server->map(packetTypes[IDX_REQUEST_IDR_FRAME], [&](session_t *session, const std::string_view &payload) { BOOST_LOG(debug) << "type [IDX_REQUEST_IDR_FRAME]"sv; session->video.idr_events->raise(true); }); server->map(packetTypes[IDX_INVALIDATE_REF_FRAMES], [&](session_t *session, const std::string_view &payload) { auto frames = (std::int64_t *) payload.data(); auto firstFrame = frames[0]; auto lastFrame = frames[1]; BOOST_LOG(debug) << "type [IDX_INVALIDATE_REF_FRAMES]"sv << std::endl << "firstFrame [" << firstFrame << ']' << std::endl << "lastFrame [" << lastFrame << ']'; session->video.invalidate_ref_frames_events->raise(std::make_pair(firstFrame, lastFrame)); }); server->map(packetTypes[IDX_INPUT_DATA], [&](session_t *session, const std::string_view &payload) { BOOST_LOG(debug) << "type [IDX_INPUT_DATA]"sv; auto tagged_cipher_length = util::endian::big(*(int32_t *) payload.data()); std::string_view tagged_cipher { payload.data() + sizeof(tagged_cipher_length), (size_t) tagged_cipher_length }; std::vector<uint8_t> plaintext; auto &cipher = session->control.cipher; auto &iv = session->control.legacy_input_enc_iv; if (cipher.decrypt(tagged_cipher, plaintext, &iv)) { // something went wrong :( BOOST_LOG(error) << "Failed to verify tag"sv; session::stop(*session); return; } if (tagged_cipher_length >= 16 + iv.size()) { std::copy(payload.end() - 16, payload.end(), std::begin(iv)); } input::passthrough(session->input, std::move(plaintext)); }); server->map(packetTypes[IDX_ENCRYPTED], [server](session_t *session, const std::string_view &payload) { BOOST_LOG(verbose) << "type [IDX_ENCRYPTED]"sv; auto header = (control_encrypted_p) (payload.data() - 2); auto length = util::endian::little(header->length); auto seq = util::endian::little(header->seq); if (length < (16 + 4 + 4)) { BOOST_LOG(warning) << "Control: Runt packet"sv; return; } auto tagged_cipher_length = length - 4; std::string_view tagged_cipher { (char *) header->payload(), (size_t) tagged_cipher_length }; auto &cipher = session->control.cipher; auto &iv = session->control.incoming_iv; if (session->config.encryptionFlagsEnabled & SS_ENC_CONTROL_V2) { // We use the deterministic IV construction algorithm specified in NIST SP 800-38D // Section 8.2.1. The sequence number is our "invocation" field and the 'CC' in the // high bytes is the "fixed" field. Because each client provides their own unique // key, our values in the fixed field need only uniquely identify each independent // use of the client's key with AES-GCM in our code. // // The sequence number is 32 bits long which allows for 2^32 control stream messages // to be received from each client before the IV repeats. iv.resize(12); std::copy_n((uint8_t *) &seq, sizeof(seq), std::begin(iv)); iv[10] = 'C'; // Client originated iv[11] = 'C'; // Control stream } else { // Nvidia's old style encryption uses a 16-byte IV iv.resize(16); iv[0] = (std::uint8_t) seq; } std::vector<uint8_t> plaintext; if (cipher.decrypt(tagged_cipher, plaintext, &iv)) { // something went wrong :( BOOST_LOG(error) << "Failed to verify tag"sv; session::stop(*session); return; } auto type = *(std::uint16_t *) plaintext.data(); std::string_view next_payload { (char *) plaintext.data() + 4, plaintext.size() - 4 }; if (type == packetTypes[IDX_ENCRYPTED]) { BOOST_LOG(error) << "Bad packet type [IDX_ENCRYPTED] found"sv; session::stop(*session); return; } // IDX_INPUT_DATA callback will attempt to decrypt unencrypted data, therefore we need pass it directly if (type == packetTypes[IDX_INPUT_DATA]) { plaintext.erase(std::begin(plaintext), std::begin(plaintext) + 4); input::passthrough(session->input, std::move(plaintext)); } else { server->call(type, session, next_payload, true); } }); // This thread handles latency-sensitive control messages platf::adjust_thread_priority(platf::thread_priority_e::critical); // Check for both the full shutdown event and the shutdown event for this // broadcast to ensure we can inform connected clients of our graceful // termination when we shut down. auto shutdown_event = mail::man->event<bool>(mail::shutdown); auto broadcast_shutdown_event = mail::man->event<bool>(mail::broadcast_shutdown); while (!shutdown_event->peek() && !broadcast_shutdown_event->peek()) { bool has_session_awaiting_peer = false; { auto lg = server->_sessions.lock(); auto now = std::chrono::steady_clock::now(); KITTY_WHILE_LOOP(auto pos = std::begin(*server->_sessions), pos != std::end(*server->_sessions), { // Don't perform additional session processing if we're shutting down if (shutdown_event->peek() || broadcast_shutdown_event->peek()) { break; } auto session = *pos; if (now > session->pingTimeout) { auto address = session->control.peer ? platf::from_sockaddr((sockaddr *) &session->control.peer->address.address) : session->control.expected_peer_address; BOOST_LOG(info) << address << ": Ping Timeout"sv; session::stop(*session); } if (session->state.load(std::memory_order_acquire) == session::state_e::STOPPING) { pos = server->_sessions->erase(pos); if (session->control.peer) { { auto ptslg = server->_peer_to_session.lock(); server->_peer_to_session->erase(session->control.peer); } enet_peer_disconnect_now(session->control.peer, 0); } session->controlEnd.raise(true); continue; } // Remember if we have a session that's waiting for a peer to connect to the // control stream. This ensures the clients are properly notified even when // the app terminates before they finish connecting. if (!session->control.peer) { has_session_awaiting_peer = true; } else { auto &feedback_queue = session->control.feedback_queue; while (feedback_queue->peek()) { auto feedback_msg = feedback_queue->pop(); send_feedback_msg(session, *feedback_msg); } auto &hdr_queue = session->control.hdr_queue; while (session->control.peer && hdr_queue->peek()) { auto hdr_info = hdr_queue->pop(); send_hdr_mode(session, std::move(hdr_info)); } } ++pos; }) } // Don't break until any pending sessions either expire or connect if (proc::proc.running() == 0 && !has_session_awaiting_peer) { BOOST_LOG(info) << "Process terminated"sv; break; } server->iterate(150ms); } // Let all remaining connections know the server is shutting down // reason: graceful termination std::uint32_t reason = 0x80030023; control_terminate_t plaintext; plaintext.header.type = packetTypes[IDX_TERMINATION]; plaintext.header.payloadLength = sizeof(plaintext.ec); plaintext.ec = util::endian::big<uint32_t>(reason); std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size> encrypted_payload; auto lg = server->_sessions.lock(); for (auto pos = std::begin(*server->_sessions); pos != std::end(*server->_sessions); ++pos) { auto session = *pos; // We may not have gotten far enough to have an ENet connection yet if (session->control.peer) { auto payload = encode_control(session, util::view(plaintext), encrypted_payload); if (server->send(payload, session->control.peer)) { TUPLE_2D(port, addr, platf::from_sockaddr_ex((sockaddr *) &session->control.peer->address.address)); BOOST_LOG(warning) << "Couldn't send termination code to ["sv << addr << ':' << port << ']'; } } session->shutdown_event->raise(true); session->controlEnd.raise(true); } server->flush(); } void recvThread(broadcast_ctx_t &ctx) { std::map<av_session_id_t, message_queue_t> peer_to_video_session; std::map<av_session_id_t, message_queue_t> peer_to_audio_session; auto &video_sock = ctx.video_sock; auto &audio_sock = ctx.audio_sock; auto &message_queue_queue = ctx.message_queue_queue; auto broadcast_shutdown_event = mail::man->event<bool>(mail::broadcast_shutdown); auto &io = ctx.io; udp::endpoint peer; std::array<char, 2048> buf[2]; std::function<void(const boost::system::error_code, size_t)> recv_func[2]; auto populate_peer_to_session = [&]() { while (message_queue_queue->peek()) { auto message_queue_opt = message_queue_queue->pop(); TUPLE_3D_REF(socket_type, session_id, message_queue, *message_queue_opt); switch (socket_type) { case socket_e::video: if (message_queue) { peer_to_video_session.emplace(session_id, message_queue); } else { peer_to_video_session.erase(session_id); } break; case socket_e::audio: if (message_queue) { peer_to_audio_session.emplace(session_id, message_queue); } else { peer_to_audio_session.erase(session_id); } break; } } }; auto recv_func_init = [&](udp::socket &sock, int buf_elem, std::map<av_session_id_t, message_queue_t> &peer_to_session) { recv_func[buf_elem] = [&, buf_elem](const boost::system::error_code &ec, size_t bytes) { auto fg = util::fail_guard([&]() { sock.async_receive_from(asio::buffer(buf[buf_elem]), peer, 0, recv_func[buf_elem]); }); auto type_str = buf_elem ? "AUDIO"sv : "VIDEO"sv; BOOST_LOG(verbose) << "Recv: "sv << peer.address().to_string() << ':' << peer.port() << " :: " << type_str; populate_peer_to_session(); // No data, yet no error if (ec == boost::system::errc::connection_refused || ec == boost::system::errc::connection_reset) { return; } if (ec || !bytes) { BOOST_LOG(error) << "Couldn't receive data from udp socket: "sv << ec.message(); return; } if (bytes == 4) { // For legacy PING packets, find the matching session by address. auto it = peer_to_session.find(peer.address()); if (it != std::end(peer_to_session)) { BOOST_LOG(debug) << "RAISE: "sv << peer.address().to_string() << ':' << peer.port() << " :: " << type_str; it->second->raise(peer, std::string { buf[buf_elem].data(), bytes }); } } else if (bytes >= sizeof(SS_PING)) { auto ping = (PSS_PING) buf[buf_elem].data(); // For new PING packets that include a client identifier, search by payload. auto it = peer_to_session.find(std::string { ping->payload, sizeof(ping->payload) }); if (it != std::end(peer_to_session)) { BOOST_LOG(debug) << "RAISE: "sv << peer.address().to_string() << ':' << peer.port() << " :: " << type_str; it->second->raise(peer, std::string { buf[buf_elem].data(), bytes }); } } }; }; recv_func_init(video_sock, 0, peer_to_video_session); recv_func_init(audio_sock, 1, peer_to_audio_session); video_sock.async_receive_from(asio::buffer(buf[0]), peer, 0, recv_func[0]); audio_sock.async_receive_from(asio::buffer(buf[1]), peer, 0, recv_func[1]); while (!broadcast_shutdown_event->peek()) { io.run(); } } void videoBroadcastThread(udp::socket &sock) { auto shutdown_event = mail::man->event<bool>(mail::broadcast_shutdown); auto packets = mail::man->queue<video::packet_t>(mail::video_packets); auto timebase = boost::posix_time::microsec_clock::universal_time(); // Video traffic is sent on this thread platf::adjust_thread_priority(platf::thread_priority_e::high); logging::min_max_avg_periodic_logger<double> frame_processing_latency_logger(debug, "Frame processing latency", "ms"); logging::time_delta_periodic_logger frame_send_batch_latency_logger(debug, "Network: each send_batch() latency"); logging::time_delta_periodic_logger frame_fec_latency_logger(debug, "Network: each FEC block latency"); logging::time_delta_periodic_logger frame_network_latency_logger(debug, "Network: frame's overall network latency"); crypto::aes_t iv(12); auto timer = platf::create_high_precision_timer(); if (!timer || !*timer) { BOOST_LOG(error) << "Failed to create timer, aborting video broadcast thread"; return; } auto ratecontrol_next_frame_start = std::chrono::steady_clock::now(); while (auto packet = packets->pop()) { if (shutdown_event->peek()) { break; } frame_network_latency_logger.first_point_now(); auto session = (session_t *) packet->channel_data; auto lowseq = session->video.lowseq; std::string_view payload { (char *) packet->data(), packet->data_size() }; std::vector<uint8_t> payload_with_replacements; // Apply replacements on the packet payload before performing any other operations. // We need to know the final frame size to calculate the last packet size, and we // must avoid matching replacements against the frame header or any other non-video // part of the payload. if (packet->is_idr() && packet->replacements) { for (auto &replacement : *packet->replacements) { auto frame_old = replacement.old; auto frame_new = replacement._new; payload_with_replacements = replace(payload, frame_old, frame_new); payload = { (char *) payload_with_replacements.data(), payload_with_replacements.size() }; } } video_short_frame_header_t frame_header = {}; frame_header.headerType = 0x01; // Short header type frame_header.frameType = packet->is_idr() ? 2 : packet->after_ref_frame_invalidation ? 5 : 1; frame_header.lastPayloadLen = (payload.size() + sizeof(frame_header)) % (session->config.packetsize - sizeof(NV_VIDEO_PACKET)); if (frame_header.lastPayloadLen == 0) { frame_header.lastPayloadLen = session->config.packetsize - sizeof(NV_VIDEO_PACKET); } if (packet->frame_timestamp) { auto duration_to_latency = [](const std::chrono::steady_clock::duration &duration) { const auto duration_us = std::chrono::duration_cast<std::chrono::microseconds>(duration).count(); return (uint16_t) std::clamp<decltype(duration_us)>((duration_us + 50) / 100, 0, std::numeric_limits<uint16_t>::max()); }; uint16_t latency = duration_to_latency(std::chrono::steady_clock::now() - *packet->frame_timestamp); frame_header.frame_processing_latency = latency; frame_processing_latency_logger.collect_and_log(latency / 10.); } else { frame_header.frame_processing_latency = 0; } auto fecPercentage = config::stream.fec_percentage; // Insert space for packet headers auto blocksize = session->config.packetsize + MAX_RTP_HEADER_SIZE; auto payload_blocksize = blocksize - sizeof(video_packet_raw_t); auto payload_new = concat_and_insert(sizeof(video_packet_raw_t), payload_blocksize, std::string_view { (char *) &frame_header, sizeof(frame_header) }, payload); payload = std::string_view { (char *) payload_new.data(), payload_new.size() }; // There are 2 bits for FEC block count for a maximum of 4 FEC blocks constexpr auto MAX_FEC_BLOCKS = 4; // The max number of data shards per block is found by solving this system of equations for D: // D = 255 - P // P = D * F // which results in the solution: // D = 255 / (1 + F) // multiplied by 100 since F is the percentage as an integer: // D = (255 * 100) / (100 + F) auto max_data_shards_per_fec_block = (DATA_SHARDS_MAX * 100) / (100 + fecPercentage); // Compute the number of FEC blocks needed for this frame using the block size and max shards auto max_data_per_fec_block = max_data_shards_per_fec_block * blocksize; auto fec_blocks_needed = (payload.size() + (max_data_per_fec_block - 1)) / max_data_per_fec_block; // If the number of FEC blocks needed exceeds the protocol limit, turn off FEC for this frame. // For normal FEC percentages, this should only happen for enormous frames (over 800 packets at 20%). if (fec_blocks_needed > MAX_FEC_BLOCKS) { BOOST_LOG(warning) << "Skipping FEC for abnormally large encoded frame (needed "sv << fec_blocks_needed << " FEC blocks)"sv; fecPercentage = 0; fec_blocks_needed = MAX_FEC_BLOCKS; } std::array<std::string_view, MAX_FEC_BLOCKS> fec_blocks; decltype(fec_blocks)::iterator fec_blocks_begin = std::begin(fec_blocks), fec_blocks_end = std::begin(fec_blocks) + fec_blocks_needed; BOOST_LOG(verbose) << "Generating "sv << fec_blocks_needed << " FEC blocks"sv; // Align individual FEC blocks to blocksize auto unaligned_size = payload.size() / fec_blocks_needed; auto aligned_size = ((unaligned_size + (blocksize - 1)) / blocksize) * blocksize; // If we exceed the 10-bit FEC packet index (which means our frame exceeded 4096 packets), // the frame will be unrecoverable. Log an error for this case. if (aligned_size / blocksize >= 1024) { BOOST_LOG(error) << "Encoder produced a frame too large to send! Is the encoder broken? (needed "sv << (aligned_size / blocksize) << " packets)"sv; } // Split the data into aligned FEC blocks for (int x = 0; x < fec_blocks_needed; ++x) { if (x == fec_blocks_needed - 1) { // The last block must extend to the end of the payload fec_blocks[x] = payload.substr(x * aligned_size); } else { // Earlier blocks just extend to the next block offset fec_blocks[x] = payload.substr(x * aligned_size, aligned_size); } } try { // Use around 80% of 1Gbps 1Gbps percent ms packet byte size_t ratecontrol_packets_in_1ms = std::giga::num * 80 / 100 / 1000 / blocksize / 8; // Send less than 64K in a single batch. // On Windows, batches above 64K seem to bypass SO_SNDBUF regardless of its size, // appear in "Other I/O" and begin waiting for interrupts. // This gives inconsistent performance so we'd rather avoid it. size_t send_batch_size = 64 * 1024 / blocksize; // Also don't exceed 64 packets, which can happen when Moonlight requests // unusually small packet size. // Generic Segmentation Offload on Linux can't do more than 64. send_batch_size = std::min<size_t>(64, send_batch_size); // Don't ignore the last ratecontrol group of the previous frame auto ratecontrol_frame_start = std::max(ratecontrol_next_frame_start, std::chrono::steady_clock::now()); size_t ratecontrol_frame_packets_sent = 0; size_t ratecontrol_group_packets_sent = 0; auto blockIndex = 0; std::for_each(fec_blocks_begin, fec_blocks_end, [&](std::string_view &current_payload) { auto packets = (current_payload.size() + (blocksize - 1)) / blocksize; for (int x = 0; x < packets; ++x) { auto *inspect = (video_packet_raw_t *) &current_payload[x * blocksize]; inspect->packet.frameIndex = packet->frame_index(); inspect->packet.streamPacketIndex = ((uint32_t) lowseq + x) << 8; // Match multiFecFlags with Moonlight inspect->packet.multiFecFlags = 0x10; inspect->packet.multiFecBlocks = (blockIndex << 4) | ((fec_blocks_needed - 1) << 6); inspect->packet.flags = FLAG_CONTAINS_PIC_DATA; if (x == 0) { inspect->packet.flags |= FLAG_SOF; } if (x == packets - 1) { inspect->packet.flags |= FLAG_EOF; } } frame_fec_latency_logger.first_point_now(); // If video encryption is enabled, we allocate space for the encryption header before each shard auto shards = fec::encode(current_payload, blocksize, fecPercentage, session->config.minRequiredFecPackets, session->video.cipher ? sizeof(video_packet_enc_prefix_t) : 0); frame_fec_latency_logger.second_point_now_and_log(); auto peer_address = session->video.peer.address(); auto batch_info = platf::batched_send_info_t { shards.headers.begin(), shards.prefixsize, shards.payload_buffers, shards.blocksize, 0, 0, (uintptr_t) sock.native_handle(), peer_address, session->video.peer.port(), session->localAddress, }; size_t next_shard_to_send = 0; // set FEC info now that we know for sure what our percentage will be for this frame for (auto x = 0; x < shards.size(); ++x) { auto *inspect = (video_packet_raw_t *) shards.data(x); // RTP video timestamps use a 90 KHz clock auto now = boost::posix_time::microsec_clock::universal_time(); auto timestamp = (now - timebase).total_microseconds() / (1000 / 90); inspect->packet.fecInfo = (x << 12 | shards.data_shards << 22 | shards.percentage << 4); inspect->rtp.header = 0x80 | FLAG_EXTENSION; inspect->rtp.sequenceNumber = util::endian::big<uint16_t>(lowseq + x); inspect->rtp.timestamp = util::endian::big<uint32_t>(timestamp); inspect->packet.multiFecBlocks = (blockIndex << 4) | ((fec_blocks_needed - 1) << 6); inspect->packet.frameIndex = packet->frame_index(); // Encrypt this shard if video encryption is enabled if (session->video.cipher) { // We use the deterministic IV construction algorithm specified in NIST SP 800-38D // Section 8.2.1. The sequence number is our "invocation" field and the 'V' in the // high bytes is the "fixed" field. Because each client provides their own unique // key, our values in the fixed field need only uniquely identify each independent // use of the client's key with AES-GCM in our code. // // The IV counter is 64 bits long which allows for 2^64 encrypted video packets // to be sent to each client before the IV repeats. std::copy_n((uint8_t *) &session->video.gcm_iv_counter, sizeof(session->video.gcm_iv_counter), std::begin(iv)); iv[11] = 'V'; // Video stream session->video.gcm_iv_counter++; // Encrypt the target buffer in place auto *prefix = (video_packet_enc_prefix_t *) shards.prefix(x); prefix->frameNumber = packet->frame_index(); std::copy(std::begin(iv), std::end(iv), prefix->iv); session->video.cipher->encrypt(std::string_view { (char *) inspect, (size_t) blocksize }, prefix->tag, (uint8_t *) inspect, &iv); } if (x - next_shard_to_send + 1 >= send_batch_size || x + 1 == shards.size()) { // Do pacing within the frame. // Also trigger pacing before the first send_batch() of the frame // to account for the last send_batch() of the previous frame. if (ratecontrol_group_packets_sent >= ratecontrol_packets_in_1ms || ratecontrol_frame_packets_sent == 0) { auto due = ratecontrol_frame_start + std::chrono::duration_cast<std::chrono::nanoseconds>(1ms) * ratecontrol_frame_packets_sent / ratecontrol_packets_in_1ms; auto now = std::chrono::steady_clock::now(); if (now < due) { timer->sleep_for(due - now); } ratecontrol_group_packets_sent = 0; } size_t current_batch_size = x - next_shard_to_send + 1; batch_info.block_offset = next_shard_to_send; batch_info.block_count = current_batch_size; frame_send_batch_latency_logger.first_point_now(); // Use a batched send if it's supported on this platform if (!platf::send_batch(batch_info)) { // Batched send is not available, so send each packet individually BOOST_LOG(verbose) << "Falling back to unbatched send"sv; for (auto y = 0; y < current_batch_size; y++) { auto send_info = platf::send_info_t { shards.prefix(next_shard_to_send + y), shards.prefixsize, shards.data(next_shard_to_send + y), shards.blocksize, (uintptr_t) sock.native_handle(), peer_address, session->video.peer.port(), session->localAddress, }; platf::send(send_info); } } frame_send_batch_latency_logger.second_point_now_and_log(); ratecontrol_group_packets_sent += current_batch_size; ratecontrol_frame_packets_sent += current_batch_size; next_shard_to_send = x + 1; } } // remember this in case the next frame comes immediately ratecontrol_next_frame_start = ratecontrol_frame_start + std::chrono::duration_cast<std::chrono::nanoseconds>(1ms) * ratecontrol_frame_packets_sent / ratecontrol_packets_in_1ms; frame_network_latency_logger.second_point_now_and_log(); if (packet->is_idr()) { BOOST_LOG(verbose) << "Key Frame ["sv << packet->frame_index() << "] :: send ["sv << shards.size() << "] shards..."sv; } else { BOOST_LOG(verbose) << "Frame ["sv << packet->frame_index() << "] :: send ["sv << shards.size() << "] shards..."sv << std::endl; } ++blockIndex; lowseq += shards.size(); }); session->video.lowseq = lowseq; } catch (const std::exception &e) { BOOST_LOG(error) << "Broadcast video failed "sv << e.what(); std::this_thread::sleep_for(100ms); } } shutdown_event->raise(true); } void audioBroadcastThread(udp::socket &sock) { auto shutdown_event = mail::man->event<bool>(mail::broadcast_shutdown); auto packets = mail::man->queue<audio::packet_t>(mail::audio_packets); audio_packet_t audio_packet; fec::rs_t rs { reed_solomon_new(RTPA_DATA_SHARDS, RTPA_FEC_SHARDS) }; crypto::aes_t iv(16); // For unknown reasons, the RS parity matrix computed by our RS implementation // doesn't match the one Nvidia uses for audio data. I'm not exactly sure why, // but we can simply replace it with the matrix generated by OpenFEC which // works correctly. This is possible because the data and FEC shard count is // constant and known in advance. const unsigned char parity[] = { 0x77, 0x40, 0x38, 0x0e, 0xc7, 0xa7, 0x0d, 0x6c }; memcpy(rs.get()->p, parity, sizeof(parity)); audio_packet.rtp.header = 0x80; audio_packet.rtp.packetType = 97; audio_packet.rtp.ssrc = 0; // Audio traffic is sent on this thread platf::adjust_thread_priority(platf::thread_priority_e::high); while (auto packet = packets->pop()) { if (shutdown_event->peek()) { break; } TUPLE_2D_REF(channel_data, packet_data, *packet); auto session = (session_t *) channel_data; auto sequenceNumber = session->audio.sequenceNumber; auto timestamp = session->audio.timestamp; *(std::uint32_t *) iv.data() = util::endian::big<std::uint32_t>(session->audio.avRiKeyId + sequenceNumber); auto &shards_p = session->audio.shards_p; auto bytes = encode_audio(session->config.encryptionFlagsEnabled & SS_ENC_AUDIO, packet_data, shards_p[sequenceNumber % RTPA_DATA_SHARDS], iv, session->audio.cipher); if (bytes < 0) { BOOST_LOG(error) << "Couldn't encode audio packet"sv; break; } audio_packet.rtp.sequenceNumber = util::endian::big(sequenceNumber); audio_packet.rtp.timestamp = util::endian::big(timestamp); session->audio.sequenceNumber++; session->audio.timestamp += session->config.audio.packetDuration; auto peer_address = session->audio.peer.address(); try { auto send_info = platf::send_info_t { (const char *) &audio_packet, sizeof(audio_packet), (const char *) shards_p[sequenceNumber % RTPA_DATA_SHARDS], (size_t) bytes, (uintptr_t) sock.native_handle(), peer_address, session->audio.peer.port(), session->localAddress, }; platf::send(send_info); BOOST_LOG(verbose) << "Audio ["sv << sequenceNumber << "] :: send..."sv; auto &fec_packet = session->audio.fec_packet; // initialize the FEC header at the beginning of the FEC block if (sequenceNumber % RTPA_DATA_SHARDS == 0) { fec_packet.fecHeader.baseSequenceNumber = util::endian::big(sequenceNumber); fec_packet.fecHeader.baseTimestamp = util::endian::big(timestamp); } // generate parity shards at the end of the FEC block if ((sequenceNumber + 1) % RTPA_DATA_SHARDS == 0) { reed_solomon_encode(rs.get(), shards_p.begin(), RTPA_TOTAL_SHARDS, bytes); for (auto x = 0; x < RTPA_FEC_SHARDS; ++x) { fec_packet.rtp.sequenceNumber = util::endian::big<std::uint16_t>(sequenceNumber + x + 1); fec_packet.fecHeader.fecShardIndex = x; auto send_info = platf::send_info_t { (const char *) &fec_packet, sizeof(fec_packet), (const char *) shards_p[RTPA_DATA_SHARDS + x], (size_t) bytes, (uintptr_t) sock.native_handle(), peer_address, session->audio.peer.port(), session->localAddress, }; platf::send(send_info); BOOST_LOG(verbose) << "Audio FEC ["sv << (sequenceNumber & ~(RTPA_DATA_SHARDS - 1)) << ' ' << x << "] :: send..."sv; } } } catch (const std::exception &e) { BOOST_LOG(error) << "Broadcast audio failed "sv << e.what(); std::this_thread::sleep_for(100ms); } } shutdown_event->raise(true); } int start_broadcast(broadcast_ctx_t &ctx) { auto address_family = net::af_from_enum_string(config::sunshine.address_family); auto protocol = address_family == net::IPV4 ? udp::v4() : udp::v6(); auto control_port = net::map_port(CONTROL_PORT); auto video_port = net::map_port(VIDEO_STREAM_PORT); auto audio_port = net::map_port(AUDIO_STREAM_PORT); if (ctx.control_server.bind(address_family, control_port)) { BOOST_LOG(error) << "Couldn't bind Control server to port ["sv << control_port << "], likely another process already bound to the port"sv; return -1; } boost::system::error_code ec; ctx.video_sock.open(protocol, ec); if (ec) { BOOST_LOG(fatal) << "Couldn't open socket for Video server: "sv << ec.message(); return -1; } // Set video socket send buffer size (SO_SENDBUF) to 1MB try { ctx.video_sock.set_option(boost::asio::socket_base::send_buffer_size(1024 * 1024)); } catch (...) { BOOST_LOG(error) << "Failed to set video socket send buffer size (SO_SENDBUF)"; } ctx.video_sock.bind(udp::endpoint(protocol, video_port), ec); if (ec) { BOOST_LOG(fatal) << "Couldn't bind Video server to port ["sv << video_port << "]: "sv << ec.message(); return -1; } ctx.audio_sock.open(protocol, ec); if (ec) { BOOST_LOG(fatal) << "Couldn't open socket for Audio server: "sv << ec.message(); return -1; } ctx.audio_sock.bind(udp::endpoint(protocol, audio_port), ec); if (ec) { BOOST_LOG(fatal) << "Couldn't bind Audio server to port ["sv << audio_port << "]: "sv << ec.message(); return -1; } ctx.message_queue_queue = std::make_shared<message_queue_queue_t::element_type>(30); ctx.video_thread = std::thread { videoBroadcastThread, std::ref(ctx.video_sock) }; ctx.audio_thread = std::thread { audioBroadcastThread, std::ref(ctx.audio_sock) }; ctx.control_thread = std::thread { controlBroadcastThread, &ctx.control_server }; ctx.recv_thread = std::thread { recvThread, std::ref(ctx) }; return 0; } void end_broadcast(broadcast_ctx_t &ctx) { auto broadcast_shutdown_event = mail::man->event<bool>(mail::broadcast_shutdown); broadcast_shutdown_event->raise(true); auto video_packets = mail::man->queue<video::packet_t>(mail::video_packets); auto audio_packets = mail::man->queue<audio::packet_t>(mail::audio_packets); // Minimize delay stopping video/audio threads video_packets->stop(); audio_packets->stop(); ctx.message_queue_queue->stop(); ctx.io.stop(); ctx.video_sock.close(); ctx.audio_sock.close(); video_packets.reset(); audio_packets.reset(); BOOST_LOG(debug) << "Waiting for main listening thread to end..."sv; ctx.recv_thread.join(); BOOST_LOG(debug) << "Waiting for main video thread to end..."sv; ctx.video_thread.join(); BOOST_LOG(debug) << "Waiting for main audio thread to end..."sv; ctx.audio_thread.join(); BOOST_LOG(debug) << "Waiting for main control thread to end..."sv; ctx.control_thread.join(); BOOST_LOG(debug) << "All broadcasting threads ended"sv; broadcast_shutdown_event->reset(); } int recv_ping(session_t *session, decltype(broadcast)::ptr_t ref, socket_e type, std::string_view expected_payload, udp::endpoint &peer, std::chrono::milliseconds timeout) { auto messages = std::make_shared<message_queue_t::element_type>(30); av_session_id_t session_id = std::string { expected_payload }; // Only allow matches on the peer address for legacy clients if (!(session->config.mlFeatureFlags & ML_FF_SESSION_ID_V1)) { ref->message_queue_queue->raise(type, peer.address(), messages); } ref->message_queue_queue->raise(type, session_id, messages); auto fg = util::fail_guard([&]() { messages->stop(); // remove message queue from session if (!(session->config.mlFeatureFlags & ML_FF_SESSION_ID_V1)) { ref->message_queue_queue->raise(type, peer.address(), nullptr); } ref->message_queue_queue->raise(type, session_id, nullptr); }); auto start_time = std::chrono::steady_clock::now(); auto current_time = start_time; while (current_time - start_time < config::stream.ping_timeout) { auto delta_time = current_time - start_time; auto msg_opt = messages->pop(config::stream.ping_timeout - delta_time); if (!msg_opt) { break; } TUPLE_2D_REF(recv_peer, msg, *msg_opt); if (msg.find(expected_payload) != std::string::npos) { // Match the new PING payload format BOOST_LOG(debug) << "Received ping [v2] from "sv << recv_peer.address() << ':' << recv_peer.port() << " ["sv << util::hex_vec(msg) << ']'; } else if (!(session->config.mlFeatureFlags & ML_FF_SESSION_ID_V1) && msg == "PING"sv) { // Match the legacy fixed PING payload only if the new type is not supported BOOST_LOG(debug) << "Received ping [v1] from "sv << recv_peer.address() << ':' << recv_peer.port() << " ["sv << util::hex_vec(msg) << ']'; } else { BOOST_LOG(debug) << "Received non-ping from "sv << recv_peer.address() << ':' << recv_peer.port() << " ["sv << util::hex_vec(msg) << ']'; current_time = std::chrono::steady_clock::now(); continue; } // Update connection details. peer = recv_peer; return 0; } BOOST_LOG(error) << "Initial Ping Timeout"sv; return -1; } void videoThread(session_t *session) { auto fg = util::fail_guard([&]() { session::stop(*session); }); while_starting_do_nothing(session->state); auto ref = broadcast.ref(); auto error = recv_ping(session, ref, socket_e::video, session->video.ping_payload, session->video.peer, config::stream.ping_timeout); if (error < 0) { return; } // Enable local prioritization and QoS tagging on video traffic if requested by the client auto address = session->video.peer.address(); session->video.qos = platf::enable_socket_qos(ref->video_sock.native_handle(), address, session->video.peer.port(), platf::qos_data_type_e::video, session->config.videoQosType != 0); BOOST_LOG(debug) << "Start capturing Video"sv; video::capture(session->mail, session->config.monitor, session); } void audioThread(session_t *session) { auto fg = util::fail_guard([&]() { session::stop(*session); }); while_starting_do_nothing(session->state); auto ref = broadcast.ref(); auto error = recv_ping(session, ref, socket_e::audio, session->audio.ping_payload, session->audio.peer, config::stream.ping_timeout); if (error < 0) { return; } // Enable local prioritization and QoS tagging on audio traffic if requested by the client auto address = session->audio.peer.address(); session->audio.qos = platf::enable_socket_qos(ref->audio_sock.native_handle(), address, session->audio.peer.port(), platf::qos_data_type_e::audio, session->config.audioQosType != 0); BOOST_LOG(debug) << "Start capturing Audio"sv; audio::capture(session->mail, session->config.audio, session); } namespace session { std::atomic_uint running_sessions; state_e state(session_t &session) { return session.state.load(std::memory_order_relaxed); } void stop(session_t &session) { while_starting_do_nothing(session.state); auto expected = state_e::RUNNING; auto already_stopping = !session.state.compare_exchange_strong(expected, state_e::STOPPING); if (already_stopping) { return; } session.shutdown_event->raise(true); } void join(session_t &session) { // Current Nvidia drivers have a bug where NVENC can deadlock the encoder thread with hardware-accelerated // GPU scheduling enabled. If this happens, we will terminate ourselves and the service can restart. // The alternative is that Sunshine can never start another session until it's manually restarted. auto task = []() { BOOST_LOG(fatal) << "Hang detected! Session failed to terminate in 10 seconds."sv; logging::log_flush(); lifetime::debug_trap(); }; auto force_kill = task_pool.pushDelayed(task, 10s).task_id; auto fg = util::fail_guard([&force_kill]() { // Cancel the kill task if we manage to return from this function task_pool.cancel(force_kill); }); BOOST_LOG(debug) << "Waiting for video to end..."sv; session.videoThread.join(); BOOST_LOG(debug) << "Waiting for audio to end..."sv; session.audioThread.join(); BOOST_LOG(debug) << "Waiting for control to end..."sv; session.controlEnd.view(); // Reset input on session stop to avoid stuck repeated keys BOOST_LOG(debug) << "Resetting Input..."sv; input::reset(session.input); // If this is the last session, invoke the platform callbacks if (--running_sessions == 0) { #if defined SUNSHINE_TRAY && SUNSHINE_TRAY >= 1 if (proc::proc.running()) { system_tray::update_tray_pausing(proc::proc.get_last_run_app_name()); } #endif platf::streaming_will_stop(); } BOOST_LOG(debug) << "Session ended"sv; } int start(session_t &session, const std::string &addr_string) { session.input = input::alloc(session.mail); session.broadcast_ref = broadcast.ref(); if (!session.broadcast_ref) { return -1; } session.control.expected_peer_address = addr_string; BOOST_LOG(debug) << "Expecting incoming session connections from "sv << addr_string; // Insert this session into the session list { auto lg = session.broadcast_ref->control_server._sessions.lock(); session.broadcast_ref->control_server._sessions->push_back(&session); } auto addr = boost::asio::ip::make_address(addr_string); session.video.peer.address(addr); session.video.peer.port(0); session.audio.peer.address(addr); session.audio.peer.port(0); session.pingTimeout = std::chrono::steady_clock::now() + config::stream.ping_timeout; session.audioThread = std::thread { audioThread, &session }; session.videoThread = std::thread { videoThread, &session }; session.state.store(state_e::RUNNING, std::memory_order_relaxed); // If this is the first session, invoke the platform callbacks if (++running_sessions == 1) { platf::streaming_will_start(); #if defined SUNSHINE_TRAY && SUNSHINE_TRAY >= 1 system_tray::update_tray_playing(proc::proc.get_last_run_app_name()); #endif } return 0; } std::shared_ptr<session_t> alloc(config_t &config, rtsp_stream::launch_session_t &launch_session) { auto session = std::make_shared<session_t>(); auto mail = std::make_shared<safe::mail_raw_t>(); session->shutdown_event = mail->event<bool>(mail::shutdown); session->launch_session_id = launch_session.id; session->config = config; session->control.connect_data = launch_session.control_connect_data; session->control.feedback_queue = mail->queue<platf::gamepad_feedback_msg_t>(mail::gamepad_feedback); session->control.hdr_queue = mail->event<video::hdr_info_t>(mail::hdr); session->control.legacy_input_enc_iv = launch_session.iv; session->control.cipher = crypto::cipher::gcm_t { launch_session.gcm_key, false }; session->video.idr_events = mail->event<bool>(mail::idr); session->video.invalidate_ref_frames_events = mail->event<std::pair<int64_t, int64_t>>(mail::invalidate_ref_frames); session->video.lowseq = 0; session->video.ping_payload = launch_session.av_ping_payload; if (config.encryptionFlagsEnabled & SS_ENC_VIDEO) { BOOST_LOG(info) << "Video encryption enabled"sv; session->video.cipher = crypto::cipher::gcm_t { launch_session.gcm_key, false }; session->video.gcm_iv_counter = 0; } constexpr auto max_block_size = crypto::cipher::round_to_pkcs7_padded(2048); util::buffer_t<char> shards { RTPA_TOTAL_SHARDS * max_block_size }; util::buffer_t<uint8_t *> shards_p { RTPA_TOTAL_SHARDS }; for (auto x = 0; x < RTPA_TOTAL_SHARDS; ++x) { shards_p[x] = (uint8_t *) &shards[x * max_block_size]; } // Audio FEC spans multiple audio packets, // therefore its session specific session->audio.shards = std::move(shards); session->audio.shards_p = std::move(shards_p); session->audio.fec_packet.rtp.header = 0x80; session->audio.fec_packet.rtp.packetType = 127; session->audio.fec_packet.rtp.timestamp = 0; session->audio.fec_packet.rtp.ssrc = 0; session->audio.fec_packet.fecHeader.payloadType = 97; session->audio.fec_packet.fecHeader.ssrc = 0; session->audio.cipher = crypto::cipher::cbc_t { launch_session.gcm_key, true }; session->audio.ping_payload = launch_session.av_ping_payload; session->audio.avRiKeyId = util::endian::big(*(std::uint32_t *) launch_session.iv.data()); session->audio.sequenceNumber = 0; session->audio.timestamp = 0; session->control.peer = nullptr; session->state.store(state_e::STOPPED, std::memory_order_relaxed); session->mail = std::move(mail); return session; } } // namespace session } // namespace stream
76,868
C++
.cpp
1,652
38.986077
183
0.629818
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,978
rtsp.cpp
LizardByte_Sunshine/src/rtsp.cpp
/** * @file src/rtsp.cpp * @brief Definitions for RTSP streaming. */ #define BOOST_BIND_GLOBAL_PLACEHOLDERS extern "C" { #include <moonlight-common-c/src/Limelight-internal.h> #include <moonlight-common-c/src/Rtsp.h> } #include <array> #include <cctype> #include <utility> #include <boost/asio.hpp> #include <boost/bind.hpp> #include "config.h" #include "globals.h" #include "input.h" #include "logging.h" #include "network.h" #include "rtsp.h" #include "stream.h" #include "sync.h" #include "video.h" #include <set> #include <unordered_map> namespace asio = boost::asio; using asio::ip::tcp; using asio::ip::udp; using namespace std::literals; namespace rtsp_stream { void free_msg(PRTSP_MESSAGE msg) { freeMessage(msg); delete msg; } #pragma pack(push, 1) struct encrypted_rtsp_header_t { // We set the MSB in encrypted RTSP messages to allow format-agnostic // parsing code to be able to tell encrypted from plaintext messages. static constexpr std::uint32_t ENCRYPTED_MESSAGE_TYPE_BIT = 0x80000000; uint8_t * payload() { return (uint8_t *) (this + 1); } std::uint32_t payload_length() { return util::endian::big<std::uint32_t>(typeAndLength) & ~ENCRYPTED_MESSAGE_TYPE_BIT; } bool is_encrypted() { return !!(util::endian::big<std::uint32_t>(typeAndLength) & ENCRYPTED_MESSAGE_TYPE_BIT); } // This field is the length of the payload + ENCRYPTED_MESSAGE_TYPE_BIT in big-endian std::uint32_t typeAndLength; // This field is the number used to initialize the bottom 4 bytes of the AES IV in big-endian std::uint32_t sequenceNumber; // This field is the AES GCM authentication tag std::uint8_t tag[16]; }; #pragma pack(pop) class rtsp_server_t; using msg_t = util::safe_ptr<RTSP_MESSAGE, free_msg>; using cmd_func_t = std::function<void(rtsp_server_t *server, tcp::socket &, launch_session_t &, msg_t &&)>; void print_msg(PRTSP_MESSAGE msg); void cmd_not_found(tcp::socket &sock, launch_session_t &, msg_t &&req); void respond(tcp::socket &sock, launch_session_t &session, POPTION_ITEM options, int statuscode, const char *status_msg, int seqn, const std::string_view &payload); class socket_t: public std::enable_shared_from_this<socket_t> { public: socket_t(boost::asio::io_service &ios, std::function<void(tcp::socket &sock, launch_session_t &, msg_t &&)> &&handle_data_fn): handle_data_fn { std::move(handle_data_fn) }, sock { ios } {} /** * @brief Queue an asynchronous read to begin the next message. */ void read() { if (begin == std::end(msg_buf) || (session->rtsp_cipher && begin + sizeof(encrypted_rtsp_header_t) >= std::end(msg_buf))) { BOOST_LOG(error) << "RTSP: read(): Exceeded maximum rtsp packet size: "sv << msg_buf.size(); respond(sock, *session, nullptr, 400, "BAD REQUEST", 0, {}); boost::system::error_code ec; sock.close(ec); return; } if (session->rtsp_cipher) { // For encrypted RTSP, we will read the the entire header first boost::asio::async_read(sock, boost::asio::buffer(begin, sizeof(encrypted_rtsp_header_t)), boost::bind( &socket_t::handle_read_encrypted_header, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { sock.async_read_some( boost::asio::buffer(begin, (std::size_t)(std::end(msg_buf) - begin)), boost::bind( &socket_t::handle_read_plaintext, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } /** * @brief Handle the initial read of the header of an encrypted message. * @param socket The socket the message was received on. * @param ec The error code of the read operation. * @param bytes The number of bytes read. */ static void handle_read_encrypted_header(std::shared_ptr<socket_t> &socket, const boost::system::error_code &ec, std::size_t bytes) { BOOST_LOG(debug) << "handle_read_encrypted_header(): Handle read of size: "sv << bytes << " bytes"sv; auto sock_close = util::fail_guard([&socket]() { boost::system::error_code ec; socket->sock.close(ec); if (ec) { BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Couldn't close tcp socket: "sv << ec.message(); } }); if (ec || bytes < sizeof(encrypted_rtsp_header_t)) { BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Couldn't read from tcp socket: "sv << ec.message(); respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); return; } auto header = (encrypted_rtsp_header_t *) socket->begin; if (!header->is_encrypted()) { BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Rejecting unencrypted RTSP message"sv; respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); return; } auto payload_length = header->payload_length(); // Check if we have enough space to read this message if (socket->begin + sizeof(*header) + payload_length >= std::end(socket->msg_buf)) { BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Exceeded maximum rtsp packet size: "sv << socket->msg_buf.size(); respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); return; } sock_close.disable(); // Read the remainder of the header and full encrypted payload boost::asio::async_read(socket->sock, boost::asio::buffer(socket->begin + bytes, payload_length), boost::bind( &socket_t::handle_read_encrypted_message, socket->shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } /** * @brief Handle the final read of the content of an encrypted message. * @param socket The socket the message was received on. * @param ec The error code of the read operation. * @param bytes The number of bytes read. */ static void handle_read_encrypted_message(std::shared_ptr<socket_t> &socket, const boost::system::error_code &ec, std::size_t bytes) { BOOST_LOG(debug) << "handle_read_encrypted(): Handle read of size: "sv << bytes << " bytes"sv; auto sock_close = util::fail_guard([&socket]() { boost::system::error_code ec; socket->sock.close(ec); if (ec) { BOOST_LOG(error) << "RTSP: handle_read_encrypted_message(): Couldn't close tcp socket: "sv << ec.message(); } }); auto header = (encrypted_rtsp_header_t *) socket->begin; auto payload_length = header->payload_length(); auto seq = util::endian::big<std::uint32_t>(header->sequenceNumber); if (ec || bytes < payload_length) { BOOST_LOG(error) << "RTSP: handle_read_encrypted(): Couldn't read from tcp socket: "sv << ec.message(); respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); return; } // We use the deterministic IV construction algorithm specified in NIST SP 800-38D // Section 8.2.1. The sequence number is our "invocation" field and the 'RC' in the // high bytes is the "fixed" field. Because each client provides their own unique // key, our values in the fixed field need only uniquely identify each independent // use of the client's key with AES-GCM in our code. // // The sequence number is 32 bits long which allows for 2^32 RTSP messages to be // received from each client before the IV repeats. crypto::aes_t iv(12); std::copy_n((uint8_t *) &seq, sizeof(seq), std::begin(iv)); iv[10] = 'C'; // Client originated iv[11] = 'R'; // RTSP std::vector<uint8_t> plaintext; if (socket->session->rtsp_cipher->decrypt(std::string_view { (const char *) header->tag, sizeof(header->tag) + bytes }, plaintext, &iv)) { BOOST_LOG(error) << "Failed to verify RTSP message tag"sv; respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); return; } msg_t req { new msg_t::element_type {} }; if (auto status = parseRtspMessage(req.get(), (char *) plaintext.data(), plaintext.size())) { BOOST_LOG(error) << "Malformed RTSP message: ["sv << status << ']'; respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); return; } sock_close.disable(); print_msg(req.get()); socket->handle_data(std::move(req)); } /** * @brief Queue an asynchronous read of the payload portion of a plaintext message. */ void read_plaintext_payload() { if (begin == std::end(msg_buf)) { BOOST_LOG(error) << "RTSP: read_plaintext_payload(): Exceeded maximum rtsp packet size: "sv << msg_buf.size(); respond(sock, *session, nullptr, 400, "BAD REQUEST", 0, {}); boost::system::error_code ec; sock.close(ec); return; } sock.async_read_some( boost::asio::buffer(begin, (std::size_t)(std::end(msg_buf) - begin)), boost::bind( &socket_t::handle_plaintext_payload, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } /** * @brief Handle the read of the payload portion of a plaintext message. * @param socket The socket the message was received on. * @param ec The error code of the read operation. * @param bytes The number of bytes read. */ static void handle_plaintext_payload(std::shared_ptr<socket_t> &socket, const boost::system::error_code &ec, std::size_t bytes) { BOOST_LOG(debug) << "handle_plaintext_payload(): Handle read of size: "sv << bytes << " bytes"sv; auto sock_close = util::fail_guard([&socket]() { boost::system::error_code ec; socket->sock.close(ec); if (ec) { BOOST_LOG(error) << "RTSP: handle_plaintext_payload(): Couldn't close tcp socket: "sv << ec.message(); } }); if (ec) { BOOST_LOG(error) << "RTSP: handle_plaintext_payload(): Couldn't read from tcp socket: "sv << ec.message(); return; } auto end = socket->begin + bytes; msg_t req { new msg_t::element_type {} }; if (auto status = parseRtspMessage(req.get(), socket->msg_buf.data(), (std::size_t)(end - socket->msg_buf.data()))) { BOOST_LOG(error) << "Malformed RTSP message: ["sv << status << ']'; respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); return; } sock_close.disable(); auto fg = util::fail_guard([&socket]() { socket->read_plaintext_payload(); }); auto content_length = 0; for (auto option = req->options; option != nullptr; option = option->next) { if ("Content-length"sv == option->option) { BOOST_LOG(debug) << "Found Content-Length: "sv << option->content << " bytes"sv; // If content_length > bytes read, then we need to store current data read, // to be appended by the next read. std::string_view content { option->content }; auto begin = std::find_if(std::begin(content), std::end(content), [](auto ch) { return (bool) std::isdigit(ch); }); content_length = util::from_chars(begin, std::end(content)); break; } } if (end - socket->crlf >= content_length) { if (end - socket->crlf > content_length) { BOOST_LOG(warning) << "(end - socket->crlf) > content_length -- "sv << (std::size_t)(end - socket->crlf) << " > "sv << content_length; } fg.disable(); print_msg(req.get()); socket->handle_data(std::move(req)); } socket->begin = end; } /** * @brief Handle the read of the header portion of a plaintext message. * @param socket The socket the message was received on. * @param ec The error code of the read operation. * @param bytes The number of bytes read. */ static void handle_read_plaintext(std::shared_ptr<socket_t> &socket, const boost::system::error_code &ec, std::size_t bytes) { BOOST_LOG(debug) << "handle_read_plaintext(): Handle read of size: "sv << bytes << " bytes"sv; if (ec) { BOOST_LOG(error) << "RTSP: handle_read_plaintext(): Couldn't read from tcp socket: "sv << ec.message(); boost::system::error_code ec; socket->sock.close(ec); if (ec) { BOOST_LOG(error) << "RTSP: handle_read_plaintext(): Couldn't close tcp socket: "sv << ec.message(); } return; } auto fg = util::fail_guard([&socket]() { socket->read(); }); auto begin = std::max(socket->begin - 4, socket->begin); auto buf_size = bytes + (begin - socket->begin); auto end = begin + buf_size; constexpr auto needle = "\r\n\r\n"sv; auto it = std::search(begin, begin + buf_size, std::begin(needle), std::end(needle)); if (it == end) { socket->begin = end; return; } // Emulate read completion for payload data socket->begin = it + needle.size(); socket->crlf = socket->begin; buf_size = end - socket->begin; fg.disable(); handle_plaintext_payload(socket, ec, buf_size); } void handle_data(msg_t &&req) { handle_data_fn(sock, *session, std::move(req)); } std::function<void(tcp::socket &sock, launch_session_t &, msg_t &&)> handle_data_fn; tcp::socket sock; std::array<char, 2048> msg_buf; char *crlf; char *begin = msg_buf.data(); std::shared_ptr<launch_session_t> session; }; class rtsp_server_t { public: ~rtsp_server_t() { clear(); } int bind(net::af_e af, std::uint16_t port, boost::system::error_code &ec) { acceptor.open(af == net::IPV4 ? tcp::v4() : tcp::v6(), ec); if (ec) { return -1; } acceptor.set_option(boost::asio::socket_base::reuse_address { true }); acceptor.bind(tcp::endpoint(af == net::IPV4 ? tcp::v4() : tcp::v6(), port), ec); if (ec) { return -1; } acceptor.listen(4096, ec); if (ec) { return -1; } next_socket = std::make_shared<socket_t>(ios, [this](tcp::socket &sock, launch_session_t &session, msg_t &&msg) { handle_msg(sock, session, std::move(msg)); }); acceptor.async_accept(next_socket->sock, [this](const auto &ec) { handle_accept(ec); }); return 0; } template <class T, class X> void iterate(std::chrono::duration<T, X> timeout) { ios.run_one_for(timeout); } void handle_msg(tcp::socket &sock, launch_session_t &session, msg_t &&req) { auto func = _map_cmd_cb.find(req->message.request.command); if (func != std::end(_map_cmd_cb)) { func->second(this, sock, session, std::move(req)); } else { cmd_not_found(sock, session, std::move(req)); } boost::system::error_code ec; sock.shutdown(boost::asio::socket_base::shutdown_type::shutdown_both, ec); } void handle_accept(const boost::system::error_code &ec) { if (ec) { BOOST_LOG(error) << "Couldn't accept incoming connections: "sv << ec.message(); // Stop server clear(); return; } auto socket = std::move(next_socket); auto launch_session { launch_event.view(0s) }; if (launch_session) { // Associate the current RTSP session with this socket and start reading socket->session = launch_session; socket->read(); } else { // This can happen due to normal things like port scanning, so let's not make these visible by default BOOST_LOG(debug) << "No pending session for incoming RTSP connection"sv; // If there is no session pending, close the connection immediately boost::system::error_code ec; socket->sock.close(ec); } // Queue another asynchronous accept for the next incoming connection next_socket = std::make_shared<socket_t>(ios, [this](tcp::socket &sock, launch_session_t &session, msg_t &&msg) { handle_msg(sock, session, std::move(msg)); }); acceptor.async_accept(next_socket->sock, [this](const auto &ec) { handle_accept(ec); }); } void map(const std::string_view &type, cmd_func_t cb) { _map_cmd_cb.emplace(type, std::move(cb)); } /** * @brief Launch a new streaming session. * @note If the client does not begin streaming within the ping_timeout, * the session will be discarded. * @param launch_session Streaming session information. */ void session_raise(std::shared_ptr<launch_session_t> launch_session) { auto now = std::chrono::steady_clock::now(); // If a launch event is still pending, don't overwrite it. if (raised_timeout > now && launch_event.peek()) { return; } raised_timeout = now + config::stream.ping_timeout; launch_event.raise(std::move(launch_session)); } /** * @brief Clear state for the oldest launch session. * @param launch_session_id The ID of the session to clear. */ void session_clear(uint32_t launch_session_id) { // We currently only support a single pending RTSP session, // so the ID should always match the one for that session. auto launch_session = launch_event.view(0s); if (launch_session) { if (launch_session->id != launch_session_id) { BOOST_LOG(error) << "Attempted to clear unexpected session: "sv << launch_session_id << " vs "sv << launch_session->id; } else { launch_event.pop(); } } } /** * @brief Get the number of active sessions. * @return Count of active sessions. */ int session_count() { auto lg = _session_slots.lock(); return _session_slots->size(); } safe::event_t<std::shared_ptr<launch_session_t>> launch_event; /** * @brief Clear launch sessions. * @param all If true, clear all sessions. Otherwise, only clear timed out and stopped sessions. * @examples * clear(false); * @examples_end */ void clear(bool all = true) { // if a launch event timed out --> Remove it. if (raised_timeout < std::chrono::steady_clock::now()) { auto discarded = launch_event.pop(0s); if (discarded) { BOOST_LOG(debug) << "Event timeout: "sv << discarded->unique_id; } } auto lg = _session_slots.lock(); for (auto i = _session_slots->begin(); i != _session_slots->end();) { auto &slot = *(*i); if (all || stream::session::state(slot) == stream::session::state_e::STOPPING) { stream::session::stop(slot); stream::session::join(slot); i = _session_slots->erase(i); } else { i++; } } } /** * @brief Removes the provided session from the set of sessions. * @param session The session to remove. */ void remove(const std::shared_ptr<stream::session_t> &session) { auto lg = _session_slots.lock(); _session_slots->erase(session); } /** * @brief Inserts the provided session into the set of sessions. * @param session The session to insert. */ void insert(const std::shared_ptr<stream::session_t> &session) { auto lg = _session_slots.lock(); _session_slots->emplace(session); BOOST_LOG(info) << "New streaming session started [active sessions: "sv << _session_slots->size() << ']'; } private: std::unordered_map<std::string_view, cmd_func_t> _map_cmd_cb; sync_util::sync_t<std::set<std::shared_ptr<stream::session_t>>> _session_slots; std::chrono::steady_clock::time_point raised_timeout; boost::asio::io_service ios; tcp::acceptor acceptor { ios }; std::shared_ptr<socket_t> next_socket; }; rtsp_server_t server {}; void launch_session_raise(std::shared_ptr<launch_session_t> launch_session) { server.session_raise(std::move(launch_session)); } void launch_session_clear(uint32_t launch_session_id) { server.session_clear(launch_session_id); } int session_count() { // Ensure session_count is up-to-date server.clear(false); return server.session_count(); } void terminate_sessions() { server.clear(true); } int send(tcp::socket &sock, const std::string_view &sv) { std::size_t bytes_send = 0; while (bytes_send != sv.size()) { boost::system::error_code ec; bytes_send += sock.send(boost::asio::buffer(sv.substr(bytes_send)), 0, ec); if (ec) { BOOST_LOG(error) << "RTSP: Couldn't send data over tcp socket: "sv << ec.message(); return -1; } } return 0; } void respond(tcp::socket &sock, launch_session_t &session, msg_t &resp) { auto payload = std::make_pair(resp->payload, resp->payloadLength); // Restore response message for proper destruction auto lg = util::fail_guard([&]() { resp->payload = payload.first; resp->payloadLength = payload.second; }); resp->payload = nullptr; resp->payloadLength = 0; int serialized_len; util::c_ptr<char> raw_resp { serializeRtspMessage(resp.get(), &serialized_len) }; BOOST_LOG(debug) << "---Begin Response---"sv << std::endl << std::string_view { raw_resp.get(), (std::size_t) serialized_len } << std::endl << std::string_view { payload.first, (std::size_t) payload.second } << std::endl << "---End Response---"sv << std::endl; // Encrypt the RTSP message if encryption is enabled if (session.rtsp_cipher) { // We use the deterministic IV construction algorithm specified in NIST SP 800-38D // Section 8.2.1. The sequence number is our "invocation" field and the 'RH' in the // high bytes is the "fixed" field. Because each client provides their own unique // key, our values in the fixed field need only uniquely identify each independent // use of the client's key with AES-GCM in our code. // // The sequence number is 32 bits long which allows for 2^32 RTSP messages to be // sent to each client before the IV repeats. crypto::aes_t iv(12); session.rtsp_iv_counter++; std::copy_n((uint8_t *) &session.rtsp_iv_counter, sizeof(session.rtsp_iv_counter), std::begin(iv)); iv[10] = 'H'; // Host originated iv[11] = 'R'; // RTSP // Allocate the message with an empty header and reserved space for the payload auto payload_length = serialized_len + payload.second; std::vector<uint8_t> message(sizeof(encrypted_rtsp_header_t)); message.reserve(message.size() + payload_length); // Copy the complete plaintext into the message std::copy_n(raw_resp.get(), serialized_len, std::back_inserter(message)); std::copy_n(payload.first, payload.second, std::back_inserter(message)); // Initialize the message header auto header = (encrypted_rtsp_header_t *) message.data(); header->typeAndLength = util::endian::big<std::uint32_t>(encrypted_rtsp_header_t::ENCRYPTED_MESSAGE_TYPE_BIT + payload_length); header->sequenceNumber = util::endian::big<std::uint32_t>(session.rtsp_iv_counter); // Encrypt the RTSP message in place session.rtsp_cipher->encrypt(std::string_view { (const char *) header->payload(), (std::size_t) payload_length }, header->tag, &iv); // Send the full encrypted message send(sock, std::string_view { (char *) message.data(), message.size() }); } else { std::string_view tmp_resp { raw_resp.get(), (size_t) serialized_len }; // Send the plaintext RTSP message header if (send(sock, tmp_resp)) { return; } // Send the plaintext RTSP message payload (if present) send(sock, std::string_view { payload.first, (std::size_t) payload.second }); } } void respond(tcp::socket &sock, launch_session_t &session, POPTION_ITEM options, int statuscode, const char *status_msg, int seqn, const std::string_view &payload) { msg_t resp { new msg_t::element_type }; createRtspResponse(resp.get(), nullptr, 0, const_cast<char *>("RTSP/1.0"), statuscode, const_cast<char *>(status_msg), seqn, options, const_cast<char *>(payload.data()), (int) payload.size()); respond(sock, session, resp); } void cmd_not_found(tcp::socket &sock, launch_session_t &session, msg_t &&req) { respond(sock, session, nullptr, 404, "NOT FOUND", req->sequenceNumber, {}); } void cmd_option(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) { OPTION_ITEM option {}; // I know these string literals will not be modified option.option = const_cast<char *>("CSeq"); auto seqn_str = std::to_string(req->sequenceNumber); option.content = const_cast<char *>(seqn_str.c_str()); respond(sock, session, &option, 200, "OK", req->sequenceNumber, {}); } void cmd_describe(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) { OPTION_ITEM option {}; // I know these string literals will not be modified option.option = const_cast<char *>("CSeq"); auto seqn_str = std::to_string(req->sequenceNumber); option.content = const_cast<char *>(seqn_str.c_str()); std::stringstream ss; // Tell the client about our supported features ss << "a=x-ss-general.featureFlags:" << (uint32_t) platf::get_capabilities() << std::endl; // Always request new control stream encryption if the client supports it uint32_t encryption_flags_supported = SS_ENC_CONTROL_V2 | SS_ENC_AUDIO; uint32_t encryption_flags_requested = SS_ENC_CONTROL_V2; // Determine the encryption desired for this remote endpoint auto encryption_mode = net::encryption_mode_for_address(sock.remote_endpoint().address()); if (encryption_mode != config::ENCRYPTION_MODE_NEVER) { // Advertise support for video encryption if it's not disabled encryption_flags_supported |= SS_ENC_VIDEO; // If it's mandatory, also request it to enable use if the client // didn't explicitly opt in, but it otherwise has support. if (encryption_mode == config::ENCRYPTION_MODE_MANDATORY) { encryption_flags_requested |= SS_ENC_VIDEO | SS_ENC_AUDIO; } } // Report supported and required encryption flags ss << "a=x-ss-general.encryptionSupported:" << encryption_flags_supported << std::endl; ss << "a=x-ss-general.encryptionRequested:" << encryption_flags_requested << std::endl; if (video::last_encoder_probe_supported_ref_frames_invalidation) { ss << "a=x-nv-video[0].refPicInvalidation:1"sv << std::endl; } if (video::active_hevc_mode != 1) { ss << "sprop-parameter-sets=AAAAAU"sv << std::endl; } if (video::active_av1_mode != 1) { ss << "a=rtpmap:98 AV1/90000"sv << std::endl; } if (!session.surround_params.empty()) { // If we have our own surround parameters, advertise them twice first ss << "a=fmtp:97 surround-params="sv << session.surround_params << std::endl; ss << "a=fmtp:97 surround-params="sv << session.surround_params << std::endl; } for (int x = 0; x < audio::MAX_STREAM_CONFIG; ++x) { auto &stream_config = audio::stream_configs[x]; std::uint8_t mapping[platf::speaker::MAX_SPEAKERS]; auto mapping_p = stream_config.mapping; /** * GFE advertises incorrect mapping for normal quality configurations, * as a result, Moonlight rotates all channels from index '3' to the right * To work around this, rotate channels to the left from index '3' */ if (x == audio::SURROUND51 || x == audio::SURROUND71) { std::copy_n(mapping_p, stream_config.channelCount, mapping); std::rotate(mapping + 3, mapping + 4, mapping + audio::MAX_STREAM_CONFIG); mapping_p = mapping; } ss << "a=fmtp:97 surround-params="sv << stream_config.channelCount << stream_config.streams << stream_config.coupledStreams; std::for_each_n(mapping_p, stream_config.channelCount, [&ss](std::uint8_t digit) { ss << (char) (digit + '0'); }); ss << std::endl; } respond(sock, session, &option, 200, "OK", req->sequenceNumber, ss.str()); } void cmd_setup(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) { OPTION_ITEM options[4] {}; auto &seqn = options[0]; auto &session_option = options[1]; auto &port_option = options[2]; auto &payload_option = options[3]; seqn.option = const_cast<char *>("CSeq"); auto seqn_str = std::to_string(req->sequenceNumber); seqn.content = const_cast<char *>(seqn_str.c_str()); std::string_view target { req->message.request.target }; auto begin = std::find(std::begin(target), std::end(target), '=') + 1; auto end = std::find(begin, std::end(target), '/'); std::string_view type { begin, (size_t) std::distance(begin, end) }; std::uint16_t port; if (type == "audio"sv) { port = net::map_port(stream::AUDIO_STREAM_PORT); } else if (type == "video"sv) { port = net::map_port(stream::VIDEO_STREAM_PORT); } else if (type == "control"sv) { port = net::map_port(stream::CONTROL_PORT); } else { cmd_not_found(sock, session, std::move(req)); return; } seqn.next = &session_option; session_option.option = const_cast<char *>("Session"); session_option.content = const_cast<char *>("DEADBEEFCAFE;timeout = 90"); session_option.next = &port_option; // Moonlight merely requires 'server_port=<port>' auto port_value = "server_port=" + std::to_string(port); port_option.option = const_cast<char *>("Transport"); port_option.content = port_value.data(); // Send identifiers that will be echoed in the other connections auto connect_data = std::to_string(session.control_connect_data); if (type == "control"sv) { payload_option.option = const_cast<char *>("X-SS-Connect-Data"); payload_option.content = connect_data.data(); } else { payload_option.option = const_cast<char *>("X-SS-Ping-Payload"); payload_option.content = session.av_ping_payload.data(); } port_option.next = &payload_option; respond(sock, session, &seqn, 200, "OK", req->sequenceNumber, {}); } void cmd_announce(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) { OPTION_ITEM option {}; // I know these string literals will not be modified option.option = const_cast<char *>("CSeq"); auto seqn_str = std::to_string(req->sequenceNumber); option.content = const_cast<char *>(seqn_str.c_str()); std::string_view payload { req->payload, (size_t) req->payloadLength }; std::vector<std::string_view> lines; auto whitespace = [](char ch) { return ch == '\n' || ch == '\r'; }; { auto pos = std::begin(payload); auto begin = pos; while (pos != std::end(payload)) { if (whitespace(*pos++)) { lines.emplace_back(begin, pos - begin - 1); while (pos != std::end(payload) && whitespace(*pos)) { ++pos; } begin = pos; } } } std::string_view client; std::unordered_map<std::string_view, std::string_view> args; for (auto line : lines) { auto type = line.substr(0, 2); if (type == "s="sv) { client = line.substr(2); } else if (type == "a=") { auto pos = line.find(':'); auto name = line.substr(2, pos - 2); auto val = line.substr(pos + 1); if (val[val.size() - 1] == ' ') { val = val.substr(0, val.size() - 1); } args.emplace(name, val); } } // Initialize any omitted parameters to defaults args.try_emplace("x-nv-video[0].encoderCscMode"sv, "0"sv); args.try_emplace("x-nv-vqos[0].bitStreamFormat"sv, "0"sv); args.try_emplace("x-nv-video[0].dynamicRangeMode"sv, "0"sv); args.try_emplace("x-nv-aqos.packetDuration"sv, "5"sv); args.try_emplace("x-nv-general.useReliableUdp"sv, "1"sv); args.try_emplace("x-nv-vqos[0].fec.minRequiredFecPackets"sv, "0"sv); args.try_emplace("x-nv-general.featureFlags"sv, "135"sv); args.try_emplace("x-ml-general.featureFlags"sv, "0"sv); args.try_emplace("x-nv-vqos[0].qosTrafficType"sv, "5"sv); args.try_emplace("x-nv-aqos.qosTrafficType"sv, "4"sv); args.try_emplace("x-ml-video.configuredBitrateKbps"sv, "0"sv); args.try_emplace("x-ss-general.encryptionEnabled"sv, "0"sv); args.try_emplace("x-ss-video[0].chromaSamplingType"sv, "0"sv); stream::config_t config; std::int64_t configuredBitrateKbps; config.audio.flags[audio::config_t::HOST_AUDIO] = session.host_audio; try { config.audio.channels = util::from_view(args.at("x-nv-audio.surround.numChannels"sv)); config.audio.mask = util::from_view(args.at("x-nv-audio.surround.channelMask"sv)); config.audio.packetDuration = util::from_view(args.at("x-nv-aqos.packetDuration"sv)); config.audio.flags[audio::config_t::HIGH_QUALITY] = util::from_view(args.at("x-nv-audio.surround.AudioQuality"sv)); config.controlProtocolType = util::from_view(args.at("x-nv-general.useReliableUdp"sv)); config.packetsize = util::from_view(args.at("x-nv-video[0].packetSize"sv)); config.minRequiredFecPackets = util::from_view(args.at("x-nv-vqos[0].fec.minRequiredFecPackets"sv)); config.mlFeatureFlags = util::from_view(args.at("x-ml-general.featureFlags"sv)); config.audioQosType = util::from_view(args.at("x-nv-aqos.qosTrafficType"sv)); config.videoQosType = util::from_view(args.at("x-nv-vqos[0].qosTrafficType"sv)); config.encryptionFlagsEnabled = util::from_view(args.at("x-ss-general.encryptionEnabled"sv)); // Legacy clients use nvFeatureFlags to indicate support for audio encryption if (util::from_view(args.at("x-nv-general.featureFlags"sv)) & 0x20) { config.encryptionFlagsEnabled |= SS_ENC_AUDIO; } config.monitor.height = util::from_view(args.at("x-nv-video[0].clientViewportHt"sv)); config.monitor.width = util::from_view(args.at("x-nv-video[0].clientViewportWd"sv)); config.monitor.framerate = util::from_view(args.at("x-nv-video[0].maxFPS"sv)); config.monitor.bitrate = util::from_view(args.at("x-nv-vqos[0].bw.maximumBitrateKbps"sv)); config.monitor.slicesPerFrame = util::from_view(args.at("x-nv-video[0].videoEncoderSlicesPerFrame"sv)); config.monitor.numRefFrames = util::from_view(args.at("x-nv-video[0].maxNumReferenceFrames"sv)); config.monitor.encoderCscMode = util::from_view(args.at("x-nv-video[0].encoderCscMode"sv)); config.monitor.videoFormat = util::from_view(args.at("x-nv-vqos[0].bitStreamFormat"sv)); config.monitor.dynamicRange = util::from_view(args.at("x-nv-video[0].dynamicRangeMode"sv)); config.monitor.chromaSamplingType = util::from_view(args.at("x-ss-video[0].chromaSamplingType"sv)); configuredBitrateKbps = util::from_view(args.at("x-ml-video.configuredBitrateKbps"sv)); } catch (std::out_of_range &) { respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {}); return; } // When using stereo audio, the audio quality is (strangely) indicated by whether the Host field // in the RTSP message matches a local interface's IP address. Fortunately, Moonlight always sends // 0.0.0.0 when it wants low quality, so it is easy to check without enumerating interfaces. if (config.audio.channels == 2) { for (auto option = req->options; option != nullptr; option = option->next) { if ("Host"sv == option->option) { std::string_view content { option->content }; BOOST_LOG(debug) << "Found Host: "sv << content; config.audio.flags[audio::config_t::HIGH_QUALITY] = (content.find("0.0.0.0"sv) == std::string::npos); } } } else if (session.surround_params.length() > 3) { // Channels std::uint8_t c = session.surround_params[0] - '0'; // Streams std::uint8_t n = session.surround_params[1] - '0'; // Coupled streams std::uint8_t m = session.surround_params[2] - '0'; auto valid = false; if ((c == 6 || c == 8) && c == config.audio.channels && n + m == c && session.surround_params.length() == c + 3) { config.audio.customStreamParams.channelCount = c; config.audio.customStreamParams.streams = n; config.audio.customStreamParams.coupledStreams = m; valid = true; for (std::uint8_t i = 0; i < c; i++) { config.audio.customStreamParams.mapping[i] = session.surround_params[i + 3] - '0'; if (config.audio.customStreamParams.mapping[i] >= c) { valid = false; break; } } } config.audio.flags[audio::config_t::CUSTOM_SURROUND_PARAMS] = valid; } // If the client sent a configured bitrate, we will choose the actual bitrate ourselves // by using FEC percentage and audio quality settings. If the calculated bitrate ends up // too low, we'll allow it to exceed the limits rather than reducing the encoding bitrate // down to nearly nothing. if (configuredBitrateKbps) { BOOST_LOG(debug) << "Client configured bitrate is "sv << configuredBitrateKbps << " Kbps"sv; // If the FEC percentage isn't too high, adjust the configured bitrate to ensure video // traffic doesn't exceed the user's selected bitrate when the FEC shards are included. if (config::stream.fec_percentage <= 80) { configuredBitrateKbps /= 100.f / (100 - config::stream.fec_percentage); } // Adjust the bitrate to account for audio traffic bandwidth usage (capped at 20% reduction). // The bitrate per channel is 256 Kbps for high quality mode and 96 Kbps for normal quality. auto audioBitrateAdjustment = (config.audio.flags[audio::config_t::HIGH_QUALITY] ? 256 : 96) * config.audio.channels; configuredBitrateKbps -= std::min((std::int64_t) audioBitrateAdjustment, configuredBitrateKbps / 5); // Reduce it by another 500Kbps to account for A/V packet overhead and control data // traffic (capped at 10% reduction). configuredBitrateKbps -= std::min((std::int64_t) 500, configuredBitrateKbps / 10); BOOST_LOG(debug) << "Final adjusted video encoding bitrate is "sv << configuredBitrateKbps << " Kbps"sv; config.monitor.bitrate = configuredBitrateKbps; } if (config.monitor.videoFormat == 1 && video::active_hevc_mode == 1) { BOOST_LOG(warning) << "HEVC is disabled, yet the client requested HEVC"sv; respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {}); return; } if (config.monitor.videoFormat == 2 && video::active_av1_mode == 1) { BOOST_LOG(warning) << "AV1 is disabled, yet the client requested AV1"sv; respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {}); return; } // Check that any required encryption is enabled auto encryption_mode = net::encryption_mode_for_address(sock.remote_endpoint().address()); if (encryption_mode == config::ENCRYPTION_MODE_MANDATORY && (config.encryptionFlagsEnabled & (SS_ENC_VIDEO | SS_ENC_AUDIO)) != (SS_ENC_VIDEO | SS_ENC_AUDIO)) { BOOST_LOG(error) << "Rejecting client that cannot comply with mandatory encryption requirement"sv; respond(sock, session, &option, 403, "Forbidden", req->sequenceNumber, {}); return; } auto stream_session = stream::session::alloc(config, session); server->insert(stream_session); if (stream::session::start(*stream_session, sock.remote_endpoint().address().to_string())) { BOOST_LOG(error) << "Failed to start a streaming session"sv; server->remove(stream_session); respond(sock, session, &option, 500, "Internal Server Error", req->sequenceNumber, {}); return; } respond(sock, session, &option, 200, "OK", req->sequenceNumber, {}); } void cmd_play(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) { OPTION_ITEM option {}; // I know these string literals will not be modified option.option = const_cast<char *>("CSeq"); auto seqn_str = std::to_string(req->sequenceNumber); option.content = const_cast<char *>(seqn_str.c_str()); respond(sock, session, &option, 200, "OK", req->sequenceNumber, {}); } void rtpThread() { auto shutdown_event = mail::man->event<bool>(mail::shutdown); auto broadcast_shutdown_event = mail::man->event<bool>(mail::broadcast_shutdown); server.map("OPTIONS"sv, &cmd_option); server.map("DESCRIBE"sv, &cmd_describe); server.map("SETUP"sv, &cmd_setup); server.map("ANNOUNCE"sv, &cmd_announce); server.map("PLAY"sv, &cmd_play); boost::system::error_code ec; if (server.bind(net::af_from_enum_string(config::sunshine.address_family), net::map_port(rtsp_stream::RTSP_SETUP_PORT), ec)) { BOOST_LOG(fatal) << "Couldn't bind RTSP server to port ["sv << net::map_port(rtsp_stream::RTSP_SETUP_PORT) << "], " << ec.message(); shutdown_event->raise(true); return; } while (!shutdown_event->peek()) { server.iterate(std::min(500ms, config::stream.ping_timeout)); if (broadcast_shutdown_event->peek()) { server.clear(); } else { // cleanup all stopped sessions server.clear(false); } } server.clear(); } void print_msg(PRTSP_MESSAGE msg) { std::string_view type = msg->type == TYPE_RESPONSE ? "RESPONSE"sv : "REQUEST"sv; std::string_view payload { msg->payload, (size_t) msg->payloadLength }; std::string_view protocol { msg->protocol }; auto seqnm = msg->sequenceNumber; std::string_view messageBuffer { msg->messageBuffer }; BOOST_LOG(debug) << "type ["sv << type << ']'; BOOST_LOG(debug) << "sequence number ["sv << seqnm << ']'; BOOST_LOG(debug) << "protocol :: "sv << protocol; BOOST_LOG(debug) << "payload :: "sv << payload; if (msg->type == TYPE_RESPONSE) { auto &resp = msg->message.response; auto statuscode = resp.statusCode; std::string_view status { resp.statusString }; BOOST_LOG(debug) << "statuscode :: "sv << statuscode; BOOST_LOG(debug) << "status :: "sv << status; } else { auto &req = msg->message.request; std::string_view command { req.command }; std::string_view target { req.target }; BOOST_LOG(debug) << "command :: "sv << command; BOOST_LOG(debug) << "target :: "sv << target; } for (auto option = msg->options; option != nullptr; option = option->next) { std::string_view content { option->content }; std::string_view name { option->option }; BOOST_LOG(debug) << name << " :: "sv << content; } BOOST_LOG(debug) << "---Begin MessageBuffer---"sv << std::endl << messageBuffer << std::endl << "---End MessageBuffer---"sv << std::endl; } } // namespace rtsp_stream
43,824
C++
.cpp
963
38.870197
196
0.634616
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,979
audio.cpp
LizardByte_Sunshine/src/audio.cpp
/** * @file src/audio.cpp * @brief Definitions for audio capture and encoding. */ #include <thread> #include <opus/opus_multistream.h> #include "platform/common.h" #include "audio.h" #include "config.h" #include "globals.h" #include "logging.h" #include "thread_safe.h" #include "utility.h" namespace audio { using namespace std::literals; using opus_t = util::safe_ptr<OpusMSEncoder, opus_multistream_encoder_destroy>; using sample_queue_t = std::shared_ptr<safe::queue_t<std::vector<float>>>; struct audio_ctx_t { // We want to change the sink for the first stream only std::unique_ptr<std::atomic_bool> sink_flag; std::unique_ptr<platf::audio_control_t> control; bool restore_sink; platf::sink_t sink; }; static int start_audio_control(audio_ctx_t &ctx); static void stop_audio_control(audio_ctx_t &); static void apply_surround_params(opus_stream_config_t &stream, const stream_params_t &params); int map_stream(int channels, bool quality); constexpr auto SAMPLE_RATE = 48000; // NOTE: If you adjust the bitrates listed here, make sure to update the // corresponding bitrate adjustment logic in rtsp_stream::cmd_announce() opus_stream_config_t stream_configs[MAX_STREAM_CONFIG] { { SAMPLE_RATE, 2, 1, 1, platf::speaker::map_stereo, 96000, }, { SAMPLE_RATE, 2, 1, 1, platf::speaker::map_stereo, 512000, }, { SAMPLE_RATE, 6, 4, 2, platf::speaker::map_surround51, 256000, }, { SAMPLE_RATE, 6, 6, 0, platf::speaker::map_surround51, 1536000, }, { SAMPLE_RATE, 8, 5, 3, platf::speaker::map_surround71, 450000, }, { SAMPLE_RATE, 8, 8, 0, platf::speaker::map_surround71, 2048000, }, }; auto control_shared = safe::make_shared<audio_ctx_t>(start_audio_control, stop_audio_control); void encodeThread(sample_queue_t samples, config_t config, void *channel_data) { auto packets = mail::man->queue<packet_t>(mail::audio_packets); auto stream = stream_configs[map_stream(config.channels, config.flags[config_t::HIGH_QUALITY])]; if (config.flags[config_t::CUSTOM_SURROUND_PARAMS]) { apply_surround_params(stream, config.customStreamParams); } // Encoding takes place on this thread platf::adjust_thread_priority(platf::thread_priority_e::high); opus_t opus { opus_multistream_encoder_create( stream.sampleRate, stream.channelCount, stream.streams, stream.coupledStreams, stream.mapping, OPUS_APPLICATION_RESTRICTED_LOWDELAY, nullptr) }; opus_multistream_encoder_ctl(opus.get(), OPUS_SET_BITRATE(stream.bitrate)); opus_multistream_encoder_ctl(opus.get(), OPUS_SET_VBR(0)); BOOST_LOG(info) << "Opus initialized: "sv << stream.sampleRate / 1000 << " kHz, "sv << stream.channelCount << " channels, "sv << stream.bitrate / 1000 << " kbps (total), LOWDELAY"sv; auto frame_size = config.packetDuration * stream.sampleRate / 1000; while (auto sample = samples->pop()) { buffer_t packet { 1400 }; int bytes = opus_multistream_encode_float(opus.get(), sample->data(), frame_size, std::begin(packet), packet.size()); if (bytes < 0) { BOOST_LOG(error) << "Couldn't encode audio: "sv << opus_strerror(bytes); packets->stop(); return; } packet.fake_resize(bytes); packets->raise(channel_data, std::move(packet)); } } void capture(safe::mail_t mail, config_t config, void *channel_data) { auto shutdown_event = mail->event<bool>(mail::shutdown); auto stream = stream_configs[map_stream(config.channels, config.flags[config_t::HIGH_QUALITY])]; if (config.flags[config_t::CUSTOM_SURROUND_PARAMS]) { apply_surround_params(stream, config.customStreamParams); } auto ref = control_shared.ref(); if (!ref) { return; } auto init_failure_fg = util::fail_guard([&shutdown_event]() { BOOST_LOG(error) << "Unable to initialize audio capture. The stream will not have audio."sv; // Wait for shutdown to be signalled if we fail init. // This allows streaming to continue without audio. shutdown_event->view(); }); auto &control = ref->control; if (!control) { return; } // Order of priority: // 1. Virtual sink // 2. Audio sink // 3. Host std::string *sink = &ref->sink.host; if (!config::audio.sink.empty()) { sink = &config::audio.sink; } // Prefer the virtual sink if host playback is disabled or there's no other sink if (ref->sink.null && (!config.flags[config_t::HOST_AUDIO] || sink->empty())) { auto &null = *ref->sink.null; switch (stream.channelCount) { case 2: sink = &null.stereo; break; case 6: sink = &null.surround51; break; case 8: sink = &null.surround71; break; } } // Only the first to start a session may change the default sink if (!ref->sink_flag->exchange(true, std::memory_order_acquire)) { // If the selected sink is different than the current one, change sinks. ref->restore_sink = ref->sink.host != *sink; if (ref->restore_sink) { if (control->set_sink(*sink)) { return; } } } auto frame_size = config.packetDuration * stream.sampleRate / 1000; auto mic = control->microphone(stream.mapping, stream.channelCount, stream.sampleRate, frame_size); if (!mic) { return; } // Audio is initialized, so we don't want to print the failure message init_failure_fg.disable(); // Capture takes place on this thread platf::adjust_thread_priority(platf::thread_priority_e::critical); auto samples = std::make_shared<sample_queue_t::element_type>(30); std::thread thread { encodeThread, samples, config, channel_data }; auto fg = util::fail_guard([&]() { samples->stop(); thread.join(); shutdown_event->view(); }); int samples_per_frame = frame_size * stream.channelCount; while (!shutdown_event->peek()) { std::vector<float> sample_buffer; sample_buffer.resize(samples_per_frame); auto status = mic->sample(sample_buffer); switch (status) { case platf::capture_e::ok: break; case platf::capture_e::timeout: continue; case platf::capture_e::reinit: BOOST_LOG(info) << "Reinitializing audio capture"sv; mic.reset(); do { mic = control->microphone(stream.mapping, stream.channelCount, stream.sampleRate, frame_size); if (!mic) { BOOST_LOG(warning) << "Couldn't re-initialize audio input"sv; } } while (!mic && !shutdown_event->view(5s)); continue; default: return; } samples->raise(std::move(sample_buffer)); } } int map_stream(int channels, bool quality) { int shift = quality ? 1 : 0; switch (channels) { case 2: return STEREO + shift; case 6: return SURROUND51 + shift; case 8: return SURROUND71 + shift; } return STEREO; } int start_audio_control(audio_ctx_t &ctx) { auto fg = util::fail_guard([]() { BOOST_LOG(warning) << "There will be no audio"sv; }); ctx.sink_flag = std::make_unique<std::atomic_bool>(false); // The default sink has not been replaced yet. ctx.restore_sink = false; if (!(ctx.control = platf::audio_control())) { return 0; } auto sink = ctx.control->sink_info(); if (!sink) { // Let the calling code know it failed ctx.control.reset(); return 0; } ctx.sink = std::move(*sink); fg.disable(); return 0; } void stop_audio_control(audio_ctx_t &ctx) { // restore audio-sink if applicable if (!ctx.restore_sink) { return; } // Change back to the host sink, unless there was none const std::string &sink = ctx.sink.host.empty() ? config::audio.sink : ctx.sink.host; if (!sink.empty()) { // Best effort, it's allowed to fail ctx.control->set_sink(sink); } } void apply_surround_params(opus_stream_config_t &stream, const stream_params_t &params) { stream.channelCount = params.channelCount; stream.streams = params.streams; stream.coupledStreams = params.coupledStreams; stream.mapping = params.mapping; } } // namespace audio
8,711
C++
.cpp
272
25.897059
123
0.627369
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,980
nvhttp.cpp
LizardByte_Sunshine/src/nvhttp.cpp
/** * @file src/nvhttp.cpp * @brief Definitions for the nvhttp (GameStream) server. */ // macros #define BOOST_BIND_GLOBAL_PLACEHOLDERS // standard includes #include <filesystem> #include <utility> // lib includes #include <Simple-Web-Server/server_http.hpp> #include <Simple-Web-Server/server_https.hpp> #include <boost/asio/ssl/context.hpp> #include <boost/asio/ssl/context_base.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <string> // local includes #include "config.h" #include "crypto.h" #include "file_handler.h" #include "globals.h" #include "httpcommon.h" #include "logging.h" #include "network.h" #include "nvhttp.h" #include "platform/common.h" #include "process.h" #include "rtsp.h" #include "system_tray.h" #include "utility.h" #include "uuid.h" #include "video.h" using namespace std::literals; namespace nvhttp { namespace fs = std::filesystem; namespace pt = boost::property_tree; crypto::cert_chain_t cert_chain; class SunshineHTTPS: public SimpleWeb::HTTPS { public: SunshineHTTPS(boost::asio::io_service &io_service, boost::asio::ssl::context &ctx): SimpleWeb::HTTPS(io_service, ctx) {} virtual ~SunshineHTTPS() { // Gracefully shutdown the TLS connection SimpleWeb::error_code ec; shutdown(ec); } }; class SunshineHTTPSServer: public SimpleWeb::ServerBase<SunshineHTTPS> { public: SunshineHTTPSServer(const std::string &certification_file, const std::string &private_key_file): ServerBase<SunshineHTTPS>::ServerBase(443), context(boost::asio::ssl::context::tls_server) { // Disabling TLS 1.0 and 1.1 (see RFC 8996) context.set_options(boost::asio::ssl::context::no_tlsv1); context.set_options(boost::asio::ssl::context::no_tlsv1_1); context.use_certificate_chain_file(certification_file); context.use_private_key_file(private_key_file, boost::asio::ssl::context::pem); } std::function<int(SSL *)> verify; std::function<void(std::shared_ptr<Response>, std::shared_ptr<Request>)> on_verify_failed; protected: boost::asio::ssl::context context; void after_bind() override { if (verify) { context.set_verify_mode(boost::asio::ssl::verify_peer | boost::asio::ssl::verify_fail_if_no_peer_cert | boost::asio::ssl::verify_client_once); context.set_verify_callback([](int verified, boost::asio::ssl::verify_context &ctx) { // To respond with an error message, a connection must be established return 1; }); } } // This is Server<HTTPS>::accept() with SSL validation support added void accept() override { auto connection = create_connection(*io_service, context); acceptor->async_accept(connection->socket->lowest_layer(), [this, connection](const SimpleWeb::error_code &ec) { auto lock = connection->handler_runner->continue_lock(); if (!lock) return; if (ec != SimpleWeb::error::operation_aborted) this->accept(); auto session = std::make_shared<Session>(config.max_request_streambuf_size, connection); if (!ec) { boost::asio::ip::tcp::no_delay option(true); SimpleWeb::error_code ec; session->connection->socket->lowest_layer().set_option(option, ec); session->connection->set_timeout(config.timeout_request); session->connection->socket->async_handshake(boost::asio::ssl::stream_base::server, [this, session](const SimpleWeb::error_code &ec) { session->connection->cancel_timeout(); auto lock = session->connection->handler_runner->continue_lock(); if (!lock) return; if (!ec) { if (verify && !verify(session->connection->socket->native_handle())) this->write(session, on_verify_failed); else this->read(session); } else if (this->on_error) this->on_error(session->request, ec); }); } else if (this->on_error) this->on_error(session->request, ec); }); } }; using https_server_t = SunshineHTTPSServer; using http_server_t = SimpleWeb::Server<SimpleWeb::HTTP>; struct conf_intern_t { std::string servercert; std::string pkey; } conf_intern; struct named_cert_t { std::string name; std::string uuid; std::string cert; }; struct client_t { std::vector<named_cert_t> named_devices; }; struct pair_session_t { struct { std::string uniqueID; std::string cert; std::string name; } client; std::unique_ptr<crypto::aes_t> cipher_key; std::vector<uint8_t> clienthash; std::string serversecret; std::string serverchallenge; struct { util::Either< std::shared_ptr<typename SimpleWeb::ServerBase<SimpleWeb::HTTP>::Response>, std::shared_ptr<typename SimpleWeb::ServerBase<SunshineHTTPS>::Response>> response; std::string salt; } async_insert_pin; }; // uniqueID, session std::unordered_map<std::string, pair_session_t> map_id_sess; client_t client_root; std::atomic<uint32_t> session_id_counter; using args_t = SimpleWeb::CaseInsensitiveMultimap; using resp_https_t = std::shared_ptr<typename SimpleWeb::ServerBase<SunshineHTTPS>::Response>; using req_https_t = std::shared_ptr<typename SimpleWeb::ServerBase<SunshineHTTPS>::Request>; using resp_http_t = std::shared_ptr<typename SimpleWeb::ServerBase<SimpleWeb::HTTP>::Response>; using req_http_t = std::shared_ptr<typename SimpleWeb::ServerBase<SimpleWeb::HTTP>::Request>; enum class op_e { ADD, ///< Add certificate REMOVE ///< Remove certificate }; std::string get_arg(const args_t &args, const char *name, const char *default_value = nullptr) { auto it = args.find(name); if (it == std::end(args)) { if (default_value != NULL) { return std::string(default_value); } throw std::out_of_range(name); } return it->second; } void save_state() { pt::ptree root; if (fs::exists(config::nvhttp.file_state)) { try { pt::read_json(config::nvhttp.file_state, root); } catch (std::exception &e) { BOOST_LOG(error) << "Couldn't read "sv << config::nvhttp.file_state << ": "sv << e.what(); return; } } root.erase("root"s); root.put("root.uniqueid", http::unique_id); client_t &client = client_root; pt::ptree node; pt::ptree named_cert_nodes; for (auto &named_cert : client.named_devices) { pt::ptree named_cert_node; named_cert_node.put("name"s, named_cert.name); named_cert_node.put("cert"s, named_cert.cert); named_cert_node.put("uuid"s, named_cert.uuid); named_cert_nodes.push_back(std::make_pair(""s, named_cert_node)); } root.add_child("root.named_devices"s, named_cert_nodes); try { pt::write_json(config::nvhttp.file_state, root); } catch (std::exception &e) { BOOST_LOG(error) << "Couldn't write "sv << config::nvhttp.file_state << ": "sv << e.what(); return; } } void load_state() { if (!fs::exists(config::nvhttp.file_state)) { BOOST_LOG(info) << "File "sv << config::nvhttp.file_state << " doesn't exist"sv; http::unique_id = uuid_util::uuid_t::generate().string(); return; } pt::ptree tree; try { pt::read_json(config::nvhttp.file_state, tree); } catch (std::exception &e) { BOOST_LOG(error) << "Couldn't read "sv << config::nvhttp.file_state << ": "sv << e.what(); return; } auto unique_id_p = tree.get_optional<std::string>("root.uniqueid"); if (!unique_id_p) { // This file doesn't contain moonlight credentials http::unique_id = uuid_util::uuid_t::generate().string(); return; } http::unique_id = std::move(*unique_id_p); auto root = tree.get_child("root"); client_t client; // Import from old format if (root.get_child_optional("devices")) { auto device_nodes = root.get_child("devices"); for (auto &[_, device_node] : device_nodes) { auto uniqID = device_node.get<std::string>("uniqueid"); if (device_node.count("certs")) { for (auto &[_, el] : device_node.get_child("certs")) { named_cert_t named_cert; named_cert.name = ""s; named_cert.cert = el.get_value<std::string>(); named_cert.uuid = uuid_util::uuid_t::generate().string(); client.named_devices.emplace_back(named_cert); } } } } if (root.count("named_devices")) { for (auto &[_, el] : root.get_child("named_devices")) { named_cert_t named_cert; named_cert.name = el.get_child("name").get_value<std::string>(); named_cert.cert = el.get_child("cert").get_value<std::string>(); named_cert.uuid = el.get_child("uuid").get_value<std::string>(); client.named_devices.emplace_back(named_cert); } } // Empty certificate chain and import certs from file cert_chain.clear(); for (auto &named_cert : client.named_devices) { cert_chain.add(crypto::x509(named_cert.cert)); } client_root = client; } void add_authorized_client(const std::string &name, std::string &&cert) { client_t &client = client_root; named_cert_t named_cert; named_cert.name = name; named_cert.cert = std::move(cert); named_cert.uuid = uuid_util::uuid_t::generate().string(); client.named_devices.emplace_back(named_cert); if (!config::sunshine.flags[config::flag::FRESH_STATE]) { save_state(); } } std::shared_ptr<rtsp_stream::launch_session_t> make_launch_session(bool host_audio, const args_t &args) { auto launch_session = std::make_shared<rtsp_stream::launch_session_t>(); launch_session->id = ++session_id_counter; auto rikey = util::from_hex_vec(get_arg(args, "rikey"), true); std::copy(rikey.cbegin(), rikey.cend(), std::back_inserter(launch_session->gcm_key)); launch_session->host_audio = host_audio; std::stringstream mode = std::stringstream(get_arg(args, "mode", "0x0x0")); // Split mode by the char "x", to populate width/height/fps int x = 0; std::string segment; while (std::getline(mode, segment, 'x')) { if (x == 0) launch_session->width = atoi(segment.c_str()); if (x == 1) launch_session->height = atoi(segment.c_str()); if (x == 2) launch_session->fps = atoi(segment.c_str()); x++; } launch_session->unique_id = (get_arg(args, "uniqueid", "unknown")); launch_session->appid = util::from_view(get_arg(args, "appid", "unknown")); launch_session->enable_sops = util::from_view(get_arg(args, "sops", "0")); launch_session->surround_info = util::from_view(get_arg(args, "surroundAudioInfo", "196610")); launch_session->surround_params = (get_arg(args, "surroundParams", "")); launch_session->gcmap = util::from_view(get_arg(args, "gcmap", "0")); launch_session->enable_hdr = util::from_view(get_arg(args, "hdrMode", "0")); // Encrypted RTSP is enabled with client reported corever >= 1 auto corever = util::from_view(get_arg(args, "corever", "0")); if (corever >= 1) { launch_session->rtsp_cipher = crypto::cipher::gcm_t { launch_session->gcm_key, false }; launch_session->rtsp_iv_counter = 0; } launch_session->rtsp_url_scheme = launch_session->rtsp_cipher ? "rtspenc://"s : "rtsp://"s; // Generate the unique identifiers for this connection that we will send later during RTSP handshake unsigned char raw_payload[8]; RAND_bytes(raw_payload, sizeof(raw_payload)); launch_session->av_ping_payload = util::hex_vec(raw_payload); RAND_bytes((unsigned char *) &launch_session->control_connect_data, sizeof(launch_session->control_connect_data)); launch_session->iv.resize(16); uint32_t prepend_iv = util::endian::big<uint32_t>(util::from_view(get_arg(args, "rikeyid"))); auto prepend_iv_p = (uint8_t *) &prepend_iv; std::copy(prepend_iv_p, prepend_iv_p + sizeof(prepend_iv), std::begin(launch_session->iv)); return launch_session; } void getservercert(pair_session_t &sess, pt::ptree &tree, const std::string &pin) { if (sess.async_insert_pin.salt.size() < 32) { tree.put("root.paired", 0); tree.put("root.<xmlattr>.status_code", 400); tree.put("root.<xmlattr>.status_message", "Salt too short"); return; } std::string_view salt_view { sess.async_insert_pin.salt.data(), 32 }; auto salt = util::from_hex<std::array<uint8_t, 16>>(salt_view, true); auto key = crypto::gen_aes_key(salt, pin); sess.cipher_key = std::make_unique<crypto::aes_t>(key); tree.put("root.paired", 1); tree.put("root.plaincert", util::hex_vec(conf_intern.servercert, true)); tree.put("root.<xmlattr>.status_code", 200); } void serverchallengeresp(pair_session_t &sess, pt::ptree &tree, const args_t &args) { auto encrypted_response = util::from_hex_vec(get_arg(args, "serverchallengeresp"), true); std::vector<uint8_t> decrypted; crypto::cipher::ecb_t cipher(*sess.cipher_key, false); cipher.decrypt(encrypted_response, decrypted); sess.clienthash = std::move(decrypted); auto serversecret = sess.serversecret; auto sign = crypto::sign256(crypto::pkey(conf_intern.pkey), serversecret); serversecret.insert(std::end(serversecret), std::begin(sign), std::end(sign)); tree.put("root.pairingsecret", util::hex_vec(serversecret, true)); tree.put("root.paired", 1); tree.put("root.<xmlattr>.status_code", 200); } void clientchallenge(pair_session_t &sess, pt::ptree &tree, const args_t &args) { auto challenge = util::from_hex_vec(get_arg(args, "clientchallenge"), true); crypto::cipher::ecb_t cipher(*sess.cipher_key, false); std::vector<uint8_t> decrypted; cipher.decrypt(challenge, decrypted); auto x509 = crypto::x509(conf_intern.servercert); auto sign = crypto::signature(x509); auto serversecret = crypto::rand(16); decrypted.insert(std::end(decrypted), std::begin(sign), std::end(sign)); decrypted.insert(std::end(decrypted), std::begin(serversecret), std::end(serversecret)); auto hash = crypto::hash({ (char *) decrypted.data(), decrypted.size() }); auto serverchallenge = crypto::rand(16); std::string plaintext; plaintext.reserve(hash.size() + serverchallenge.size()); plaintext.insert(std::end(plaintext), std::begin(hash), std::end(hash)); plaintext.insert(std::end(plaintext), std::begin(serverchallenge), std::end(serverchallenge)); std::vector<uint8_t> encrypted; cipher.encrypt(plaintext, encrypted); sess.serversecret = std::move(serversecret); sess.serverchallenge = std::move(serverchallenge); tree.put("root.paired", 1); tree.put("root.challengeresponse", util::hex_vec(encrypted, true)); tree.put("root.<xmlattr>.status_code", 200); } void clientpairingsecret(std::shared_ptr<safe::queue_t<crypto::x509_t>> &add_cert, pair_session_t &sess, pt::ptree &tree, const args_t &args) { auto &client = sess.client; auto pairingsecret = util::from_hex_vec(get_arg(args, "clientpairingsecret"), true); if (pairingsecret.size() <= 16) { tree.put("root.paired", 0); tree.put("root.<xmlattr>.status_code", 400); tree.put("root.<xmlattr>.status_message", "Clientpairingsecret too short"); return; } std::string_view secret { pairingsecret.data(), 16 }; std::string_view sign { pairingsecret.data() + secret.size(), pairingsecret.size() - secret.size() }; auto x509 = crypto::x509(client.cert); auto x509_sign = crypto::signature(x509); std::string data; data.reserve(sess.serverchallenge.size() + x509_sign.size() + secret.size()); data.insert(std::end(data), std::begin(sess.serverchallenge), std::end(sess.serverchallenge)); data.insert(std::end(data), std::begin(x509_sign), std::end(x509_sign)); data.insert(std::end(data), std::begin(secret), std::end(secret)); auto hash = crypto::hash(data); // if hash not correct, probably MITM if (!std::memcmp(hash.data(), sess.clienthash.data(), hash.size()) && crypto::verify256(crypto::x509(client.cert), secret, sign)) { tree.put("root.paired", 1); add_cert->raise(crypto::x509(client.cert)); // The client is now successfully paired and will be authorized to connect auto it = map_id_sess.find(client.uniqueID); add_authorized_client(client.name, std::move(client.cert)); map_id_sess.erase(it); } else { map_id_sess.erase(client.uniqueID); tree.put("root.paired", 0); } tree.put("root.<xmlattr>.status_code", 200); } template <class T> struct tunnel; template <> struct tunnel<SunshineHTTPS> { static auto constexpr to_string = "HTTPS"sv; }; template <> struct tunnel<SimpleWeb::HTTP> { static auto constexpr to_string = "NONE"sv; }; template <class T> void print_req(std::shared_ptr<typename SimpleWeb::ServerBase<T>::Request> request) { BOOST_LOG(debug) << "TUNNEL :: "sv << tunnel<T>::to_string; BOOST_LOG(debug) << "METHOD :: "sv << request->method; BOOST_LOG(debug) << "DESTINATION :: "sv << request->path; for (auto &[name, val] : request->header) { BOOST_LOG(debug) << name << " -- " << val; } BOOST_LOG(debug) << " [--] "sv; for (auto &[name, val] : request->parse_query_string()) { BOOST_LOG(debug) << name << " -- " << val; } BOOST_LOG(debug) << " [--] "sv; } template <class T> void not_found(std::shared_ptr<typename SimpleWeb::ServerBase<T>::Response> response, std::shared_ptr<typename SimpleWeb::ServerBase<T>::Request> request) { print_req<T>(request); pt::ptree tree; tree.put("root.<xmlattr>.status_code", 404); std::ostringstream data; pt::write_xml(data, tree); response->write(data.str()); *response << "HTTP/1.1 404 NOT FOUND\r\n" << data.str(); response->close_connection_after_response = true; } template <class T> void pair(std::shared_ptr<safe::queue_t<crypto::x509_t>> &add_cert, std::shared_ptr<typename SimpleWeb::ServerBase<T>::Response> response, std::shared_ptr<typename SimpleWeb::ServerBase<T>::Request> request) { print_req<T>(request); pt::ptree tree; auto fg = util::fail_guard([&]() { std::ostringstream data; pt::write_xml(data, tree); response->write(data.str()); response->close_connection_after_response = true; }); auto args = request->parse_query_string(); if (args.find("uniqueid"s) == std::end(args)) { tree.put("root.<xmlattr>.status_code", 400); tree.put("root.<xmlattr>.status_message", "Missing uniqueid parameter"); return; } auto uniqID { get_arg(args, "uniqueid") }; auto sess_it = map_id_sess.find(uniqID); args_t::const_iterator it; if (it = args.find("phrase"); it != std::end(args)) { if (it->second == "getservercert"sv) { pair_session_t sess; sess.client.uniqueID = std::move(uniqID); sess.client.cert = util::from_hex_vec(get_arg(args, "clientcert"), true); BOOST_LOG(debug) << sess.client.cert; auto ptr = map_id_sess.emplace(sess.client.uniqueID, std::move(sess)).first; ptr->second.async_insert_pin.salt = std::move(get_arg(args, "salt")); if (config::sunshine.flags[config::flag::PIN_STDIN]) { std::string pin; std::cout << "Please insert pin: "sv; std::getline(std::cin, pin); getservercert(ptr->second, tree, pin); } else { #if defined SUNSHINE_TRAY && SUNSHINE_TRAY >= 1 system_tray::update_tray_require_pin(); #endif ptr->second.async_insert_pin.response = std::move(response); fg.disable(); return; } } else if (it->second == "pairchallenge"sv) { tree.put("root.paired", 1); tree.put("root.<xmlattr>.status_code", 200); } } else if (it = args.find("clientchallenge"); it != std::end(args)) { clientchallenge(sess_it->second, tree, args); } else if (it = args.find("serverchallengeresp"); it != std::end(args)) { serverchallengeresp(sess_it->second, tree, args); } else if (it = args.find("clientpairingsecret"); it != std::end(args)) { clientpairingsecret(add_cert, sess_it->second, tree, args); } else { tree.put("root.<xmlattr>.status_code", 404); tree.put("root.<xmlattr>.status_message", "Invalid pairing request"); } } bool pin(std::string pin, std::string name) { pt::ptree tree; if (map_id_sess.empty()) { return false; } // ensure pin is 4 digits if (pin.size() != 4) { tree.put("root.paired", 0); tree.put("root.<xmlattr>.status_code", 400); tree.put( "root.<xmlattr>.status_message", "Pin must be 4 digits, " + std::to_string(pin.size()) + " provided"); return false; } // ensure all pin characters are numeric if (!std::all_of(pin.begin(), pin.end(), ::isdigit)) { tree.put("root.paired", 0); tree.put("root.<xmlattr>.status_code", 400); tree.put("root.<xmlattr>.status_message", "Pin must be numeric"); return false; } auto &sess = std::begin(map_id_sess)->second; getservercert(sess, tree, pin); sess.client.name = name; // response to the request for pin std::ostringstream data; pt::write_xml(data, tree); auto &async_response = sess.async_insert_pin.response; if (async_response.has_left() && async_response.left()) { async_response.left()->write(data.str()); } else if (async_response.has_right() && async_response.right()) { async_response.right()->write(data.str()); } else { return false; } // reset async_response async_response = std::decay_t<decltype(async_response.left())>(); // response to the current request return true; } template <class T> void serverinfo(std::shared_ptr<typename SimpleWeb::ServerBase<T>::Response> response, std::shared_ptr<typename SimpleWeb::ServerBase<T>::Request> request) { print_req<T>(request); int pair_status = 0; if constexpr (std::is_same_v<SunshineHTTPS, T>) { auto args = request->parse_query_string(); auto clientID = args.find("uniqueid"s); if (clientID != std::end(args)) { pair_status = 1; } } auto local_endpoint = request->local_endpoint(); pt::ptree tree; tree.put("root.<xmlattr>.status_code", 200); tree.put("root.hostname", config::nvhttp.sunshine_name); tree.put("root.appversion", VERSION); tree.put("root.GfeVersion", GFE_VERSION); tree.put("root.uniqueid", http::unique_id); tree.put("root.HttpsPort", net::map_port(PORT_HTTPS)); tree.put("root.ExternalPort", net::map_port(PORT_HTTP)); tree.put("root.MaxLumaPixelsHEVC", video::active_hevc_mode > 1 ? "1869449984" : "0"); // Only include the MAC address for requests sent from paired clients over HTTPS. // For HTTP requests, use a placeholder MAC address that Moonlight knows to ignore. if constexpr (std::is_same_v<SunshineHTTPS, T>) { tree.put("root.mac", platf::get_mac_address(net::addr_to_normalized_string(local_endpoint.address()))); } else { tree.put("root.mac", "00:00:00:00:00:00"); } // Moonlight clients track LAN IPv6 addresses separately from LocalIP which is expected to // always be an IPv4 address. If we return that same IPv6 address here, it will clobber the // stored LAN IPv4 address. To avoid this, we need to return an IPv4 address in this field // when we get a request over IPv6. // // HACK: We should return the IPv4 address of local interface here, but we don't currently // have that implemented. For now, we will emulate the behavior of GFE+GS-IPv6-Forwarder, // which returns 127.0.0.1 as LocalIP for IPv6 connections. Moonlight clients with IPv6 // support know to ignore this bogus address. if (local_endpoint.address().is_v6() && !local_endpoint.address().to_v6().is_v4_mapped()) { tree.put("root.LocalIP", "127.0.0.1"); } else { tree.put("root.LocalIP", net::addr_to_normalized_string(local_endpoint.address())); } uint32_t codec_mode_flags = SCM_H264; if (video::last_encoder_probe_supported_yuv444_for_codec[0]) { codec_mode_flags |= SCM_H264_HIGH8_444; } if (video::active_hevc_mode >= 2) { codec_mode_flags |= SCM_HEVC; if (video::last_encoder_probe_supported_yuv444_for_codec[1]) { codec_mode_flags |= SCM_HEVC_REXT8_444; } } if (video::active_hevc_mode >= 3) { codec_mode_flags |= SCM_HEVC_MAIN10; if (video::last_encoder_probe_supported_yuv444_for_codec[1]) { codec_mode_flags |= SCM_HEVC_REXT10_444; } } if (video::active_av1_mode >= 2) { codec_mode_flags |= SCM_AV1_MAIN8; if (video::last_encoder_probe_supported_yuv444_for_codec[2]) { codec_mode_flags |= SCM_AV1_HIGH8_444; } } if (video::active_av1_mode >= 3) { codec_mode_flags |= SCM_AV1_MAIN10; if (video::last_encoder_probe_supported_yuv444_for_codec[2]) { codec_mode_flags |= SCM_AV1_HIGH10_444; } } tree.put("root.ServerCodecModeSupport", codec_mode_flags); auto current_appid = proc::proc.running(); tree.put("root.PairStatus", pair_status); tree.put("root.currentgame", current_appid); tree.put("root.state", current_appid > 0 ? "SUNSHINE_SERVER_BUSY" : "SUNSHINE_SERVER_FREE"); std::ostringstream data; pt::write_xml(data, tree); response->write(data.str()); response->close_connection_after_response = true; } pt::ptree get_all_clients() { pt::ptree named_cert_nodes; client_t &client = client_root; for (auto &named_cert : client.named_devices) { pt::ptree named_cert_node; named_cert_node.put("name"s, named_cert.name); named_cert_node.put("uuid"s, named_cert.uuid); named_cert_nodes.push_back(std::make_pair(""s, named_cert_node)); } return named_cert_nodes; } void applist(resp_https_t response, req_https_t request) { print_req<SunshineHTTPS>(request); pt::ptree tree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_xml(data, tree); response->write(data.str()); response->close_connection_after_response = true; }); auto &apps = tree.add_child("root", pt::ptree {}); apps.put("<xmlattr>.status_code", 200); for (auto &proc : proc::proc.get_apps()) { pt::ptree app; app.put("IsHdrSupported"s, video::active_hevc_mode == 3 ? 1 : 0); app.put("AppTitle"s, proc.name); app.put("ID", proc.id); apps.push_back(std::make_pair("App", std::move(app))); } } void launch(bool &host_audio, resp_https_t response, req_https_t request) { print_req<SunshineHTTPS>(request); pt::ptree tree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_xml(data, tree); response->write(data.str()); response->close_connection_after_response = true; }); auto args = request->parse_query_string(); if ( args.find("rikey"s) == std::end(args) || args.find("rikeyid"s) == std::end(args) || args.find("localAudioPlayMode"s) == std::end(args) || args.find("appid"s) == std::end(args)) { tree.put("root.resume", 0); tree.put("root.<xmlattr>.status_code", 400); tree.put("root.<xmlattr>.status_message", "Missing a required launch parameter"); return; } auto appid = util::from_view(get_arg(args, "appid")); auto current_appid = proc::proc.running(); if (current_appid > 0) { tree.put("root.resume", 0); tree.put("root.<xmlattr>.status_code", 400); tree.put("root.<xmlattr>.status_message", "An app is already running on this host"); return; } // Probe encoders again before streaming to ensure our chosen // encoder matches the active GPU (which could have changed // due to hotplugging, driver crash, primary monitor change, // or any number of other factors). if (rtsp_stream::session_count() == 0) { if (video::probe_encoders()) { tree.put("root.<xmlattr>.status_code", 503); tree.put("root.<xmlattr>.status_message", "Failed to initialize video capture/encoding. Is a display connected and turned on?"); tree.put("root.gamesession", 0); return; } } host_audio = util::from_view(get_arg(args, "localAudioPlayMode")); auto launch_session = make_launch_session(host_audio, args); auto encryption_mode = net::encryption_mode_for_address(request->remote_endpoint().address()); if (!launch_session->rtsp_cipher && encryption_mode == config::ENCRYPTION_MODE_MANDATORY) { BOOST_LOG(error) << "Rejecting client that cannot comply with mandatory encryption requirement"sv; tree.put("root.<xmlattr>.status_code", 403); tree.put("root.<xmlattr>.status_message", "Encryption is mandatory for this host but unsupported by the client"); tree.put("root.gamesession", 0); return; } if (appid > 0) { auto err = proc::proc.execute(appid, launch_session); if (err) { tree.put("root.<xmlattr>.status_code", err); tree.put("root.<xmlattr>.status_message", "Failed to start the specified application"); tree.put("root.gamesession", 0); return; } } tree.put("root.<xmlattr>.status_code", 200); tree.put("root.sessionUrl0", launch_session->rtsp_url_scheme + net::addr_to_url_escaped_string(request->local_endpoint().address()) + ':' + std::to_string(net::map_port(rtsp_stream::RTSP_SETUP_PORT))); tree.put("root.gamesession", 1); rtsp_stream::launch_session_raise(launch_session); } void resume(bool &host_audio, resp_https_t response, req_https_t request) { print_req<SunshineHTTPS>(request); pt::ptree tree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_xml(data, tree); response->write(data.str()); response->close_connection_after_response = true; }); auto current_appid = proc::proc.running(); if (current_appid == 0) { tree.put("root.resume", 0); tree.put("root.<xmlattr>.status_code", 503); tree.put("root.<xmlattr>.status_message", "No running app to resume"); return; } auto args = request->parse_query_string(); if ( args.find("rikey"s) == std::end(args) || args.find("rikeyid"s) == std::end(args)) { tree.put("root.resume", 0); tree.put("root.<xmlattr>.status_code", 400); tree.put("root.<xmlattr>.status_message", "Missing a required resume parameter"); return; } if (rtsp_stream::session_count() == 0) { // Probe encoders again before streaming to ensure our chosen // encoder matches the active GPU (which could have changed // due to hotplugging, driver crash, primary monitor change, // or any number of other factors). if (video::probe_encoders()) { tree.put("root.resume", 0); tree.put("root.<xmlattr>.status_code", 503); tree.put("root.<xmlattr>.status_message", "Failed to initialize video capture/encoding. Is a display connected and turned on?"); return; } // Newer Moonlight clients send localAudioPlayMode on /resume too, // so we should use it if it's present in the args and there are // no active sessions we could be interfering with. if (args.find("localAudioPlayMode"s) != std::end(args)) { host_audio = util::from_view(get_arg(args, "localAudioPlayMode")); } } auto launch_session = make_launch_session(host_audio, args); auto encryption_mode = net::encryption_mode_for_address(request->remote_endpoint().address()); if (!launch_session->rtsp_cipher && encryption_mode == config::ENCRYPTION_MODE_MANDATORY) { BOOST_LOG(error) << "Rejecting client that cannot comply with mandatory encryption requirement"sv; tree.put("root.<xmlattr>.status_code", 403); tree.put("root.<xmlattr>.status_message", "Encryption is mandatory for this host but unsupported by the client"); tree.put("root.gamesession", 0); return; } tree.put("root.<xmlattr>.status_code", 200); tree.put("root.sessionUrl0", launch_session->rtsp_url_scheme + net::addr_to_url_escaped_string(request->local_endpoint().address()) + ':' + std::to_string(net::map_port(rtsp_stream::RTSP_SETUP_PORT))); tree.put("root.resume", 1); rtsp_stream::launch_session_raise(launch_session); } void cancel(resp_https_t response, req_https_t request) { print_req<SunshineHTTPS>(request); pt::ptree tree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_xml(data, tree); response->write(data.str()); response->close_connection_after_response = true; }); tree.put("root.cancel", 1); tree.put("root.<xmlattr>.status_code", 200); rtsp_stream::terminate_sessions(); if (proc::proc.running() > 0) { proc::proc.terminate(); } } void appasset(resp_https_t response, req_https_t request) { print_req<SunshineHTTPS>(request); auto args = request->parse_query_string(); auto app_image = proc::proc.get_app_image(util::from_view(get_arg(args, "appid"))); std::ifstream in(app_image, std::ios::binary); SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", "image/png"); response->write(SimpleWeb::StatusCode::success_ok, in, headers); response->close_connection_after_response = true; } void start() { auto shutdown_event = mail::man->event<bool>(mail::shutdown); auto port_http = net::map_port(PORT_HTTP); auto port_https = net::map_port(PORT_HTTPS); auto address_family = net::af_from_enum_string(config::sunshine.address_family); bool clean_slate = config::sunshine.flags[config::flag::FRESH_STATE]; if (!clean_slate) { load_state(); } conf_intern.pkey = file_handler::read_file(config::nvhttp.pkey.c_str()); conf_intern.servercert = file_handler::read_file(config::nvhttp.cert.c_str()); auto add_cert = std::make_shared<safe::queue_t<crypto::x509_t>>(30); // resume doesn't always get the parameter "localAudioPlayMode" // launch will store it in host_audio bool host_audio {}; https_server_t https_server { config::nvhttp.cert, config::nvhttp.pkey }; http_server_t http_server; // Verify certificates after establishing connection https_server.verify = [add_cert](SSL *ssl) { crypto::x509_t x509 { #if OPENSSL_VERSION_MAJOR >= 3 SSL_get1_peer_certificate(ssl) #else SSL_get_peer_certificate(ssl) #endif }; if (!x509) { BOOST_LOG(info) << "unknown -- denied"sv; return 0; } int verified = 0; auto fg = util::fail_guard([&]() { char subject_name[256]; X509_NAME_oneline(X509_get_subject_name(x509.get()), subject_name, sizeof(subject_name)); BOOST_LOG(debug) << subject_name << " -- "sv << (verified ? "verified"sv : "denied"sv); }); while (add_cert->peek()) { char subject_name[256]; auto cert = add_cert->pop(); X509_NAME_oneline(X509_get_subject_name(cert.get()), subject_name, sizeof(subject_name)); BOOST_LOG(debug) << "Added cert ["sv << subject_name << ']'; cert_chain.add(std::move(cert)); } auto err_str = cert_chain.verify(x509.get()); if (err_str) { BOOST_LOG(warning) << "SSL Verification error :: "sv << err_str; return verified; } verified = 1; return verified; }; https_server.on_verify_failed = [](resp_https_t resp, req_https_t req) { pt::ptree tree; auto g = util::fail_guard([&]() { std::ostringstream data; pt::write_xml(data, tree); resp->write(data.str()); resp->close_connection_after_response = true; }); tree.put("root.<xmlattr>.status_code"s, 401); tree.put("root.<xmlattr>.query"s, req->path); tree.put("root.<xmlattr>.status_message"s, "The client is not authorized. Certificate verification failed."s); }; https_server.default_resource["GET"] = not_found<SunshineHTTPS>; https_server.resource["^/serverinfo$"]["GET"] = serverinfo<SunshineHTTPS>; https_server.resource["^/pair$"]["GET"] = [&add_cert](auto resp, auto req) { pair<SunshineHTTPS>(add_cert, resp, req); }; https_server.resource["^/applist$"]["GET"] = applist; https_server.resource["^/appasset$"]["GET"] = appasset; https_server.resource["^/launch$"]["GET"] = [&host_audio](auto resp, auto req) { launch(host_audio, resp, req); }; https_server.resource["^/resume$"]["GET"] = [&host_audio](auto resp, auto req) { resume(host_audio, resp, req); }; https_server.resource["^/cancel$"]["GET"] = cancel; https_server.config.reuse_address = true; https_server.config.address = net::af_to_any_address_string(address_family); https_server.config.port = port_https; http_server.default_resource["GET"] = not_found<SimpleWeb::HTTP>; http_server.resource["^/serverinfo$"]["GET"] = serverinfo<SimpleWeb::HTTP>; http_server.resource["^/pair$"]["GET"] = [&add_cert](auto resp, auto req) { pair<SimpleWeb::HTTP>(add_cert, resp, req); }; http_server.config.reuse_address = true; http_server.config.address = net::af_to_any_address_string(address_family); http_server.config.port = port_http; auto accept_and_run = [&](auto *http_server) { try { http_server->start(); } catch (boost::system::system_error &err) { // It's possible the exception gets thrown after calling http_server->stop() from a different thread if (shutdown_event->peek()) { return; } BOOST_LOG(fatal) << "Couldn't start http server on ports ["sv << port_https << ", "sv << port_https << "]: "sv << err.what(); shutdown_event->raise(true); return; } }; std::thread ssl { accept_and_run, &https_server }; std::thread tcp { accept_and_run, &http_server }; // Wait for any event shutdown_event->view(); https_server.stop(); http_server.stop(); ssl.join(); tcp.join(); } void erase_all_clients() { client_t client; client_root = client; cert_chain.clear(); save_state(); } int unpair_client(std::string uuid) { int removed = 0; client_t &client = client_root; for (auto it = client.named_devices.begin(); it != client.named_devices.end();) { if ((*it).uuid == uuid) { it = client.named_devices.erase(it); removed++; } else { ++it; } } save_state(); load_state(); return removed; } } // namespace nvhttp
39,504
C++
.cpp
943
35.774125
206
0.642015
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,981
file_handler.cpp
LizardByte_Sunshine/src/file_handler.cpp
/** * @file file_handler.cpp * @brief Definitions for file handling functions. */ // standard includes #include <filesystem> #include <fstream> // local includes #include "file_handler.h" #include "logging.h" namespace file_handler { std::string get_parent_directory(const std::string &path) { // remove any trailing path separators std::string trimmed_path = path; while (!trimmed_path.empty() && trimmed_path.back() == '/') { trimmed_path.pop_back(); } std::filesystem::path p(trimmed_path); return p.parent_path().string(); } bool make_directory(const std::string &path) { // first, check if the directory already exists if (std::filesystem::exists(path)) { return true; } return std::filesystem::create_directories(path); } std::string read_file(const char *path) { if (!std::filesystem::exists(path)) { BOOST_LOG(debug) << "Missing file: " << path; return {}; } std::ifstream in(path); return std::string { (std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>() }; } int write_file(const char *path, const std::string_view &contents) { std::ofstream out(path); if (!out.is_open()) { return -1; } out << contents; return 0; } } // namespace file_handler
1,320
C++
.cpp
48
23.479167
98
0.653175
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,982
system_tray.cpp
LizardByte_Sunshine/src/system_tray.cpp
/** * @file src/system_tray.cpp * @brief Definitions for the system tray icon and notification system. */ // macros #if defined SUNSHINE_TRAY && SUNSHINE_TRAY >= 1 #if defined(_WIN32) #define WIN32_LEAN_AND_MEAN #include <accctrl.h> #include <aclapi.h> #define TRAY_ICON WEB_DIR "images/sunshine.ico" #define TRAY_ICON_PLAYING WEB_DIR "images/sunshine-playing.ico" #define TRAY_ICON_PAUSING WEB_DIR "images/sunshine-pausing.ico" #define TRAY_ICON_LOCKED WEB_DIR "images/sunshine-locked.ico" #elif defined(__linux__) || defined(linux) || defined(__linux) #define TRAY_ICON "sunshine-tray" #define TRAY_ICON_PLAYING "sunshine-playing" #define TRAY_ICON_PAUSING "sunshine-pausing" #define TRAY_ICON_LOCKED "sunshine-locked" #elif defined(__APPLE__) || defined(__MACH__) #define TRAY_ICON WEB_DIR "images/logo-sunshine-16.png" #define TRAY_ICON_PLAYING WEB_DIR "images/sunshine-playing-16.png" #define TRAY_ICON_PAUSING WEB_DIR "images/sunshine-pausing-16.png" #define TRAY_ICON_LOCKED WEB_DIR "images/sunshine-locked-16.png" #include <dispatch/dispatch.h> #endif // standard includes #include <csignal> #include <string> // lib includes #include "tray/src/tray.h" #include <boost/filesystem.hpp> #include <boost/process/v1/environment.hpp> // local includes #include "confighttp.h" #include "logging.h" #include "platform/common.h" #include "process.h" #include "src/entry_handler.h" #include "version.h" using namespace std::literals; // system_tray namespace namespace system_tray { static std::atomic<bool> tray_initialized = false; void tray_open_ui_cb(struct tray_menu *item) { BOOST_LOG(info) << "Opening UI from system tray"sv; launch_ui(); } void tray_donate_github_cb(struct tray_menu *item) { platf::open_url("https://github.com/sponsors/LizardByte"); } void tray_donate_patreon_cb(struct tray_menu *item) { platf::open_url("https://www.patreon.com/LizardByte"); } void tray_donate_paypal_cb(struct tray_menu *item) { platf::open_url("https://www.paypal.com/paypalme/ReenigneArcher"); } void tray_restart_cb(struct tray_menu *item) { BOOST_LOG(info) << "Restarting from system tray"sv; platf::restart(); } void tray_quit_cb(struct tray_menu *item) { BOOST_LOG(info) << "Quitting from system tray"sv; #ifdef _WIN32 // If we're running in a service, return a special status to // tell it to terminate too, otherwise it will just respawn us. if (GetConsoleWindow() == NULL) { lifetime::exit_sunshine(ERROR_SHUTDOWN_IN_PROGRESS, true); return; } #endif lifetime::exit_sunshine(0, true); } // Tray menu static struct tray tray = { .icon = TRAY_ICON, .tooltip = PROJECT_NAME, .menu = (struct tray_menu[]) { // todo - use boost/locale to translate menu strings { .text = "Open Sunshine", .cb = tray_open_ui_cb }, { .text = "-" }, { .text = "Donate", .submenu = (struct tray_menu[]) { { .text = "GitHub Sponsors", .cb = tray_donate_github_cb }, { .text = "Patreon", .cb = tray_donate_patreon_cb }, { .text = "PayPal", .cb = tray_donate_paypal_cb }, { .text = nullptr } } }, { .text = "-" }, { .text = "Restart", .cb = tray_restart_cb }, { .text = "Quit", .cb = tray_quit_cb }, { .text = nullptr } }, .iconPathCount = 4, .allIconPaths = { TRAY_ICON, TRAY_ICON_LOCKED, TRAY_ICON_PLAYING, TRAY_ICON_PAUSING }, }; int system_tray() { #ifdef _WIN32 // If we're running as SYSTEM, Explorer.exe will not have permission to open our thread handle // to monitor for thread termination. If Explorer fails to open our thread, our tray icon // will persist forever if we terminate unexpectedly. To avoid this, we will modify our thread // DACL to add an ACE that allows SYNCHRONIZE access to Everyone. { PACL old_dacl; PSECURITY_DESCRIPTOR sd; auto error = GetSecurityInfo(GetCurrentThread(), SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, nullptr, nullptr, &old_dacl, nullptr, &sd); if (error != ERROR_SUCCESS) { BOOST_LOG(warning) << "GetSecurityInfo() failed: "sv << error; return 1; } auto free_sd = util::fail_guard([sd]() { LocalFree(sd); }); SID_IDENTIFIER_AUTHORITY sid_authority = SECURITY_WORLD_SID_AUTHORITY; PSID world_sid; if (!AllocateAndInitializeSid(&sid_authority, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &world_sid)) { error = GetLastError(); BOOST_LOG(warning) << "AllocateAndInitializeSid() failed: "sv << error; return 1; } auto free_sid = util::fail_guard([world_sid]() { FreeSid(world_sid); }); EXPLICIT_ACCESS ea {}; ea.grfAccessPermissions = SYNCHRONIZE; ea.grfAccessMode = GRANT_ACCESS; ea.grfInheritance = NO_INHERITANCE; ea.Trustee.TrusteeForm = TRUSTEE_IS_SID; ea.Trustee.ptstrName = (LPSTR) world_sid; PACL new_dacl; error = SetEntriesInAcl(1, &ea, old_dacl, &new_dacl); if (error != ERROR_SUCCESS) { BOOST_LOG(warning) << "SetEntriesInAcl() failed: "sv << error; return 1; } auto free_new_dacl = util::fail_guard([new_dacl]() { LocalFree(new_dacl); }); error = SetSecurityInfo(GetCurrentThread(), SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, nullptr, nullptr, new_dacl, nullptr); if (error != ERROR_SUCCESS) { BOOST_LOG(warning) << "SetSecurityInfo() failed: "sv << error; return 1; } } // Wait for the shell to be initialized before registering the tray icon. // This ensures the tray icon works reliably after a logoff/logon cycle. while (GetShellWindow() == nullptr) { Sleep(1000); } #endif if (tray_init(&tray) < 0) { BOOST_LOG(warning) << "Failed to create system tray"sv; return 1; } else { BOOST_LOG(info) << "System tray created"sv; } tray_initialized = true; while (tray_loop(1) == 0) { BOOST_LOG(debug) << "System tray loop"sv; } return 0; } void run_tray() { // create the system tray #if defined(__APPLE__) || defined(__MACH__) // macOS requires that UI elements be created on the main thread // creating tray using dispatch queue does not work, although the code doesn't actually throw any (visible) errors // dispatch_async(dispatch_get_main_queue(), ^{ // system_tray(); // }); BOOST_LOG(info) << "system_tray() is not yet implemented for this platform."sv; #else // Windows, Linux // create tray in separate thread std::thread tray_thread(system_tray); tray_thread.detach(); #endif } int end_tray() { tray_initialized = false; tray_exit(); return 0; } void update_tray_playing(std::string app_name) { if (!tray_initialized) { return; } tray.notification_title = NULL; tray.notification_text = NULL; tray.notification_cb = NULL; tray.notification_icon = NULL; tray.icon = TRAY_ICON_PLAYING; tray_update(&tray); tray.icon = TRAY_ICON_PLAYING; tray.notification_title = "Stream Started"; char msg[256]; snprintf(msg, std::size(msg), "Streaming started for %s", app_name.c_str()); tray.notification_text = msg; tray.tooltip = msg; tray.notification_icon = TRAY_ICON_PLAYING; tray_update(&tray); } void update_tray_pausing(std::string app_name) { if (!tray_initialized) { return; } tray.notification_title = NULL; tray.notification_text = NULL; tray.notification_cb = NULL; tray.notification_icon = NULL; tray.icon = TRAY_ICON_PAUSING; tray_update(&tray); char msg[256]; snprintf(msg, std::size(msg), "Streaming paused for %s", app_name.c_str()); tray.icon = TRAY_ICON_PAUSING; tray.notification_title = "Stream Paused"; tray.notification_text = msg; tray.tooltip = msg; tray.notification_icon = TRAY_ICON_PAUSING; tray_update(&tray); } void update_tray_stopped(std::string app_name) { if (!tray_initialized) { return; } tray.notification_title = NULL; tray.notification_text = NULL; tray.notification_cb = NULL; tray.notification_icon = NULL; tray.icon = TRAY_ICON; tray_update(&tray); char msg[256]; snprintf(msg, std::size(msg), "Application %s successfully stopped", app_name.c_str()); tray.icon = TRAY_ICON; tray.notification_icon = TRAY_ICON; tray.notification_title = "Application Stopped"; tray.notification_text = msg; tray.tooltip = PROJECT_NAME; tray_update(&tray); } void update_tray_require_pin() { if (!tray_initialized) { return; } tray.notification_title = NULL; tray.notification_text = NULL; tray.notification_cb = NULL; tray.notification_icon = NULL; tray.icon = TRAY_ICON; tray_update(&tray); tray.icon = TRAY_ICON; tray.notification_title = "Incoming Pairing Request"; tray.notification_text = "Click here to complete the pairing process"; tray.notification_icon = TRAY_ICON_LOCKED; tray.tooltip = PROJECT_NAME; tray.notification_cb = []() { launch_ui_with_path("/pin"); }; tray_update(&tray); } } // namespace system_tray #endif
9,570
C++
.cpp
288
27.770833
118
0.644411
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,983
upnp.cpp
LizardByte_Sunshine/src/upnp.cpp
/** * @file src/upnp.cpp * @brief Definitions for UPnP port mapping. */ #include <miniupnpc/miniupnpc.h> #include <miniupnpc/upnpcommands.h> #include "config.h" #include "confighttp.h" #include "globals.h" #include "logging.h" #include "network.h" #include "nvhttp.h" #include "rtsp.h" #include "stream.h" #include "upnp.h" #include "utility.h" using namespace std::literals; namespace upnp { struct mapping_t { struct { std::string wan; std::string lan; std::string proto; } port; std::string description; }; static std::string_view status_string(int status) { switch (status) { case 0: return "No IGD device found"sv; case 1: return "Valid IGD device found"sv; case 2: return "Valid IGD device found, but it isn't connected"sv; case 3: return "A UPnP device has been found, but it wasn't recognized as an IGD"sv; } return "Unknown status"sv; } /** * This function is a wrapper around UPNP_GetValidIGD() that returns the status code. There is a pre-processor * check to determine which version of the function to call based on the version of the MiniUPnPc library. */ int UPNP_GetValidIGDStatus(device_t &device, urls_t *urls, IGDdatas *data, std::array<char, INET6_ADDRESS_STRLEN> &lan_addr) { #if (MINIUPNPC_API_VERSION >= 18) return UPNP_GetValidIGD(device.get(), &urls->el, data, lan_addr.data(), lan_addr.size(), nullptr, 0); #else return UPNP_GetValidIGD(device.get(), &urls->el, data, lan_addr.data(), lan_addr.size()); #endif } class deinit_t: public platf::deinit_t { public: deinit_t() { auto rtsp = std::to_string(net::map_port(rtsp_stream::RTSP_SETUP_PORT)); auto video = std::to_string(net::map_port(stream::VIDEO_STREAM_PORT)); auto audio = std::to_string(net::map_port(stream::AUDIO_STREAM_PORT)); auto control = std::to_string(net::map_port(stream::CONTROL_PORT)); auto gs_http = std::to_string(net::map_port(nvhttp::PORT_HTTP)); auto gs_https = std::to_string(net::map_port(nvhttp::PORT_HTTPS)); auto wm_http = std::to_string(net::map_port(confighttp::PORT_HTTPS)); mappings.assign({ { { rtsp, rtsp, "TCP"s }, "Sunshine - RTSP"s }, { { video, video, "UDP"s }, "Sunshine - Video"s }, { { audio, audio, "UDP"s }, "Sunshine - Audio"s }, { { control, control, "UDP"s }, "Sunshine - Control"s }, { { gs_http, gs_http, "TCP"s }, "Sunshine - Client HTTP"s }, { { gs_https, gs_https, "TCP"s }, "Sunshine - Client HTTPS"s }, }); // Only map port for the Web Manager if it is configured to accept connection from WAN if (net::from_enum_string(config::nvhttp.origin_web_ui_allowed) > net::LAN) { mappings.emplace_back(mapping_t { { wm_http, wm_http, "TCP"s }, "Sunshine - Web UI"s }); } // Start the mapping thread upnp_thread = std::thread { &deinit_t::upnp_thread_proc, this }; } ~deinit_t() { upnp_thread.join(); } /** * @brief Opens pinholes for IPv6 traffic if the IGD is capable. * @details Not many IGDs support this feature, so we perform error logging with debug level. * @return `true` if the pinholes were opened successfully. */ bool create_ipv6_pinholes() { int err; device_t device { upnpDiscover(2000, nullptr, nullptr, 0, IPv6, 2, &err) }; if (!device || err) { BOOST_LOG(debug) << "Couldn't discover any IPv6 UPNP devices"sv; return false; } IGDdatas data; urls_t urls; std::array<char, INET6_ADDRESS_STRLEN> lan_addr; auto status = upnp::UPNP_GetValidIGDStatus(device, &urls, &data, lan_addr); if (status != 1 && status != 2) { BOOST_LOG(debug) << "No valid IPv6 IGD: "sv << status_string(status); return false; } if (data.IPv6FC.controlurl[0] != 0) { int firewallEnabled, pinholeAllowed; // Check if this firewall supports IPv6 pinholes err = UPNP_GetFirewallStatus(urls->controlURL_6FC, data.IPv6FC.servicetype, &firewallEnabled, &pinholeAllowed); if (err == UPNPCOMMAND_SUCCESS) { BOOST_LOG(debug) << "UPnP IPv6 firewall control available. Firewall is "sv << (firewallEnabled ? "enabled"sv : "disabled"sv) << ", pinhole is "sv << (pinholeAllowed ? "allowed"sv : "disallowed"sv); if (pinholeAllowed) { // Create pinholes for each port auto mapping_period = std::to_string(PORT_MAPPING_LIFETIME.count()); auto shutdown_event = mail::man->event<bool>(mail::shutdown); for (auto it = std::begin(mappings); it != std::end(mappings) && !shutdown_event->peek(); ++it) { auto mapping = *it; char uniqueId[8]; // Open a pinhole for the LAN port, since there will be no WAN->LAN port mapping on IPv6 err = UPNP_AddPinhole(urls->controlURL_6FC, data.IPv6FC.servicetype, "", "0", lan_addr.data(), mapping.port.lan.c_str(), mapping.port.proto.c_str(), mapping_period.c_str(), uniqueId); if (err == UPNPCOMMAND_SUCCESS) { BOOST_LOG(debug) << "Successfully created pinhole for "sv << mapping.port.proto << ' ' << mapping.port.lan; } else { BOOST_LOG(debug) << "Failed to create pinhole for "sv << mapping.port.proto << ' ' << mapping.port.lan << ": "sv << err; } } return err == 0; } else { BOOST_LOG(debug) << "IPv6 pinholes are not allowed by the IGD"sv; return false; } } else { BOOST_LOG(debug) << "Failed to get IPv6 firewall status: "sv << err; return false; } } else { BOOST_LOG(debug) << "IPv6 Firewall Control is not supported by the IGD"sv; return false; } } /** * @brief Maps a port via UPnP. * @param data IGDdatas from UPNP_GetValidIGD() * @param urls urls_t from UPNP_GetValidIGD() * @param lan_addr Local IP address to map to * @param mapping Information about port to map * @return `true` on success. */ bool map_upnp_port(const IGDdatas &data, const urls_t &urls, const std::string &lan_addr, const mapping_t &mapping) { char intClient[16]; char intPort[6]; char desc[80]; char enabled[4]; char leaseDuration[16]; bool indefinite = false; // First check if this port is already mapped successfully BOOST_LOG(debug) << "Checking for existing UPnP port mapping for "sv << mapping.port.wan; auto err = UPNP_GetSpecificPortMappingEntry( urls->controlURL, data.first.servicetype, // In params mapping.port.wan.c_str(), mapping.port.proto.c_str(), nullptr, // Out params intClient, intPort, desc, enabled, leaseDuration); if (err == 714) { // NoSuchEntryInArray BOOST_LOG(debug) << "Mapping entry not found for "sv << mapping.port.wan; } else if (err == UPNPCOMMAND_SUCCESS) { // Some routers change the description, so we can't check that here if (!std::strcmp(intClient, lan_addr.c_str())) { if (std::atoi(leaseDuration) == 0) { BOOST_LOG(debug) << "Static mapping entry found for "sv << mapping.port.wan; // It's a static mapping, so we're done here return true; } else { BOOST_LOG(debug) << "Mapping entry found for "sv << mapping.port.wan << " ("sv << leaseDuration << " seconds remaining)"sv; } } else { BOOST_LOG(warning) << "UPnP conflict detected with: "sv << intClient; // Some UPnP IGDs won't let unauthenticated clients delete other conflicting port mappings // for security reasons, but we will give it a try anyway. err = UPNP_DeletePortMapping( urls->controlURL, data.first.servicetype, mapping.port.wan.c_str(), mapping.port.proto.c_str(), nullptr); if (err) { BOOST_LOG(error) << "Unable to delete conflicting UPnP port mapping: "sv << err; return false; } } } else { BOOST_LOG(error) << "UPNP_GetSpecificPortMappingEntry() failed: "sv << err; // If we get a strange error from the router, we'll assume it's some old broken IGDv1 // device and only use indefinite lease durations to hopefully avoid confusing it. if (err != 606) { // Unauthorized indefinite = true; } } // Add/update the port mapping auto mapping_period = std::to_string(indefinite ? 0 : PORT_MAPPING_LIFETIME.count()); err = UPNP_AddPortMapping( urls->controlURL, data.first.servicetype, mapping.port.wan.c_str(), mapping.port.lan.c_str(), lan_addr.data(), mapping.description.c_str(), mapping.port.proto.c_str(), nullptr, mapping_period.c_str()); if (err != UPNPCOMMAND_SUCCESS && !indefinite) { // This may be an old/broken IGD that doesn't like non-static mappings. BOOST_LOG(debug) << "Trying static mapping after failure: "sv << err; err = UPNP_AddPortMapping( urls->controlURL, data.first.servicetype, mapping.port.wan.c_str(), mapping.port.lan.c_str(), lan_addr.data(), mapping.description.c_str(), mapping.port.proto.c_str(), nullptr, "0"); } if (err) { BOOST_LOG(error) << "Failed to map "sv << mapping.port.proto << ' ' << mapping.port.lan << ": "sv << err; return false; } BOOST_LOG(debug) << "Successfully mapped "sv << mapping.port.proto << ' ' << mapping.port.lan; return true; } /** * @brief Unmaps all ports. * @param urls urls_t from UPNP_GetValidIGD() * @param data IGDdatas from UPNP_GetValidIGD() */ void unmap_all_upnp_ports(const urls_t &urls, const IGDdatas &data) { for (auto it = std::begin(mappings); it != std::end(mappings); ++it) { auto status = UPNP_DeletePortMapping( urls->controlURL, data.first.servicetype, it->port.wan.c_str(), it->port.proto.c_str(), nullptr); if (status && status != 714) { // NoSuchEntryInArray BOOST_LOG(warning) << "Failed to unmap "sv << it->port.proto << ' ' << it->port.lan << ": "sv << status; } else { BOOST_LOG(debug) << "Successfully unmapped "sv << it->port.proto << ' ' << it->port.lan; } } } /** * @brief Maintains UPnP port forwarding rules */ void upnp_thread_proc() { auto shutdown_event = mail::man->event<bool>(mail::shutdown); bool mapped = false; IGDdatas data; urls_t mapped_urls; auto address_family = net::af_from_enum_string(config::sunshine.address_family); // Refresh UPnP rules every few minutes. They can be lost if the router reboots, // WAN IP address changes, or various other conditions. do { int err = 0; device_t device { upnpDiscover(2000, nullptr, nullptr, 0, IPv4, 2, &err) }; if (!device || err) { BOOST_LOG(warning) << "Couldn't discover any IPv4 UPNP devices"sv; mapped = false; continue; } for (auto dev = device.get(); dev != nullptr; dev = dev->pNext) { BOOST_LOG(debug) << "Found device: "sv << dev->descURL; } std::array<char, INET6_ADDRESS_STRLEN> lan_addr; urls_t urls; auto status = upnp::UPNP_GetValidIGDStatus(device, &urls, &data, lan_addr); if (status != 1 && status != 2) { BOOST_LOG(error) << status_string(status); mapped = false; continue; } std::string lan_addr_str { lan_addr.data() }; BOOST_LOG(debug) << "Found valid IGD device: "sv << urls->rootdescURL; for (auto it = std::begin(mappings); it != std::end(mappings) && !shutdown_event->peek(); ++it) { map_upnp_port(data, urls, lan_addr_str, *it); } if (!mapped) { BOOST_LOG(info) << "Completed UPnP port mappings to "sv << lan_addr_str << " via "sv << urls->rootdescURL; } // If we are listening on IPv6 and the IGD has an IPv6 firewall enabled, try to create IPv6 firewall pinholes if (address_family == net::af_e::BOTH) { if (create_ipv6_pinholes() && !mapped) { // Only log the first time through BOOST_LOG(info) << "Successfully opened IPv6 pinholes on the IGD"sv; } } mapped = true; mapped_urls = std::move(urls); } while (!shutdown_event->view(REFRESH_INTERVAL)); if (mapped) { // Unmap ports upon termination BOOST_LOG(info) << "Unmapping UPNP ports..."sv; unmap_all_upnp_ports(mapped_urls, data); } } std::vector<mapping_t> mappings; std::thread upnp_thread; }; std::unique_ptr<platf::deinit_t> start() { if (!config::sunshine.flags[config::flag::UPNP]) { return nullptr; } return std::make_unique<deinit_t>(); } } // namespace upnp
13,607
C++
.cpp
337
32.002967
136
0.587537
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,984
process.cpp
LizardByte_Sunshine/src/process.cpp
/** * @file src/process.cpp * @brief Definitions for the startup and shutdown of the apps started by a streaming Session. */ #define BOOST_BIND_GLOBAL_PLACEHOLDERS #include "process.h" #include <filesystem> #include <string> #include <thread> #include <vector> #include <boost/algorithm/string.hpp> #include <boost/crc.hpp> #include <boost/filesystem.hpp> #include <boost/program_options/parsers.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <openssl/evp.h> #include <openssl/sha.h> #include "config.h" #include "crypto.h" #include "logging.h" #include "platform/common.h" #include "system_tray.h" #include "utility.h" #ifdef _WIN32 // from_utf8() string conversion function #include "platform/windows/misc.h" // _SH constants for _wfsopen() #include <share.h> #endif #define DEFAULT_APP_IMAGE_PATH SUNSHINE_ASSETS_DIR "/box.png" namespace proc { using namespace std::literals; namespace pt = boost::property_tree; proc_t proc; class deinit_t: public platf::deinit_t { public: ~deinit_t() { proc.terminate(); } }; std::unique_ptr<platf::deinit_t> init() { return std::make_unique<deinit_t>(); } void terminate_process_group(boost::process::v1::child &proc, boost::process::v1::group &group, std::chrono::seconds exit_timeout) { if (group.valid() && platf::process_group_running((std::uintptr_t) group.native_handle())) { if (exit_timeout.count() > 0) { // Request processes in the group to exit gracefully if (platf::request_process_group_exit((std::uintptr_t) group.native_handle())) { // If the request was successful, wait for a little while for them to exit. BOOST_LOG(info) << "Successfully requested the app to exit. Waiting up to "sv << exit_timeout.count() << " seconds for it to close."sv; // group::wait_for() and similar functions are broken and deprecated, so we use a simple polling loop while (platf::process_group_running((std::uintptr_t) group.native_handle()) && (--exit_timeout).count() >= 0) { std::this_thread::sleep_for(1s); } if (exit_timeout.count() < 0) { BOOST_LOG(warning) << "App did not fully exit within the timeout. Terminating the app's remaining processes."sv; } else { BOOST_LOG(info) << "All app processes have successfully exited."sv; } } else { BOOST_LOG(info) << "App did not respond to a graceful termination request. Forcefully terminating the app's processes."sv; } } else { BOOST_LOG(info) << "No graceful exit timeout was specified for this app. Forcefully terminating the app's processes."sv; } // We always call terminate() even if we waited successfully for all processes above. // This ensures the process group state is consistent with the OS in boost. std::error_code ec; group.terminate(ec); group.detach(); } if (proc.valid()) { // avoid zombie process proc.detach(); } } boost::filesystem::path find_working_directory(const std::string &cmd, boost::process::v1::environment &env) { // Parse the raw command string into parts to get the actual command portion #ifdef _WIN32 auto parts = boost::program_options::split_winmain(cmd); #else auto parts = boost::program_options::split_unix(cmd); #endif if (parts.empty()) { BOOST_LOG(error) << "Unable to parse command: "sv << cmd; return boost::filesystem::path(); } BOOST_LOG(debug) << "Parsed target ["sv << parts.at(0) << "] from command ["sv << cmd << ']'; // If the target is a URL, don't parse any further here if (parts.at(0).find("://") != std::string::npos) { return boost::filesystem::path(); } // If the cmd path is not an absolute path, resolve it using our PATH variable boost::filesystem::path cmd_path(parts.at(0)); if (!cmd_path.is_absolute()) { cmd_path = boost::process::v1::search_path(parts.at(0)); if (cmd_path.empty()) { BOOST_LOG(error) << "Unable to find executable ["sv << parts.at(0) << "]. Is it in your PATH?"sv; return boost::filesystem::path(); } } BOOST_LOG(debug) << "Resolved target ["sv << parts.at(0) << "] to path ["sv << cmd_path << ']'; // Now that we have a complete path, we can just use parent_path() return cmd_path.parent_path(); } int proc_t::execute(int app_id, std::shared_ptr<rtsp_stream::launch_session_t> launch_session) { // Ensure starting from a clean slate terminate(); auto iter = std::find_if(_apps.begin(), _apps.end(), [&app_id](const auto app) { return app.id == std::to_string(app_id); }); if (iter == _apps.end()) { BOOST_LOG(error) << "Couldn't find app with ID ["sv << app_id << ']'; return 404; } _app_id = app_id; _app = *iter; _app_prep_begin = std::begin(_app.prep_cmds); _app_prep_it = _app_prep_begin; // Add Stream-specific environment variables _env["SUNSHINE_APP_ID"] = std::to_string(_app_id); _env["SUNSHINE_APP_NAME"] = _app.name; _env["SUNSHINE_CLIENT_WIDTH"] = std::to_string(launch_session->width); _env["SUNSHINE_CLIENT_HEIGHT"] = std::to_string(launch_session->height); _env["SUNSHINE_CLIENT_FPS"] = std::to_string(launch_session->fps); _env["SUNSHINE_CLIENT_HDR"] = launch_session->enable_hdr ? "true" : "false"; _env["SUNSHINE_CLIENT_GCMAP"] = std::to_string(launch_session->gcmap); _env["SUNSHINE_CLIENT_HOST_AUDIO"] = launch_session->host_audio ? "true" : "false"; _env["SUNSHINE_CLIENT_ENABLE_SOPS"] = launch_session->enable_sops ? "true" : "false"; int channelCount = launch_session->surround_info & (65535); switch (channelCount) { case 2: _env["SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] = "2.0"; break; case 6: _env["SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] = "5.1"; break; case 8: _env["SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] = "7.1"; break; } _env["SUNSHINE_CLIENT_AUDIO_SURROUND_PARAMS"] = launch_session->surround_params; if (!_app.output.empty() && _app.output != "null"sv) { #ifdef _WIN32 // fopen() interprets the filename as an ANSI string on Windows, so we must convert it // to UTF-16 and use the wchar_t variants for proper Unicode log file path support. auto woutput = platf::from_utf8(_app.output); // Use _SH_DENYNO to allow us to open this log file again for writing even if it is // still open from a previous execution. This is required to handle the case of a // detached process executing again while the previous process is still running. _pipe.reset(_wfsopen(woutput.c_str(), L"a", _SH_DENYNO)); #else _pipe.reset(fopen(_app.output.c_str(), "a")); #endif } std::error_code ec; // Executed when returning from function auto fg = util::fail_guard([&]() { terminate(); }); for (; _app_prep_it != std::end(_app.prep_cmds); ++_app_prep_it) { auto &cmd = *_app_prep_it; // Skip empty commands if (cmd.do_cmd.empty()) { continue; } boost::filesystem::path working_dir = _app.working_dir.empty() ? find_working_directory(cmd.do_cmd, _env) : boost::filesystem::path(_app.working_dir); BOOST_LOG(info) << "Executing Do Cmd: ["sv << cmd.do_cmd << ']'; auto child = platf::run_command(cmd.elevated, true, cmd.do_cmd, working_dir, _env, _pipe.get(), ec, nullptr); if (ec) { BOOST_LOG(error) << "Couldn't run ["sv << cmd.do_cmd << "]: System: "sv << ec.message(); // We don't want any prep commands failing launch of the desktop. // This is to prevent the issue where users reboot their PC and need to log in with Sunshine. // permission_denied is typically returned when the user impersonation fails, which can happen when user is not signed in yet. if (!(_app.cmd.empty() && ec == std::errc::permission_denied)) { return -1; } } child.wait(); auto ret = child.exit_code(); if (ret != 0 && ec != std::errc::permission_denied) { BOOST_LOG(error) << '[' << cmd.do_cmd << "] failed with code ["sv << ret << ']'; return -1; } } for (auto &cmd : _app.detached) { boost::filesystem::path working_dir = _app.working_dir.empty() ? find_working_directory(cmd, _env) : boost::filesystem::path(_app.working_dir); BOOST_LOG(info) << "Spawning ["sv << cmd << "] in ["sv << working_dir << ']'; auto child = platf::run_command(_app.elevated, true, cmd, working_dir, _env, _pipe.get(), ec, nullptr); if (ec) { BOOST_LOG(warning) << "Couldn't spawn ["sv << cmd << "]: System: "sv << ec.message(); } else { child.detach(); } } if (_app.cmd.empty()) { BOOST_LOG(info) << "Executing [Desktop]"sv; placebo = true; } else { boost::filesystem::path working_dir = _app.working_dir.empty() ? find_working_directory(_app.cmd, _env) : boost::filesystem::path(_app.working_dir); BOOST_LOG(info) << "Executing: ["sv << _app.cmd << "] in ["sv << working_dir << ']'; _process = platf::run_command(_app.elevated, true, _app.cmd, working_dir, _env, _pipe.get(), ec, &_process_group); if (ec) { BOOST_LOG(warning) << "Couldn't run ["sv << _app.cmd << "]: System: "sv << ec.message(); return -1; } } _app_launch_time = std::chrono::steady_clock::now(); fg.disable(); return 0; } int proc_t::running() { #ifndef _WIN32 // On POSIX OSes, we must periodically wait for our children to avoid // them becoming zombies. This must be synchronized carefully with // calls to bp::wait() and platf::process_group_running() which both // invoke waitpid() under the hood. auto reaper = util::fail_guard([]() { while (waitpid(-1, nullptr, WNOHANG) > 0); }); #endif if (placebo) { return _app_id; } else if (_app.wait_all && _process_group && platf::process_group_running((std::uintptr_t) _process_group.native_handle())) { // The app is still running if any process in the group is still running return _app_id; } else if (_process.running()) { // The app is still running only if the initial process launched is still running return _app_id; } else if (_app.auto_detach && _process.native_exit_code() == 0 && std::chrono::steady_clock::now() - _app_launch_time < 5s) { BOOST_LOG(info) << "App exited gracefully within 5 seconds of launch. Treating the app as a detached command."sv; BOOST_LOG(info) << "Adjust this behavior in the Applications tab or apps.json if this is not what you want."sv; placebo = true; return _app_id; } // Perform cleanup actions now if needed if (_process) { BOOST_LOG(info) << "App exited with code ["sv << _process.native_exit_code() << ']'; terminate(); } return 0; } void proc_t::terminate() { std::error_code ec; placebo = false; terminate_process_group(_process, _process_group, _app.exit_timeout); _process = boost::process::v1::child(); _process_group = boost::process::v1::group(); for (; _app_prep_it != _app_prep_begin; --_app_prep_it) { auto &cmd = *(_app_prep_it - 1); if (cmd.undo_cmd.empty()) { continue; } boost::filesystem::path working_dir = _app.working_dir.empty() ? find_working_directory(cmd.undo_cmd, _env) : boost::filesystem::path(_app.working_dir); BOOST_LOG(info) << "Executing Undo Cmd: ["sv << cmd.undo_cmd << ']'; auto child = platf::run_command(cmd.elevated, true, cmd.undo_cmd, working_dir, _env, _pipe.get(), ec, nullptr); if (ec) { BOOST_LOG(warning) << "System: "sv << ec.message(); } child.wait(); auto ret = child.exit_code(); if (ret != 0) { BOOST_LOG(warning) << "Return code ["sv << ret << ']'; } } _pipe.reset(); #if defined SUNSHINE_TRAY && SUNSHINE_TRAY >= 1 bool has_run = _app_id > 0; // Only show the Stopped notification if we actually have an app to stop // Since terminate() is always run when a new app has started if (proc::proc.get_last_run_app_name().length() > 0 && has_run) { system_tray::update_tray_stopped(proc::proc.get_last_run_app_name()); } #endif _app_id = -1; } const std::vector<ctx_t> & proc_t::get_apps() const { return _apps; } std::vector<ctx_t> & proc_t::get_apps() { return _apps; } // Gets application image from application list. // Returns image from assets directory if found there. // Returns default image if image configuration is not set. // Returns http content-type header compatible image type. std::string proc_t::get_app_image(int app_id) { auto iter = std::find_if(_apps.begin(), _apps.end(), [&app_id](const auto app) { return app.id == std::to_string(app_id); }); auto app_image_path = iter == _apps.end() ? std::string() : iter->image_path; return validate_app_image_path(app_image_path); } std::string proc_t::get_last_run_app_name() { return _app.name; } proc_t::~proc_t() { // It's not safe to call terminate() here because our proc_t is a static variable // that may be destroyed after the Boost loggers have been destroyed. Instead, // we return a deinit_t to main() to handle termination when we're exiting. // Once we reach this point here, termination must have already happened. assert(!placebo); assert(!_process.running()); } std::string_view::iterator find_match(std::string_view::iterator begin, std::string_view::iterator end) { int stack = 0; --begin; do { ++begin; switch (*begin) { case '(': ++stack; break; case ')': --stack; } } while (begin != end && stack != 0); if (begin == end) { throw std::out_of_range("Missing closing bracket \')\'"); } return begin; } std::string parse_env_val(boost::process::v1::native_environment &env, const std::string_view &val_raw) { auto pos = std::begin(val_raw); auto dollar = std::find(pos, std::end(val_raw), '$'); std::stringstream ss; while (dollar != std::end(val_raw)) { auto next = dollar + 1; if (next != std::end(val_raw)) { switch (*next) { case '(': { ss.write(pos, (dollar - pos)); auto var_begin = next + 1; auto var_end = find_match(next, std::end(val_raw)); auto var_name = std::string { var_begin, var_end }; #ifdef _WIN32 // Windows treats environment variable names in a case-insensitive manner, // so we look for a case-insensitive match here. This is critical for // correctly appending to PATH on Windows. auto itr = std::find_if(env.cbegin(), env.cend(), [&](const auto &e) { return boost::iequals(e.get_name(), var_name); }); if (itr != env.cend()) { // Use an existing case-insensitive match var_name = itr->get_name(); } #endif ss << env[var_name].to_string(); pos = var_end + 1; next = var_end; break; } case '$': ss.write(pos, (next - pos)); pos = next + 1; ++next; break; } dollar = std::find(next, std::end(val_raw), '$'); } else { dollar = next; } } ss.write(pos, (dollar - pos)); return ss.str(); } std::string validate_app_image_path(std::string app_image_path) { if (app_image_path.empty()) { return DEFAULT_APP_IMAGE_PATH; } // get the image extension and convert it to lowercase auto image_extension = std::filesystem::path(app_image_path).extension().string(); boost::to_lower(image_extension); // return the default box image if extension is not "png" if (image_extension != ".png") { return DEFAULT_APP_IMAGE_PATH; } // check if image is in assets directory auto full_image_path = std::filesystem::path(SUNSHINE_ASSETS_DIR) / app_image_path; if (std::filesystem::exists(full_image_path)) { return full_image_path.string(); } else if (app_image_path == "./assets/steam.png") { // handle old default steam image definition return SUNSHINE_ASSETS_DIR "/steam.png"; } // check if specified image exists std::error_code code; if (!std::filesystem::exists(app_image_path, code)) { // return default box image if image does not exist BOOST_LOG(warning) << "Couldn't find app image at path ["sv << app_image_path << ']'; return DEFAULT_APP_IMAGE_PATH; } // image is a png, and not in assets directory // return only "content-type" http header compatible image type return app_image_path; } std::optional<std::string> calculate_sha256(const std::string &filename) { crypto::md_ctx_t ctx { EVP_MD_CTX_create() }; if (!ctx) { return std::nullopt; } if (!EVP_DigestInit_ex(ctx.get(), EVP_sha256(), nullptr)) { return std::nullopt; } // Read file and update calculated SHA char buf[1024 * 16]; std::ifstream file(filename, std::ifstream::binary); while (file.good()) { file.read(buf, sizeof(buf)); if (!EVP_DigestUpdate(ctx.get(), buf, file.gcount())) { return std::nullopt; } } file.close(); unsigned char result[SHA256_DIGEST_LENGTH]; if (!EVP_DigestFinal_ex(ctx.get(), result, nullptr)) { return std::nullopt; } // Transform byte-array to string std::stringstream ss; ss << std::hex << std::setfill('0'); for (const auto &byte : result) { ss << std::setw(2) << (int) byte; } return ss.str(); } uint32_t calculate_crc32(const std::string &input) { boost::crc_32_type result; result.process_bytes(input.data(), input.length()); return result.checksum(); } std::tuple<std::string, std::string> calculate_app_id(const std::string &app_name, std::string app_image_path, int index) { // Generate id by hashing name with image data if present std::vector<std::string> to_hash; to_hash.push_back(app_name); auto file_path = validate_app_image_path(app_image_path); if (file_path != DEFAULT_APP_IMAGE_PATH) { auto file_hash = calculate_sha256(file_path); if (file_hash) { to_hash.push_back(file_hash.value()); } else { // Fallback to just hashing image path to_hash.push_back(file_path); } } // Create combined strings for hash std::stringstream ss; for_each(to_hash.begin(), to_hash.end(), [&ss](const std::string &s) { ss << s; }); auto input_no_index = ss.str(); ss << index; auto input_with_index = ss.str(); // CRC32 then truncate to signed 32-bit range due to client limitations auto id_no_index = std::to_string(abs((int32_t) calculate_crc32(input_no_index))); auto id_with_index = std::to_string(abs((int32_t) calculate_crc32(input_with_index))); return std::make_tuple(id_no_index, id_with_index); } std::optional<proc::proc_t> parse(const std::string &file_name) { pt::ptree tree; try { pt::read_json(file_name, tree); auto &apps_node = tree.get_child("apps"s); auto &env_vars = tree.get_child("env"s); auto this_env = boost::this_process::environment(); for (auto &[name, val] : env_vars) { this_env[name] = parse_env_val(this_env, val.get_value<std::string>()); } std::set<std::string> ids; std::vector<proc::ctx_t> apps; int i = 0; for (auto &[_, app_node] : apps_node) { proc::ctx_t ctx; auto prep_nodes_opt = app_node.get_child_optional("prep-cmd"s); auto detached_nodes_opt = app_node.get_child_optional("detached"s); auto exclude_global_prep = app_node.get_optional<bool>("exclude-global-prep-cmd"s); auto output = app_node.get_optional<std::string>("output"s); auto name = parse_env_val(this_env, app_node.get<std::string>("name"s)); auto cmd = app_node.get_optional<std::string>("cmd"s); auto image_path = app_node.get_optional<std::string>("image-path"s); auto working_dir = app_node.get_optional<std::string>("working-dir"s); auto elevated = app_node.get_optional<bool>("elevated"s); auto auto_detach = app_node.get_optional<bool>("auto-detach"s); auto wait_all = app_node.get_optional<bool>("wait-all"s); auto exit_timeout = app_node.get_optional<int>("exit-timeout"s); std::vector<proc::cmd_t> prep_cmds; if (!exclude_global_prep.value_or(false)) { prep_cmds.reserve(config::sunshine.prep_cmds.size()); for (auto &prep_cmd : config::sunshine.prep_cmds) { auto do_cmd = parse_env_val(this_env, prep_cmd.do_cmd); auto undo_cmd = parse_env_val(this_env, prep_cmd.undo_cmd); prep_cmds.emplace_back( std::move(do_cmd), std::move(undo_cmd), std::move(prep_cmd.elevated)); } } if (prep_nodes_opt) { auto &prep_nodes = *prep_nodes_opt; prep_cmds.reserve(prep_cmds.size() + prep_nodes.size()); for (auto &[_, prep_node] : prep_nodes) { auto do_cmd = prep_node.get_optional<std::string>("do"s); auto undo_cmd = prep_node.get_optional<std::string>("undo"s); auto elevated = prep_node.get_optional<bool>("elevated"); prep_cmds.emplace_back( parse_env_val(this_env, do_cmd.value_or("")), parse_env_val(this_env, undo_cmd.value_or("")), std::move(elevated.value_or(false))); } } std::vector<std::string> detached; if (detached_nodes_opt) { auto &detached_nodes = *detached_nodes_opt; detached.reserve(detached_nodes.size()); for (auto &[_, detached_val] : detached_nodes) { detached.emplace_back(parse_env_val(this_env, detached_val.get_value<std::string>())); } } if (output) { ctx.output = parse_env_val(this_env, *output); } if (cmd) { ctx.cmd = parse_env_val(this_env, *cmd); } if (working_dir) { ctx.working_dir = parse_env_val(this_env, *working_dir); #ifdef _WIN32 // The working directory, unlike the command itself, should not be quoted // when it contains spaces. Unlike POSIX, Windows forbids quotes in paths, // so we can safely strip them all out here to avoid confusing the user. boost::erase_all(ctx.working_dir, "\""); #endif } if (image_path) { ctx.image_path = parse_env_val(this_env, *image_path); } ctx.elevated = elevated.value_or(false); ctx.auto_detach = auto_detach.value_or(true); ctx.wait_all = wait_all.value_or(true); ctx.exit_timeout = std::chrono::seconds { exit_timeout.value_or(5) }; auto possible_ids = calculate_app_id(name, ctx.image_path, i++); if (ids.count(std::get<0>(possible_ids)) == 0) { // Avoid using index to generate id if possible ctx.id = std::get<0>(possible_ids); } else { // Fallback to include index on collision ctx.id = std::get<1>(possible_ids); } ids.insert(ctx.id); ctx.name = std::move(name); ctx.prep_cmds = std::move(prep_cmds); ctx.detached = std::move(detached); apps.emplace_back(std::move(ctx)); } return proc::proc_t { std::move(this_env), std::move(apps) }; } catch (std::exception &e) { BOOST_LOG(error) << e.what(); } return std::nullopt; } void refresh(const std::string &file_name) { auto proc_opt = proc::parse(file_name); if (proc_opt) { proc = std::move(*proc_opt); } } } // namespace proc
24,695
C++
.cpp
607
33.520593
145
0.601927
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,985
globals.cpp
LizardByte_Sunshine/src/globals.cpp
/** * @file globals.cpp * @brief Definitions for globally accessible variables and functions. */ #include "globals.h" safe::mail_t mail::man; thread_pool_util::ThreadPool task_pool; bool display_cursor = true; #ifdef _WIN32 nvprefs::nvprefs_interface nvprefs_instance; #endif
281
C++
.cpp
11
24.090909
70
0.779851
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,986
video_colorspace.cpp
LizardByte_Sunshine/src/video_colorspace.cpp
/** * @file src/video_colorspace.cpp * @brief Definitions for colorspace functions. */ #include "video_colorspace.h" #include "logging.h" #include "video.h" extern "C" { #include <libswscale/swscale.h> } namespace video { bool colorspace_is_hdr(const sunshine_colorspace_t &colorspace) { return colorspace.colorspace == colorspace_e::bt2020; } sunshine_colorspace_t colorspace_from_client_config(const config_t &config, bool hdr_display) { sunshine_colorspace_t colorspace; /* See video::config_t declaration for details */ if (config.dynamicRange > 0 && hdr_display) { // Rec. 2020 with ST 2084 perceptual quantizer colorspace.colorspace = colorspace_e::bt2020; } else { switch (config.encoderCscMode >> 1) { case 0: // Rec. 601 colorspace.colorspace = colorspace_e::rec601; break; case 1: // Rec. 709 colorspace.colorspace = colorspace_e::rec709; break; case 2: // Rec. 2020 colorspace.colorspace = colorspace_e::bt2020sdr; break; default: BOOST_LOG(error) << "Unknown video colorspace in csc, falling back to Rec. 709"; colorspace.colorspace = colorspace_e::rec709; break; } } colorspace.full_range = (config.encoderCscMode & 0x1); switch (config.dynamicRange) { case 0: colorspace.bit_depth = 8; break; case 1: colorspace.bit_depth = 10; break; default: BOOST_LOG(error) << "Unknown dynamicRange value, falling back to 10-bit color depth"; colorspace.bit_depth = 10; break; } if (colorspace.colorspace == colorspace_e::bt2020sdr && colorspace.bit_depth != 10) { BOOST_LOG(error) << "BT.2020 SDR colorspace expects 10-bit color depth, falling back to Rec. 709"; colorspace.colorspace = colorspace_e::rec709; } return colorspace; } avcodec_colorspace_t avcodec_colorspace_from_sunshine_colorspace(const sunshine_colorspace_t &sunshine_colorspace) { avcodec_colorspace_t avcodec_colorspace; switch (sunshine_colorspace.colorspace) { case colorspace_e::rec601: // Rec. 601 avcodec_colorspace.primaries = AVCOL_PRI_SMPTE170M; avcodec_colorspace.transfer_function = AVCOL_TRC_SMPTE170M; avcodec_colorspace.matrix = AVCOL_SPC_SMPTE170M; avcodec_colorspace.software_format = SWS_CS_SMPTE170M; break; case colorspace_e::rec709: // Rec. 709 avcodec_colorspace.primaries = AVCOL_PRI_BT709; avcodec_colorspace.transfer_function = AVCOL_TRC_BT709; avcodec_colorspace.matrix = AVCOL_SPC_BT709; avcodec_colorspace.software_format = SWS_CS_ITU709; break; case colorspace_e::bt2020sdr: // Rec. 2020 avcodec_colorspace.primaries = AVCOL_PRI_BT2020; assert(sunshine_colorspace.bit_depth == 10); avcodec_colorspace.transfer_function = AVCOL_TRC_BT2020_10; avcodec_colorspace.matrix = AVCOL_SPC_BT2020_NCL; avcodec_colorspace.software_format = SWS_CS_BT2020; break; case colorspace_e::bt2020: // Rec. 2020 with ST 2084 perceptual quantizer avcodec_colorspace.primaries = AVCOL_PRI_BT2020; assert(sunshine_colorspace.bit_depth == 10); avcodec_colorspace.transfer_function = AVCOL_TRC_SMPTE2084; avcodec_colorspace.matrix = AVCOL_SPC_BT2020_NCL; avcodec_colorspace.software_format = SWS_CS_BT2020; break; } avcodec_colorspace.range = sunshine_colorspace.full_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; return avcodec_colorspace; } const color_t * color_vectors_from_colorspace(const sunshine_colorspace_t &colorspace) { return color_vectors_from_colorspace(colorspace.colorspace, colorspace.full_range); } const color_t * color_vectors_from_colorspace(colorspace_e colorspace, bool full_range) { using float2 = float[2]; auto make_color_matrix = [](float Cr, float Cb, const float2 &range_Y, const float2 &range_UV) -> color_t { float Cg = 1.0f - Cr - Cb; float Cr_i = 1.0f - Cr; float Cb_i = 1.0f - Cb; float shift_y = range_Y[0] / 255.0f; float shift_uv = range_UV[0] / 255.0f; float scale_y = (range_Y[1] - range_Y[0]) / 255.0f; float scale_uv = (range_UV[1] - range_UV[0]) / 255.0f; return { { Cr, Cg, Cb, 0.0f }, { -(Cr * 0.5f / Cb_i), -(Cg * 0.5f / Cb_i), 0.5f, 0.5f }, { 0.5f, -(Cg * 0.5f / Cr_i), -(Cb * 0.5f / Cr_i), 0.5f }, { scale_y, shift_y }, { scale_uv, shift_uv }, }; }; static const color_t colors[] { make_color_matrix(0.299f, 0.114f, { 16.0f, 235.0f }, { 16.0f, 240.0f }), // BT601 MPEG make_color_matrix(0.299f, 0.114f, { 0.0f, 255.0f }, { 0.0f, 255.0f }), // BT601 JPEG make_color_matrix(0.2126f, 0.0722f, { 16.0f, 235.0f }, { 16.0f, 240.0f }), // BT709 MPEG make_color_matrix(0.2126f, 0.0722f, { 0.0f, 255.0f }, { 0.0f, 255.0f }), // BT709 JPEG make_color_matrix(0.2627f, 0.0593f, { 16.0f, 235.0f }, { 16.0f, 240.0f }), // BT2020 MPEG make_color_matrix(0.2627f, 0.0593f, { 0.0f, 255.0f }, { 0.0f, 255.0f }), // BT2020 JPEG }; const color_t *result = nullptr; switch (colorspace) { case colorspace_e::rec601: default: result = &colors[0]; break; case colorspace_e::rec709: result = &colors[2]; break; case colorspace_e::bt2020: case colorspace_e::bt2020sdr: result = &colors[4]; break; }; if (full_range) { result++; } return result; } const color_t * new_color_vectors_from_colorspace(const sunshine_colorspace_t &colorspace) { constexpr auto generate_color_vectors = [](const sunshine_colorspace_t &colorspace) -> color_t { double Kr, Kb; switch (colorspace.colorspace) { case colorspace_e::rec601: Kr = 0.299; Kb = 0.114; break; case colorspace_e::rec709: default: Kr = 0.2126; Kb = 0.0722; break; case colorspace_e::bt2020: case colorspace_e::bt2020sdr: Kr = 0.2627; Kb = 0.0593; break; } double Kg = 1.0 - Kr - Kb; double y_mult, y_add; double uv_mult, uv_add; // "Matrix coefficients" section of ITU-T H.273 if (colorspace.full_range) { y_mult = (1 << colorspace.bit_depth) - 1; y_add = 0; uv_mult = (1 << colorspace.bit_depth) - 1; uv_add = (1 << (colorspace.bit_depth - 1)); } else { y_mult = (1 << (colorspace.bit_depth - 8)) * 219; y_add = (1 << (colorspace.bit_depth - 8)) * 16; uv_mult = (1 << (colorspace.bit_depth - 8)) * 224; uv_add = (1 << (colorspace.bit_depth - 8)) * 128; } // For rounding y_add += 0.5; uv_add += 0.5; color_t color_vectors; color_vectors.color_vec_y[0] = Kr * y_mult; color_vectors.color_vec_y[1] = Kg * y_mult; color_vectors.color_vec_y[2] = Kb * y_mult; color_vectors.color_vec_y[3] = y_add; color_vectors.color_vec_u[0] = -0.5 * Kr / (1.0 - Kb) * uv_mult; color_vectors.color_vec_u[1] = -0.5 * Kg / (1.0 - Kb) * uv_mult; color_vectors.color_vec_u[2] = 0.5 * uv_mult; color_vectors.color_vec_u[3] = uv_add; color_vectors.color_vec_v[0] = 0.5 * uv_mult; color_vectors.color_vec_v[1] = -0.5 * Kg / (1.0 - Kr) * uv_mult; color_vectors.color_vec_v[2] = -0.5 * Kb / (1.0 - Kr) * uv_mult; color_vectors.color_vec_v[3] = uv_add; // Unused color_vectors.range_y[0] = 1; color_vectors.range_y[1] = 0; color_vectors.range_uv[0] = 1; color_vectors.range_uv[1] = 0; return color_vectors; }; static constexpr color_t colors[] = { generate_color_vectors({ colorspace_e::rec601, false, 8 }), generate_color_vectors({ colorspace_e::rec601, true, 8 }), generate_color_vectors({ colorspace_e::rec601, false, 10 }), generate_color_vectors({ colorspace_e::rec601, true, 10 }), generate_color_vectors({ colorspace_e::rec709, false, 8 }), generate_color_vectors({ colorspace_e::rec709, true, 8 }), generate_color_vectors({ colorspace_e::rec709, false, 10 }), generate_color_vectors({ colorspace_e::rec709, true, 10 }), generate_color_vectors({ colorspace_e::bt2020, false, 8 }), generate_color_vectors({ colorspace_e::bt2020, true, 8 }), generate_color_vectors({ colorspace_e::bt2020, false, 10 }), generate_color_vectors({ colorspace_e::bt2020, true, 10 }), }; const color_t *result = nullptr; switch (colorspace.colorspace) { case colorspace_e::rec601: result = &colors[0]; break; case colorspace_e::rec709: default: result = &colors[4]; break; case colorspace_e::bt2020: case colorspace_e::bt2020sdr: result = &colors[8]; break; } if (colorspace.bit_depth == 10) result += 2; if (colorspace.full_range) result += 1; return result; } } // namespace video
9,571
C++
.cpp
242
31.165289
112
0.591899
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,987
crypto.cpp
LizardByte_Sunshine/src/crypto.cpp
/** * @file src/crypto.cpp * @brief Definitions for cryptography functions. */ #include "crypto.h" #include <openssl/pem.h> #include <openssl/rsa.h> namespace crypto { using asn1_string_t = util::safe_ptr<ASN1_STRING, ASN1_STRING_free>; cert_chain_t::cert_chain_t(): _certs {}, _cert_ctx { X509_STORE_CTX_new() } {} void cert_chain_t::add(x509_t &&cert) { x509_store_t x509_store { X509_STORE_new() }; X509_STORE_add_cert(x509_store.get(), cert.get()); _certs.emplace_back(std::make_pair(std::move(cert), std::move(x509_store))); } void cert_chain_t::clear() { _certs.clear(); } static int openssl_verify_cb(int ok, X509_STORE_CTX *ctx) { int err_code = X509_STORE_CTX_get_error(ctx); switch (err_code) { // Expired or not-yet-valid certificates are fine. Sometimes Moonlight is running on embedded devices // that don't have accurate clocks (or haven't yet synchronized by the time Moonlight first runs). // This behavior also matches what GeForce Experience does. // TODO: Checking for X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY is a temporary workaround to get moonlight-embedded to work on the raspberry pi case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: case X509_V_ERR_CERT_NOT_YET_VALID: case X509_V_ERR_CERT_HAS_EXPIRED: return 1; default: return ok; } } /** * @brief Verify the certificate chain. * When certificates from two or more instances of Moonlight have been added to x509_store_t, * only one of them will be verified by X509_verify_cert, resulting in only a single instance of * Moonlight to be able to use Sunshine * * To circumvent this, x509_store_t instance will be created for each instance of the certificates. * @param cert The certificate to verify. * @return nullptr if the certificate is valid, otherwise an error string. */ const char * cert_chain_t::verify(x509_t::element_type *cert) { int err_code = 0; for (auto &[_, x509_store] : _certs) { auto fg = util::fail_guard([this]() { X509_STORE_CTX_cleanup(_cert_ctx.get()); }); X509_STORE_CTX_init(_cert_ctx.get(), x509_store.get(), cert, nullptr); X509_STORE_CTX_set_verify_cb(_cert_ctx.get(), openssl_verify_cb); // We don't care to validate the entire chain for the purposes of client auth. // Some versions of clients forked from Moonlight Embedded produce client certs // that OpenSSL doesn't detect as self-signed due to some X509v3 extensions. X509_STORE_CTX_set_flags(_cert_ctx.get(), X509_V_FLAG_PARTIAL_CHAIN); auto err = X509_verify_cert(_cert_ctx.get()); if (err == 1) { return nullptr; } err_code = X509_STORE_CTX_get_error(_cert_ctx.get()); if (err_code != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT && err_code != X509_V_ERR_INVALID_CA) { return X509_verify_cert_error_string(err_code); } } return X509_verify_cert_error_string(err_code); } namespace cipher { static int init_decrypt_gcm(cipher_ctx_t &ctx, aes_t *key, aes_t *iv, bool padding) { ctx.reset(EVP_CIPHER_CTX_new()); if (!ctx) { return -1; } if (EVP_DecryptInit_ex(ctx.get(), EVP_aes_128_gcm(), nullptr, nullptr, nullptr) != 1) { return -1; } if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, iv->size(), nullptr) != 1) { return -1; } if (EVP_DecryptInit_ex(ctx.get(), nullptr, nullptr, key->data(), iv->data()) != 1) { return -1; } EVP_CIPHER_CTX_set_padding(ctx.get(), padding); return 0; } static int init_encrypt_gcm(cipher_ctx_t &ctx, aes_t *key, aes_t *iv, bool padding) { ctx.reset(EVP_CIPHER_CTX_new()); // Gen 7 servers use 128-bit AES ECB if (EVP_EncryptInit_ex(ctx.get(), EVP_aes_128_gcm(), nullptr, nullptr, nullptr) != 1) { return -1; } if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, iv->size(), nullptr) != 1) { return -1; } if (EVP_EncryptInit_ex(ctx.get(), nullptr, nullptr, key->data(), iv->data()) != 1) { return -1; } EVP_CIPHER_CTX_set_padding(ctx.get(), padding); return 0; } static int init_encrypt_cbc(cipher_ctx_t &ctx, aes_t *key, aes_t *iv, bool padding) { ctx.reset(EVP_CIPHER_CTX_new()); // Gen 7 servers use 128-bit AES ECB if (EVP_EncryptInit_ex(ctx.get(), EVP_aes_128_cbc(), nullptr, key->data(), iv->data()) != 1) { return -1; } EVP_CIPHER_CTX_set_padding(ctx.get(), padding); return 0; } int gcm_t::decrypt(const std::string_view &tagged_cipher, std::vector<std::uint8_t> &plaintext, aes_t *iv) { if (!decrypt_ctx && init_decrypt_gcm(decrypt_ctx, &key, iv, padding)) { return -1; } // Calling with cipher == nullptr results in a parameter change // without requiring a reallocation of the internal cipher ctx. if (EVP_DecryptInit_ex(decrypt_ctx.get(), nullptr, nullptr, nullptr, iv->data()) != 1) { return false; } auto cipher = tagged_cipher.substr(tag_size); auto tag = tagged_cipher.substr(0, tag_size); plaintext.resize(round_to_pkcs7_padded(cipher.size())); int update_outlen, final_outlen; if (EVP_DecryptUpdate(decrypt_ctx.get(), plaintext.data(), &update_outlen, (const std::uint8_t *) cipher.data(), cipher.size()) != 1) { return -1; } if (EVP_CIPHER_CTX_ctrl(decrypt_ctx.get(), EVP_CTRL_GCM_SET_TAG, tag.size(), const_cast<char *>(tag.data())) != 1) { return -1; } if (EVP_DecryptFinal_ex(decrypt_ctx.get(), plaintext.data() + update_outlen, &final_outlen) != 1) { return -1; } plaintext.resize(update_outlen + final_outlen); return 0; } /** * This function encrypts the given plaintext using the AES key in GCM mode. The initialization vector (IV) is also provided. * The function handles the creation and initialization of the encryption context, and manages the encryption process. * The resulting ciphertext and the GCM tag are written into the tagged_cipher buffer. */ int gcm_t::encrypt(const std::string_view &plaintext, std::uint8_t *tag, std::uint8_t *ciphertext, aes_t *iv) { if (!encrypt_ctx && init_encrypt_gcm(encrypt_ctx, &key, iv, padding)) { return -1; } // Calling with cipher == nullptr results in a parameter change // without requiring a reallocation of the internal cipher ctx. if (EVP_EncryptInit_ex(encrypt_ctx.get(), nullptr, nullptr, nullptr, iv->data()) != 1) { return -1; } int update_outlen, final_outlen; // Encrypt into the caller's buffer if (EVP_EncryptUpdate(encrypt_ctx.get(), ciphertext, &update_outlen, (const std::uint8_t *) plaintext.data(), plaintext.size()) != 1) { return -1; } // GCM encryption won't ever fill ciphertext here but we have to call it anyway if (EVP_EncryptFinal_ex(encrypt_ctx.get(), ciphertext + update_outlen, &final_outlen) != 1) { return -1; } if (EVP_CIPHER_CTX_ctrl(encrypt_ctx.get(), EVP_CTRL_GCM_GET_TAG, tag_size, tag) != 1) { return -1; } return update_outlen + final_outlen; } int gcm_t::encrypt(const std::string_view &plaintext, std::uint8_t *tagged_cipher, aes_t *iv) { // This overload handles the common case of [GCM tag][cipher text] buffer layout return encrypt(plaintext, tagged_cipher, tagged_cipher + tag_size, iv); } int ecb_t::decrypt(const std::string_view &cipher, std::vector<std::uint8_t> &plaintext) { auto fg = util::fail_guard([this]() { EVP_CIPHER_CTX_reset(decrypt_ctx.get()); }); // Gen 7 servers use 128-bit AES ECB if (EVP_DecryptInit_ex(decrypt_ctx.get(), EVP_aes_128_ecb(), nullptr, key.data(), nullptr) != 1) { return -1; } EVP_CIPHER_CTX_set_padding(decrypt_ctx.get(), padding); plaintext.resize(round_to_pkcs7_padded(cipher.size())); int update_outlen, final_outlen; if (EVP_DecryptUpdate(decrypt_ctx.get(), plaintext.data(), &update_outlen, (const std::uint8_t *) cipher.data(), cipher.size()) != 1) { return -1; } if (EVP_DecryptFinal_ex(decrypt_ctx.get(), plaintext.data() + update_outlen, &final_outlen) != 1) { return -1; } plaintext.resize(update_outlen + final_outlen); return 0; } int ecb_t::encrypt(const std::string_view &plaintext, std::vector<std::uint8_t> &cipher) { auto fg = util::fail_guard([this]() { EVP_CIPHER_CTX_reset(encrypt_ctx.get()); }); // Gen 7 servers use 128-bit AES ECB if (EVP_EncryptInit_ex(encrypt_ctx.get(), EVP_aes_128_ecb(), nullptr, key.data(), nullptr) != 1) { return -1; } EVP_CIPHER_CTX_set_padding(encrypt_ctx.get(), padding); cipher.resize(round_to_pkcs7_padded(plaintext.size())); int update_outlen, final_outlen; // Encrypt into the caller's buffer if (EVP_EncryptUpdate(encrypt_ctx.get(), cipher.data(), &update_outlen, (const std::uint8_t *) plaintext.data(), plaintext.size()) != 1) { return -1; } if (EVP_EncryptFinal_ex(encrypt_ctx.get(), cipher.data() + update_outlen, &final_outlen) != 1) { return -1; } cipher.resize(update_outlen + final_outlen); return 0; } /** * This function encrypts the given plaintext using the AES key in CBC mode. The initialization vector (IV) is also provided. * The function handles the creation and initialization of the encryption context, and manages the encryption process. * The resulting ciphertext is written into the cipher buffer. */ int cbc_t::encrypt(const std::string_view &plaintext, std::uint8_t *cipher, aes_t *iv) { if (!encrypt_ctx && init_encrypt_cbc(encrypt_ctx, &key, iv, padding)) { return -1; } // Calling with cipher == nullptr results in a parameter change // without requiring a reallocation of the internal cipher ctx. if (EVP_EncryptInit_ex(encrypt_ctx.get(), nullptr, nullptr, nullptr, iv->data()) != 1) { return false; } int update_outlen, final_outlen; // Encrypt into the caller's buffer if (EVP_EncryptUpdate(encrypt_ctx.get(), cipher, &update_outlen, (const std::uint8_t *) plaintext.data(), plaintext.size()) != 1) { return -1; } if (EVP_EncryptFinal_ex(encrypt_ctx.get(), cipher + update_outlen, &final_outlen) != 1) { return -1; } return update_outlen + final_outlen; } ecb_t::ecb_t(const aes_t &key, bool padding): cipher_t { EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_new(), key, padding } {} cbc_t::cbc_t(const aes_t &key, bool padding): cipher_t { nullptr, nullptr, key, padding } {} gcm_t::gcm_t(const crypto::aes_t &key, bool padding): cipher_t { nullptr, nullptr, key, padding } {} } // namespace cipher aes_t gen_aes_key(const std::array<uint8_t, 16> &salt, const std::string_view &pin) { aes_t key(16); std::string salt_pin; salt_pin.reserve(salt.size() + pin.size()); salt_pin.insert(std::end(salt_pin), std::begin(salt), std::end(salt)); salt_pin.insert(std::end(salt_pin), std::begin(pin), std::end(pin)); auto hsh = hash(salt_pin); std::copy(std::begin(hsh), std::begin(hsh) + key.size(), std::begin(key)); return key; } sha256_t hash(const std::string_view &plaintext) { sha256_t hsh; EVP_Digest(plaintext.data(), plaintext.size(), hsh.data(), nullptr, EVP_sha256(), nullptr); return hsh; } x509_t x509(const std::string_view &x) { bio_t io { BIO_new(BIO_s_mem()) }; BIO_write(io.get(), x.data(), x.size()); x509_t p; PEM_read_bio_X509(io.get(), &p, nullptr, nullptr); return p; } pkey_t pkey(const std::string_view &k) { bio_t io { BIO_new(BIO_s_mem()) }; BIO_write(io.get(), k.data(), k.size()); pkey_t p = nullptr; PEM_read_bio_PrivateKey(io.get(), &p, nullptr, nullptr); return p; } std::string pem(x509_t &x509) { bio_t bio { BIO_new(BIO_s_mem()) }; PEM_write_bio_X509(bio.get(), x509.get()); BUF_MEM *mem_ptr; BIO_get_mem_ptr(bio.get(), &mem_ptr); return { mem_ptr->data, mem_ptr->length }; } std::string pem(pkey_t &pkey) { bio_t bio { BIO_new(BIO_s_mem()) }; PEM_write_bio_PrivateKey(bio.get(), pkey.get(), nullptr, nullptr, 0, nullptr, nullptr); BUF_MEM *mem_ptr; BIO_get_mem_ptr(bio.get(), &mem_ptr); return { mem_ptr->data, mem_ptr->length }; } std::string_view signature(const x509_t &x) { // X509_ALGOR *_ = nullptr; const ASN1_BIT_STRING *asn1 = nullptr; X509_get0_signature(&asn1, nullptr, x.get()); return { (const char *) asn1->data, (std::size_t) asn1->length }; } std::string rand(std::size_t bytes) { std::string r; r.resize(bytes); RAND_bytes((uint8_t *) r.data(), r.size()); return r; } std::vector<uint8_t> sign(const pkey_t &pkey, const std::string_view &data, const EVP_MD *md) { md_ctx_t ctx { EVP_MD_CTX_create() }; if (EVP_DigestSignInit(ctx.get(), nullptr, md, nullptr, (EVP_PKEY *) pkey.get()) != 1) { return {}; } if (EVP_DigestSignUpdate(ctx.get(), data.data(), data.size()) != 1) { return {}; } std::size_t slen; if (EVP_DigestSignFinal(ctx.get(), nullptr, &slen) != 1) { return {}; } std::vector<uint8_t> digest(slen); if (EVP_DigestSignFinal(ctx.get(), digest.data(), &slen) != 1) { return {}; } return digest; } creds_t gen_creds(const std::string_view &cn, std::uint32_t key_bits) { x509_t x509 { X509_new() }; pkey_ctx_t ctx { EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, nullptr) }; pkey_t pkey; EVP_PKEY_keygen_init(ctx.get()); EVP_PKEY_CTX_set_rsa_keygen_bits(ctx.get(), key_bits); EVP_PKEY_keygen(ctx.get(), &pkey); X509_set_version(x509.get(), 2); // Generate a real serial number to avoid SEC_ERROR_REUSED_ISSUER_AND_SERIAL with Firefox bignum_t serial { BN_new() }; BN_rand(serial.get(), 159, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY); // 159 bits to fit in 20 bytes in DER format BN_set_negative(serial.get(), 0); // Serial numbers must be positive BN_to_ASN1_INTEGER(serial.get(), X509_get_serialNumber(x509.get())); constexpr auto year = 60 * 60 * 24 * 365; #if OPENSSL_VERSION_NUMBER < 0x10100000L X509_gmtime_adj(X509_get_notBefore(x509.get()), 0); X509_gmtime_adj(X509_get_notAfter(x509.get()), 20 * year); #else asn1_string_t not_before { ASN1_STRING_dup(X509_get0_notBefore(x509.get())) }; asn1_string_t not_after { ASN1_STRING_dup(X509_get0_notAfter(x509.get())) }; X509_gmtime_adj(not_before.get(), 0); X509_gmtime_adj(not_after.get(), 20 * year); X509_set1_notBefore(x509.get(), not_before.get()); X509_set1_notAfter(x509.get(), not_after.get()); #endif X509_set_pubkey(x509.get(), pkey.get()); auto name = X509_get_subject_name(x509.get()); X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const std::uint8_t *) cn.data(), cn.size(), -1, 0); X509_set_issuer_name(x509.get(), name); X509_sign(x509.get(), pkey.get(), EVP_sha256()); return { pem(x509), pem(pkey) }; } std::vector<uint8_t> sign256(const pkey_t &pkey, const std::string_view &data) { return sign(pkey, data, EVP_sha256()); } bool verify(const x509_t &x509, const std::string_view &data, const std::string_view &signature, const EVP_MD *md) { auto pkey = X509_get0_pubkey(x509.get()); md_ctx_t ctx { EVP_MD_CTX_create() }; if (EVP_DigestVerifyInit(ctx.get(), nullptr, md, nullptr, pkey) != 1) { return false; } if (EVP_DigestVerifyUpdate(ctx.get(), data.data(), data.size()) != 1) { return false; } if (EVP_DigestVerifyFinal(ctx.get(), (const uint8_t *) signature.data(), signature.size()) != 1) { return false; } return true; } bool verify256(const x509_t &x509, const std::string_view &data, const std::string_view &signature) { return verify(x509, data, signature, EVP_sha256()); } void md_ctx_destroy(EVP_MD_CTX *ctx) { EVP_MD_CTX_destroy(ctx); } std::string rand_alphabet(std::size_t bytes, const std::string_view &alphabet) { auto value = rand(bytes); for (std::size_t i = 0; i != value.size(); ++i) { value[i] = alphabet[value[i] % alphabet.length()]; } return value; } } // namespace crypto
16,756
C++
.cpp
404
35.522277
152
0.630385
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,988
nvenc_utils.cpp
LizardByte_Sunshine/src/nvenc/nvenc_utils.cpp
/** * @file src/nvenc/nvenc_utils.cpp * @brief Definitions for NVENC utilities. */ #include <cassert> #include "nvenc_utils.h" namespace nvenc { #ifdef _WIN32 DXGI_FORMAT dxgi_format_from_nvenc_format(NV_ENC_BUFFER_FORMAT format) { switch (format) { case NV_ENC_BUFFER_FORMAT_YUV420_10BIT: return DXGI_FORMAT_P010; case NV_ENC_BUFFER_FORMAT_NV12: return DXGI_FORMAT_NV12; case NV_ENC_BUFFER_FORMAT_AYUV: return DXGI_FORMAT_AYUV; case NV_ENC_BUFFER_FORMAT_YUV444_10BIT: return DXGI_FORMAT_R16_UINT; default: return DXGI_FORMAT_UNKNOWN; } } #endif NV_ENC_BUFFER_FORMAT nvenc_format_from_sunshine_format(platf::pix_fmt_e format) { switch (format) { case platf::pix_fmt_e::nv12: return NV_ENC_BUFFER_FORMAT_NV12; case platf::pix_fmt_e::p010: return NV_ENC_BUFFER_FORMAT_YUV420_10BIT; case platf::pix_fmt_e::ayuv: return NV_ENC_BUFFER_FORMAT_AYUV; case platf::pix_fmt_e::yuv444p16: return NV_ENC_BUFFER_FORMAT_YUV444_10BIT; default: return NV_ENC_BUFFER_FORMAT_UNDEFINED; } } nvenc_colorspace_t nvenc_colorspace_from_sunshine_colorspace(const video::sunshine_colorspace_t &sunshine_colorspace) { nvenc_colorspace_t colorspace; switch (sunshine_colorspace.colorspace) { case video::colorspace_e::rec601: // Rec. 601 colorspace.primaries = NV_ENC_VUI_COLOR_PRIMARIES_SMPTE170M; colorspace.tranfer_function = NV_ENC_VUI_TRANSFER_CHARACTERISTIC_SMPTE170M; colorspace.matrix = NV_ENC_VUI_MATRIX_COEFFS_SMPTE170M; break; case video::colorspace_e::rec709: // Rec. 709 colorspace.primaries = NV_ENC_VUI_COLOR_PRIMARIES_BT709; colorspace.tranfer_function = NV_ENC_VUI_TRANSFER_CHARACTERISTIC_BT709; colorspace.matrix = NV_ENC_VUI_MATRIX_COEFFS_BT709; break; case video::colorspace_e::bt2020sdr: // Rec. 2020 colorspace.primaries = NV_ENC_VUI_COLOR_PRIMARIES_BT2020; assert(sunshine_colorspace.bit_depth == 10); colorspace.tranfer_function = NV_ENC_VUI_TRANSFER_CHARACTERISTIC_BT2020_10; colorspace.matrix = NV_ENC_VUI_MATRIX_COEFFS_BT2020_NCL; break; case video::colorspace_e::bt2020: // Rec. 2020 with ST 2084 perceptual quantizer colorspace.primaries = NV_ENC_VUI_COLOR_PRIMARIES_BT2020; assert(sunshine_colorspace.bit_depth == 10); colorspace.tranfer_function = NV_ENC_VUI_TRANSFER_CHARACTERISTIC_SMPTE2084; colorspace.matrix = NV_ENC_VUI_MATRIX_COEFFS_BT2020_NCL; break; } colorspace.full_range = sunshine_colorspace.full_range; return colorspace; } } // namespace nvenc
2,873
C++
.cpp
74
30.918919
103
0.667271
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,989
nvenc_d3d11_on_cuda.cpp
LizardByte_Sunshine/src/nvenc/nvenc_d3d11_on_cuda.cpp
/** * @file src/nvenc/nvenc_d3d11_on_cuda.cpp * @brief Definitions for CUDA NVENC encoder with Direct3D11 input surfaces. */ #ifdef _WIN32 #include "nvenc_d3d11_on_cuda.h" #include "nvenc_utils.h" namespace nvenc { nvenc_d3d11_on_cuda::nvenc_d3d11_on_cuda(ID3D11Device *d3d_device): nvenc_d3d11(NV_ENC_DEVICE_TYPE_CUDA), d3d_device(d3d_device) { } nvenc_d3d11_on_cuda::~nvenc_d3d11_on_cuda() { if (encoder) destroy_encoder(); if (cuda_context) { { auto autopop_context = push_context(); if (cuda_d3d_input_texture) { if (cuda_failed(cuda_functions.cuGraphicsUnregisterResource(cuda_d3d_input_texture))) { BOOST_LOG(error) << "NvEnc: cuGraphicsUnregisterResource() failed: error " << last_cuda_error; } cuda_d3d_input_texture = nullptr; } if (cuda_surface) { if (cuda_failed(cuda_functions.cuMemFree(cuda_surface))) { BOOST_LOG(error) << "NvEnc: cuMemFree() failed: error " << last_cuda_error; } cuda_surface = 0; } } if (cuda_failed(cuda_functions.cuCtxDestroy(cuda_context))) { BOOST_LOG(error) << "NvEnc: cuCtxDestroy() failed: error " << last_cuda_error; } cuda_context = nullptr; } if (cuda_functions.dll) { FreeLibrary(cuda_functions.dll); cuda_functions = {}; } } ID3D11Texture2D * nvenc_d3d11_on_cuda::get_input_texture() { return d3d_input_texture.GetInterfacePtr(); } bool nvenc_d3d11_on_cuda::init_library() { if (!nvenc_d3d11::init_library()) return false; constexpr auto dll_name = "nvcuda.dll"; if ((cuda_functions.dll = LoadLibraryEx(dll_name, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32))) { auto load_function = [&]<typename T>(T &location, auto symbol) -> bool { location = (T) GetProcAddress(cuda_functions.dll, symbol); return location != nullptr; }; if (!load_function(cuda_functions.cuInit, "cuInit") || !load_function(cuda_functions.cuD3D11GetDevice, "cuD3D11GetDevice") || !load_function(cuda_functions.cuCtxCreate, "cuCtxCreate_v2") || !load_function(cuda_functions.cuCtxDestroy, "cuCtxDestroy_v2") || !load_function(cuda_functions.cuCtxPushCurrent, "cuCtxPushCurrent_v2") || !load_function(cuda_functions.cuCtxPopCurrent, "cuCtxPopCurrent_v2") || !load_function(cuda_functions.cuMemAllocPitch, "cuMemAllocPitch_v2") || !load_function(cuda_functions.cuMemFree, "cuMemFree_v2") || !load_function(cuda_functions.cuGraphicsD3D11RegisterResource, "cuGraphicsD3D11RegisterResource") || !load_function(cuda_functions.cuGraphicsUnregisterResource, "cuGraphicsUnregisterResource") || !load_function(cuda_functions.cuGraphicsMapResources, "cuGraphicsMapResources") || !load_function(cuda_functions.cuGraphicsUnmapResources, "cuGraphicsUnmapResources") || !load_function(cuda_functions.cuGraphicsSubResourceGetMappedArray, "cuGraphicsSubResourceGetMappedArray") || !load_function(cuda_functions.cuMemcpy2D, "cuMemcpy2D_v2")) { BOOST_LOG(error) << "NvEnc: missing CUDA functions in " << dll_name; FreeLibrary(cuda_functions.dll); cuda_functions = {}; } } else { BOOST_LOG(debug) << "NvEnc: couldn't load CUDA dynamic library " << dll_name; } if (cuda_functions.dll) { IDXGIDevicePtr dxgi_device; IDXGIAdapterPtr dxgi_adapter; if (d3d_device && SUCCEEDED(d3d_device->QueryInterface(IID_PPV_ARGS(&dxgi_device))) && SUCCEEDED(dxgi_device->GetAdapter(&dxgi_adapter))) { CUdevice cuda_device; if (cuda_succeeded(cuda_functions.cuInit(0)) && cuda_succeeded(cuda_functions.cuD3D11GetDevice(&cuda_device, dxgi_adapter)) && cuda_succeeded(cuda_functions.cuCtxCreate(&cuda_context, CU_CTX_SCHED_BLOCKING_SYNC, cuda_device)) && cuda_succeeded(cuda_functions.cuCtxPopCurrent(&cuda_context))) { device = cuda_context; } else { BOOST_LOG(error) << "NvEnc: couldn't create CUDA interop context: error " << last_cuda_error; } } else { BOOST_LOG(error) << "NvEnc: couldn't get DXGI adapter for CUDA interop"; } } return device != nullptr; } bool nvenc_d3d11_on_cuda::create_and_register_input_buffer() { if (encoder_params.buffer_format != NV_ENC_BUFFER_FORMAT_YUV444_10BIT) { BOOST_LOG(error) << "NvEnc: CUDA interop is expected to be used only for 10-bit 4:4:4 encoding"; return false; } if (!d3d_input_texture) { D3D11_TEXTURE2D_DESC desc = {}; desc.Width = encoder_params.width; desc.Height = encoder_params.height * 3; // Planar YUV desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = dxgi_format_from_nvenc_format(encoder_params.buffer_format); desc.SampleDesc.Count = 1; desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_RENDER_TARGET; if (d3d_device->CreateTexture2D(&desc, nullptr, &d3d_input_texture) != S_OK) { BOOST_LOG(error) << "NvEnc: couldn't create input texture"; return false; } } { auto autopop_context = push_context(); if (!autopop_context) return false; if (!cuda_d3d_input_texture) { if (cuda_failed(cuda_functions.cuGraphicsD3D11RegisterResource( &cuda_d3d_input_texture, d3d_input_texture, CU_GRAPHICS_REGISTER_FLAGS_NONE))) { BOOST_LOG(error) << "NvEnc: cuGraphicsD3D11RegisterResource() failed: error " << last_cuda_error; return false; } } if (!cuda_surface) { if (cuda_failed(cuda_functions.cuMemAllocPitch( &cuda_surface, &cuda_surface_pitch, // Planar 16-bit YUV encoder_params.width * 2, encoder_params.height * 3, 16))) { BOOST_LOG(error) << "NvEnc: cuMemAllocPitch() failed: error " << last_cuda_error; return false; } } } if (!registered_input_buffer) { NV_ENC_REGISTER_RESOURCE register_resource = { min_struct_version(NV_ENC_REGISTER_RESOURCE_VER, 3, 4) }; register_resource.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR; register_resource.width = encoder_params.width; register_resource.height = encoder_params.height; register_resource.pitch = cuda_surface_pitch; register_resource.resourceToRegister = (void *) cuda_surface; register_resource.bufferFormat = encoder_params.buffer_format; register_resource.bufferUsage = NV_ENC_INPUT_IMAGE; if (nvenc_failed(nvenc->nvEncRegisterResource(encoder, &register_resource))) { BOOST_LOG(error) << "NvEnc: NvEncRegisterResource() failed: " << last_nvenc_error_string; return false; } registered_input_buffer = register_resource.registeredResource; } return true; } bool nvenc_d3d11_on_cuda::synchronize_input_buffer() { auto autopop_context = push_context(); if (!autopop_context) return false; if (cuda_failed(cuda_functions.cuGraphicsMapResources(1, &cuda_d3d_input_texture, 0))) { BOOST_LOG(error) << "NvEnc: cuGraphicsMapResources() failed: error " << last_cuda_error; return false; } auto unmap = [&]() -> bool { if (cuda_failed(cuda_functions.cuGraphicsUnmapResources(1, &cuda_d3d_input_texture, 0))) { BOOST_LOG(error) << "NvEnc: cuGraphicsUnmapResources() failed: error " << last_cuda_error; return false; } return true; }; auto unmap_guard = util::fail_guard(unmap); CUarray input_texture_array; if (cuda_failed(cuda_functions.cuGraphicsSubResourceGetMappedArray(&input_texture_array, cuda_d3d_input_texture, 0, 0))) { BOOST_LOG(error) << "NvEnc: cuGraphicsSubResourceGetMappedArray() failed: error " << last_cuda_error; return false; } { CUDA_MEMCPY2D copy_params = {}; copy_params.srcMemoryType = CU_MEMORYTYPE_ARRAY; copy_params.srcArray = input_texture_array; copy_params.dstMemoryType = CU_MEMORYTYPE_DEVICE; copy_params.dstDevice = cuda_surface; copy_params.dstPitch = cuda_surface_pitch; // Planar 16-bit YUV copy_params.WidthInBytes = encoder_params.width * 2; copy_params.Height = encoder_params.height * 3; if (cuda_failed(cuda_functions.cuMemcpy2D(&copy_params))) { BOOST_LOG(error) << "NvEnc: cuMemcpy2D() failed: error " << last_cuda_error; return false; } } unmap_guard.disable(); return unmap(); } bool nvenc_d3d11_on_cuda::cuda_succeeded(CUresult result) { last_cuda_error = result; return result == CUDA_SUCCESS; } bool nvenc_d3d11_on_cuda::cuda_failed(CUresult result) { last_cuda_error = result; return result != CUDA_SUCCESS; } nvenc_d3d11_on_cuda::autopop_context::~autopop_context() { if (pushed_context) { CUcontext popped_context; if (parent.cuda_failed(parent.cuda_functions.cuCtxPopCurrent(&popped_context))) { BOOST_LOG(error) << "NvEnc: cuCtxPopCurrent() failed: error " << parent.last_cuda_error; } } } nvenc_d3d11_on_cuda::autopop_context nvenc_d3d11_on_cuda::push_context() { if (cuda_context && cuda_succeeded(cuda_functions.cuCtxPushCurrent(cuda_context))) { return { *this, cuda_context }; } else { BOOST_LOG(error) << "NvEnc: cuCtxPushCurrent() failed: error " << last_cuda_error; return { *this, nullptr }; } } } // namespace nvenc #endif
9,970
C++
.cpp
230
34.995652
127
0.639251
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,990
nvenc_d3d11_native.cpp
LizardByte_Sunshine/src/nvenc/nvenc_d3d11_native.cpp
/** * @file src/nvenc/nvenc_d3d11_native.cpp * @brief Definitions for native Direct3D11 NVENC encoder. */ #ifdef _WIN32 #include "nvenc_d3d11_native.h" #include "nvenc_utils.h" namespace nvenc { nvenc_d3d11_native::nvenc_d3d11_native(ID3D11Device *d3d_device): nvenc_d3d11(NV_ENC_DEVICE_TYPE_DIRECTX), d3d_device(d3d_device) { device = d3d_device; } nvenc_d3d11_native::~nvenc_d3d11_native() { if (encoder) destroy_encoder(); } ID3D11Texture2D * nvenc_d3d11_native::get_input_texture() { return d3d_input_texture.GetInterfacePtr(); } bool nvenc_d3d11_native::create_and_register_input_buffer() { if (encoder_params.buffer_format == NV_ENC_BUFFER_FORMAT_YUV444_10BIT) { BOOST_LOG(error) << "NvEnc: 10-bit 4:4:4 encoding is incompatible with D3D11 surface formats, use CUDA interop"; return false; } if (!d3d_input_texture) { D3D11_TEXTURE2D_DESC desc = {}; desc.Width = encoder_params.width; desc.Height = encoder_params.height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = dxgi_format_from_nvenc_format(encoder_params.buffer_format); desc.SampleDesc.Count = 1; desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_RENDER_TARGET; if (d3d_device->CreateTexture2D(&desc, nullptr, &d3d_input_texture) != S_OK) { BOOST_LOG(error) << "NvEnc: couldn't create input texture"; return false; } } if (!registered_input_buffer) { NV_ENC_REGISTER_RESOURCE register_resource = { min_struct_version(NV_ENC_REGISTER_RESOURCE_VER, 3, 4) }; register_resource.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX; register_resource.width = encoder_params.width; register_resource.height = encoder_params.height; register_resource.resourceToRegister = d3d_input_texture.GetInterfacePtr(); register_resource.bufferFormat = encoder_params.buffer_format; register_resource.bufferUsage = NV_ENC_INPUT_IMAGE; if (nvenc_failed(nvenc->nvEncRegisterResource(encoder, &register_resource))) { BOOST_LOG(error) << "NvEnc: NvEncRegisterResource() failed: " << last_nvenc_error_string; return false; } registered_input_buffer = register_resource.registeredResource; } return true; } } // namespace nvenc #endif
2,426
C++
.cpp
59
34.491525
119
0.678617
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,991
nvenc_d3d11.cpp
LizardByte_Sunshine/src/nvenc/nvenc_d3d11.cpp
/** * @file src/nvenc/nvenc_d3d11.cpp * @brief Definitions for abstract Direct3D11 NVENC encoder. */ #include "src/logging.h" #ifdef _WIN32 #include "nvenc_d3d11.h" namespace nvenc { nvenc_d3d11::~nvenc_d3d11() { if (dll) { FreeLibrary(dll); dll = NULL; } } bool nvenc_d3d11::init_library() { if (dll) return true; #ifdef _WIN64 constexpr auto dll_name = "nvEncodeAPI64.dll"; #else constexpr auto dll_name = "nvEncodeAPI.dll"; #endif if ((dll = LoadLibraryEx(dll_name, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32))) { if (auto create_instance = (decltype(NvEncodeAPICreateInstance) *) GetProcAddress(dll, "NvEncodeAPICreateInstance")) { auto new_nvenc = std::make_unique<NV_ENCODE_API_FUNCTION_LIST>(); new_nvenc->version = min_struct_version(NV_ENCODE_API_FUNCTION_LIST_VER); if (nvenc_failed(create_instance(new_nvenc.get()))) { BOOST_LOG(error) << "NvEnc: NvEncodeAPICreateInstance() failed: " << last_nvenc_error_string; } else { nvenc = std::move(new_nvenc); return true; } } else { BOOST_LOG(error) << "NvEnc: No NvEncodeAPICreateInstance() in " << dll_name; } } else { BOOST_LOG(debug) << "NvEnc: Couldn't load NvEnc library " << dll_name; } if (dll) { FreeLibrary(dll); dll = NULL; } return false; } } // namespace nvenc #endif
1,504
C++
.cpp
49
24.061224
125
0.605428
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,992
nvenc_base.cpp
LizardByte_Sunshine/src/nvenc/nvenc_base.cpp
/** * @file src/nvenc/nvenc_base.cpp * @brief Definitions for abstract platform-agnostic base of standalone NVENC encoder. */ #include "nvenc_base.h" #include "src/config.h" #include "src/logging.h" #include "src/utility.h" #define MAKE_NVENC_VER(major, minor) ((major) | ((minor) << 24)) // Make sure we check backwards compatibility when bumping the Video Codec SDK version // Things to look out for: // - NV_ENC_*_VER definitions where the value inside NVENCAPI_STRUCT_VERSION() was increased // - Incompatible struct changes in nvEncodeAPI.h (fields removed, semantics changed, etc.) // - Test both old and new drivers with all supported codecs #if NVENCAPI_VERSION != MAKE_NVENC_VER(12U, 0U) #error Check and update NVENC code for backwards compatibility! #endif namespace { GUID quality_preset_guid_from_number(unsigned number) { if (number > 7) number = 7; switch (number) { case 1: default: return NV_ENC_PRESET_P1_GUID; case 2: return NV_ENC_PRESET_P2_GUID; case 3: return NV_ENC_PRESET_P3_GUID; case 4: return NV_ENC_PRESET_P4_GUID; case 5: return NV_ENC_PRESET_P5_GUID; case 6: return NV_ENC_PRESET_P6_GUID; case 7: return NV_ENC_PRESET_P7_GUID; } }; bool equal_guids(const GUID &guid1, const GUID &guid2) { return std::memcmp(&guid1, &guid2, sizeof(GUID)) == 0; } auto quality_preset_string_from_guid(const GUID &guid) { if (equal_guids(guid, NV_ENC_PRESET_P1_GUID)) { return "P1"; } if (equal_guids(guid, NV_ENC_PRESET_P2_GUID)) { return "P2"; } if (equal_guids(guid, NV_ENC_PRESET_P3_GUID)) { return "P3"; } if (equal_guids(guid, NV_ENC_PRESET_P4_GUID)) { return "P4"; } if (equal_guids(guid, NV_ENC_PRESET_P5_GUID)) { return "P5"; } if (equal_guids(guid, NV_ENC_PRESET_P6_GUID)) { return "P6"; } if (equal_guids(guid, NV_ENC_PRESET_P7_GUID)) { return "P7"; } return "Unknown"; } } // namespace namespace nvenc { nvenc_base::nvenc_base(NV_ENC_DEVICE_TYPE device_type): device_type(device_type) { } nvenc_base::~nvenc_base() { // Use destroy_encoder() instead } bool nvenc_base::create_encoder(const nvenc_config &config, const video::config_t &client_config, const nvenc_colorspace_t &colorspace, NV_ENC_BUFFER_FORMAT buffer_format) { // Pick the minimum NvEncode API version required to support the specified codec // to maximize driver compatibility. AV1 was introduced in SDK v12.0. minimum_api_version = (client_config.videoFormat <= 1) ? MAKE_NVENC_VER(11U, 0U) : MAKE_NVENC_VER(12U, 0U); if (!nvenc && !init_library()) return false; if (encoder) destroy_encoder(); auto fail_guard = util::fail_guard([this] { destroy_encoder(); }); encoder_params.width = client_config.width; encoder_params.height = client_config.height; encoder_params.buffer_format = buffer_format; encoder_params.rfi = true; NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS session_params = { min_struct_version(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER) }; session_params.device = device; session_params.deviceType = device_type; session_params.apiVersion = minimum_api_version; if (nvenc_failed(nvenc->nvEncOpenEncodeSessionEx(&session_params, &encoder))) { BOOST_LOG(error) << "NvEnc: NvEncOpenEncodeSessionEx() failed: " << last_nvenc_error_string; return false; } uint32_t encode_guid_count = 0; if (nvenc_failed(nvenc->nvEncGetEncodeGUIDCount(encoder, &encode_guid_count))) { BOOST_LOG(error) << "NvEnc: NvEncGetEncodeGUIDCount() failed: " << last_nvenc_error_string; return false; }; std::vector<GUID> encode_guids(encode_guid_count); if (nvenc_failed(nvenc->nvEncGetEncodeGUIDs(encoder, encode_guids.data(), encode_guids.size(), &encode_guid_count))) { BOOST_LOG(error) << "NvEnc: NvEncGetEncodeGUIDs() failed: " << last_nvenc_error_string; return false; } NV_ENC_INITIALIZE_PARAMS init_params = { min_struct_version(NV_ENC_INITIALIZE_PARAMS_VER) }; switch (client_config.videoFormat) { case 0: // H.264 init_params.encodeGUID = NV_ENC_CODEC_H264_GUID; break; case 1: // HEVC init_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID; break; case 2: // AV1 init_params.encodeGUID = NV_ENC_CODEC_AV1_GUID; break; default: BOOST_LOG(error) << "NvEnc: unknown video format " << client_config.videoFormat; return false; } { auto search_predicate = [&](const GUID &guid) { return equal_guids(init_params.encodeGUID, guid); }; if (std::find_if(encode_guids.begin(), encode_guids.end(), search_predicate) == encode_guids.end()) { BOOST_LOG(error) << "NvEnc: encoding format is not supported by the gpu"; return false; } } auto get_encoder_cap = [&](NV_ENC_CAPS cap) { NV_ENC_CAPS_PARAM param = { min_struct_version(NV_ENC_CAPS_PARAM_VER), cap }; int value = 0; nvenc->nvEncGetEncodeCaps(encoder, init_params.encodeGUID, &param, &value); return value; }; auto buffer_is_10bit = [&]() { return buffer_format == NV_ENC_BUFFER_FORMAT_YUV420_10BIT || buffer_format == NV_ENC_BUFFER_FORMAT_YUV444_10BIT; }; auto buffer_is_yuv444 = [&]() { return buffer_format == NV_ENC_BUFFER_FORMAT_AYUV || buffer_format == NV_ENC_BUFFER_FORMAT_YUV444_10BIT; }; { auto supported_width = get_encoder_cap(NV_ENC_CAPS_WIDTH_MAX); auto supported_height = get_encoder_cap(NV_ENC_CAPS_HEIGHT_MAX); if (encoder_params.width > supported_width || encoder_params.height > supported_height) { BOOST_LOG(error) << "NvEnc: gpu max encode resolution " << supported_width << "x" << supported_height << ", requested " << encoder_params.width << "x" << encoder_params.height; return false; } } if (buffer_is_10bit() && !get_encoder_cap(NV_ENC_CAPS_SUPPORT_10BIT_ENCODE)) { BOOST_LOG(error) << "NvEnc: gpu doesn't support 10-bit encode"; return false; } if (buffer_is_yuv444() && !get_encoder_cap(NV_ENC_CAPS_SUPPORT_YUV444_ENCODE)) { BOOST_LOG(error) << "NvEnc: gpu doesn't support YUV444 encode"; return false; } if (async_event_handle && !get_encoder_cap(NV_ENC_CAPS_ASYNC_ENCODE_SUPPORT)) { BOOST_LOG(warning) << "NvEnc: gpu doesn't support async encode"; async_event_handle = nullptr; } encoder_params.rfi = get_encoder_cap(NV_ENC_CAPS_SUPPORT_REF_PIC_INVALIDATION); init_params.presetGUID = quality_preset_guid_from_number(config.quality_preset); init_params.tuningInfo = NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY; init_params.enablePTD = 1; init_params.enableEncodeAsync = async_event_handle ? 1 : 0; init_params.enableWeightedPrediction = config.weighted_prediction && get_encoder_cap(NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION); init_params.encodeWidth = encoder_params.width; init_params.darWidth = encoder_params.width; init_params.encodeHeight = encoder_params.height; init_params.darHeight = encoder_params.height; init_params.frameRateNum = client_config.framerate; init_params.frameRateDen = 1; NV_ENC_PRESET_CONFIG preset_config = { min_struct_version(NV_ENC_PRESET_CONFIG_VER), { min_struct_version(NV_ENC_CONFIG_VER, 7, 8) } }; if (nvenc_failed(nvenc->nvEncGetEncodePresetConfigEx(encoder, init_params.encodeGUID, init_params.presetGUID, init_params.tuningInfo, &preset_config))) { BOOST_LOG(error) << "NvEnc: NvEncGetEncodePresetConfigEx() failed: " << last_nvenc_error_string; return false; } NV_ENC_CONFIG enc_config = preset_config.presetCfg; enc_config.profileGUID = NV_ENC_CODEC_PROFILE_AUTOSELECT_GUID; enc_config.gopLength = NVENC_INFINITE_GOPLENGTH; enc_config.frameIntervalP = 1; enc_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR; enc_config.rcParams.zeroReorderDelay = 1; enc_config.rcParams.enableLookahead = 0; enc_config.rcParams.lowDelayKeyFrameScale = 1; enc_config.rcParams.multiPass = config.two_pass == nvenc_two_pass::quarter_resolution ? NV_ENC_TWO_PASS_QUARTER_RESOLUTION : config.two_pass == nvenc_two_pass::full_resolution ? NV_ENC_TWO_PASS_FULL_RESOLUTION : NV_ENC_MULTI_PASS_DISABLED; enc_config.rcParams.enableAQ = config.adaptive_quantization; enc_config.rcParams.averageBitRate = client_config.bitrate * 1000; if (get_encoder_cap(NV_ENC_CAPS_SUPPORT_CUSTOM_VBV_BUF_SIZE)) { enc_config.rcParams.vbvBufferSize = client_config.bitrate * 1000 / client_config.framerate; if (config.vbv_percentage_increase > 0) { enc_config.rcParams.vbvBufferSize += enc_config.rcParams.vbvBufferSize * config.vbv_percentage_increase / 100; } } auto set_h264_hevc_common_format_config = [&](auto &format_config) { format_config.repeatSPSPPS = 1; format_config.idrPeriod = NVENC_INFINITE_GOPLENGTH; format_config.sliceMode = 3; format_config.sliceModeData = client_config.slicesPerFrame; if (buffer_is_yuv444()) { format_config.chromaFormatIDC = 3; } format_config.enableFillerDataInsertion = config.insert_filler_data; }; auto set_ref_frames = [&](uint32_t &ref_frames_option, NV_ENC_NUM_REF_FRAMES &L0_option, uint32_t ref_frames_default) { if (client_config.numRefFrames > 0) { ref_frames_option = client_config.numRefFrames; } else { ref_frames_option = ref_frames_default; } if (ref_frames_option > 0 && !get_encoder_cap(NV_ENC_CAPS_SUPPORT_MULTIPLE_REF_FRAMES)) { ref_frames_option = 1; encoder_params.rfi = false; } encoder_params.ref_frames_in_dpb = ref_frames_option; // This limits ref frames any frame can use to 1, but allows larger buffer size for fallback if some frames are invalidated through rfi L0_option = NV_ENC_NUM_REF_FRAMES_1; }; auto set_minqp_if_enabled = [&](int value) { if (config.enable_min_qp) { enc_config.rcParams.enableMinQP = 1; enc_config.rcParams.minQP.qpInterP = value; enc_config.rcParams.minQP.qpIntra = value; } }; auto fill_h264_hevc_vui = [&](auto &vui_config) { vui_config.videoSignalTypePresentFlag = 1; vui_config.videoFormat = NV_ENC_VUI_VIDEO_FORMAT_UNSPECIFIED; vui_config.videoFullRangeFlag = colorspace.full_range; vui_config.colourDescriptionPresentFlag = 1; vui_config.colourPrimaries = colorspace.primaries; vui_config.transferCharacteristics = colorspace.tranfer_function; vui_config.colourMatrix = colorspace.matrix; vui_config.chromaSampleLocationFlag = buffer_is_yuv444() ? 0 : 1; vui_config.chromaSampleLocationTop = 0; vui_config.chromaSampleLocationBot = 0; }; switch (client_config.videoFormat) { case 0: { // H.264 enc_config.profileGUID = buffer_is_yuv444() ? NV_ENC_H264_PROFILE_HIGH_444_GUID : NV_ENC_H264_PROFILE_HIGH_GUID; auto &format_config = enc_config.encodeCodecConfig.h264Config; set_h264_hevc_common_format_config(format_config); if (config.h264_cavlc || !get_encoder_cap(NV_ENC_CAPS_SUPPORT_CABAC)) { format_config.entropyCodingMode = NV_ENC_H264_ENTROPY_CODING_MODE_CAVLC; } else { format_config.entropyCodingMode = NV_ENC_H264_ENTROPY_CODING_MODE_CABAC; } set_ref_frames(format_config.maxNumRefFrames, format_config.numRefL0, 5); set_minqp_if_enabled(config.min_qp_h264); fill_h264_hevc_vui(format_config.h264VUIParameters); break; } case 1: { // HEVC auto &format_config = enc_config.encodeCodecConfig.hevcConfig; set_h264_hevc_common_format_config(format_config); if (buffer_is_10bit()) { format_config.pixelBitDepthMinus8 = 2; } set_ref_frames(format_config.maxNumRefFramesInDPB, format_config.numRefL0, 5); set_minqp_if_enabled(config.min_qp_hevc); fill_h264_hevc_vui(format_config.hevcVUIParameters); break; } case 2: { // AV1 auto &format_config = enc_config.encodeCodecConfig.av1Config; format_config.repeatSeqHdr = 1; format_config.idrPeriod = NVENC_INFINITE_GOPLENGTH; if (buffer_is_yuv444()) { format_config.chromaFormatIDC = 3; } format_config.enableBitstreamPadding = config.insert_filler_data; if (buffer_is_10bit()) { format_config.inputPixelBitDepthMinus8 = 2; format_config.pixelBitDepthMinus8 = 2; } format_config.colorPrimaries = colorspace.primaries; format_config.transferCharacteristics = colorspace.tranfer_function; format_config.matrixCoefficients = colorspace.matrix; format_config.colorRange = colorspace.full_range; format_config.chromaSamplePosition = buffer_is_yuv444() ? 0 : 1; set_ref_frames(format_config.maxNumRefFramesInDPB, format_config.numFwdRefs, 8); set_minqp_if_enabled(config.min_qp_av1); if (client_config.slicesPerFrame > 1) { // NVENC only supports slice counts that are powers of two, so we'll pick powers of two // with bias to rows due to hopefully more similar macroblocks with a row vs a column. format_config.numTileRows = std::pow(2, std::ceil(std::log2(client_config.slicesPerFrame) / 2)); format_config.numTileColumns = std::pow(2, std::floor(std::log2(client_config.slicesPerFrame) / 2)); } break; } } init_params.encodeConfig = &enc_config; if (nvenc_failed(nvenc->nvEncInitializeEncoder(encoder, &init_params))) { BOOST_LOG(error) << "NvEnc: NvEncInitializeEncoder() failed: " << last_nvenc_error_string; return false; } if (async_event_handle) { NV_ENC_EVENT_PARAMS event_params = { min_struct_version(NV_ENC_EVENT_PARAMS_VER) }; event_params.completionEvent = async_event_handle; if (nvenc_failed(nvenc->nvEncRegisterAsyncEvent(encoder, &event_params))) { BOOST_LOG(error) << "NvEnc: NvEncRegisterAsyncEvent() failed: " << last_nvenc_error_string; return false; } } NV_ENC_CREATE_BITSTREAM_BUFFER create_bitstream_buffer = { min_struct_version(NV_ENC_CREATE_BITSTREAM_BUFFER_VER) }; if (nvenc_failed(nvenc->nvEncCreateBitstreamBuffer(encoder, &create_bitstream_buffer))) { BOOST_LOG(error) << "NvEnc: NvEncCreateBitstreamBuffer() failed: " << last_nvenc_error_string; return false; } output_bitstream = create_bitstream_buffer.bitstreamBuffer; if (!create_and_register_input_buffer()) { return false; } { auto f = stat_trackers::two_digits_after_decimal(); BOOST_LOG(debug) << "NvEnc: requested encoded frame size " << f % (client_config.bitrate / 8. / client_config.framerate) << " kB"; } { auto video_format_string = client_config.videoFormat == 0 ? "H.264 " : client_config.videoFormat == 1 ? "HEVC " : client_config.videoFormat == 2 ? "AV1 " : " "; std::string extra; if (init_params.enableEncodeAsync) extra += " async"; if (buffer_is_yuv444()) extra += " yuv444"; if (buffer_is_10bit()) extra += " 10-bit"; if (enc_config.rcParams.multiPass != NV_ENC_MULTI_PASS_DISABLED) extra += " two-pass"; if (config.vbv_percentage_increase > 0 && get_encoder_cap(NV_ENC_CAPS_SUPPORT_CUSTOM_VBV_BUF_SIZE)) extra += " vbv+" + std::to_string(config.vbv_percentage_increase); if (encoder_params.rfi) extra += " rfi"; if (init_params.enableWeightedPrediction) extra += " weighted-prediction"; if (enc_config.rcParams.enableAQ) extra += " spatial-aq"; if (enc_config.rcParams.enableMinQP) extra += " qpmin=" + std::to_string(enc_config.rcParams.minQP.qpInterP); if (config.insert_filler_data) extra += " filler-data"; BOOST_LOG(info) << "NvEnc: created encoder " << video_format_string << quality_preset_string_from_guid(init_params.presetGUID) << extra; } encoder_state = {}; fail_guard.disable(); return true; } void nvenc_base::destroy_encoder() { if (output_bitstream) { if (nvenc_failed(nvenc->nvEncDestroyBitstreamBuffer(encoder, output_bitstream))) { BOOST_LOG(error) << "NvEnc: NvEncDestroyBitstreamBuffer() failed: " << last_nvenc_error_string; } output_bitstream = nullptr; } if (encoder && async_event_handle) { NV_ENC_EVENT_PARAMS event_params = { min_struct_version(NV_ENC_EVENT_PARAMS_VER) }; event_params.completionEvent = async_event_handle; if (nvenc_failed(nvenc->nvEncUnregisterAsyncEvent(encoder, &event_params))) { BOOST_LOG(error) << "NvEnc: NvEncUnregisterAsyncEvent() failed: " << last_nvenc_error_string; } } if (registered_input_buffer) { if (nvenc_failed(nvenc->nvEncUnregisterResource(encoder, registered_input_buffer))) { BOOST_LOG(error) << "NvEnc: NvEncUnregisterResource() failed: " << last_nvenc_error_string; } registered_input_buffer = nullptr; } if (encoder) { if (nvenc_failed(nvenc->nvEncDestroyEncoder(encoder))) { BOOST_LOG(error) << "NvEnc: NvEncDestroyEncoder() failed: " << last_nvenc_error_string; } encoder = nullptr; } encoder_state = {}; encoder_params = {}; } nvenc_encoded_frame nvenc_base::encode_frame(uint64_t frame_index, bool force_idr) { if (!encoder) { return {}; } assert(registered_input_buffer); assert(output_bitstream); if (!synchronize_input_buffer()) { BOOST_LOG(error) << "NvEnc: failed to synchronize input buffer"; return {}; } NV_ENC_MAP_INPUT_RESOURCE mapped_input_buffer = { min_struct_version(NV_ENC_MAP_INPUT_RESOURCE_VER) }; mapped_input_buffer.registeredResource = registered_input_buffer; if (nvenc_failed(nvenc->nvEncMapInputResource(encoder, &mapped_input_buffer))) { BOOST_LOG(error) << "NvEnc: NvEncMapInputResource() failed: " << last_nvenc_error_string; return {}; } auto unmap_guard = util::fail_guard([&] { if (nvenc_failed(nvenc->nvEncUnmapInputResource(encoder, mapped_input_buffer.mappedResource))) { BOOST_LOG(error) << "NvEnc: NvEncUnmapInputResource() failed: " << last_nvenc_error_string; } }); NV_ENC_PIC_PARAMS pic_params = { min_struct_version(NV_ENC_PIC_PARAMS_VER, 4, 6) }; pic_params.inputWidth = encoder_params.width; pic_params.inputHeight = encoder_params.height; pic_params.encodePicFlags = force_idr ? NV_ENC_PIC_FLAG_FORCEIDR : 0; pic_params.inputTimeStamp = frame_index; pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME; pic_params.inputBuffer = mapped_input_buffer.mappedResource; pic_params.bufferFmt = mapped_input_buffer.mappedBufferFmt; pic_params.outputBitstream = output_bitstream; pic_params.completionEvent = async_event_handle; if (nvenc_failed(nvenc->nvEncEncodePicture(encoder, &pic_params))) { BOOST_LOG(error) << "NvEnc: NvEncEncodePicture() failed: " << last_nvenc_error_string; return {}; } NV_ENC_LOCK_BITSTREAM lock_bitstream = { min_struct_version(NV_ENC_LOCK_BITSTREAM_VER, 1, 2) }; lock_bitstream.outputBitstream = output_bitstream; lock_bitstream.doNotWait = 0; if (async_event_handle && !wait_for_async_event(100)) { BOOST_LOG(error) << "NvEnc: frame " << frame_index << " encode wait timeout"; return {}; } if (nvenc_failed(nvenc->nvEncLockBitstream(encoder, &lock_bitstream))) { BOOST_LOG(error) << "NvEnc: NvEncLockBitstream() failed: " << last_nvenc_error_string; return {}; } auto data_pointer = (uint8_t *) lock_bitstream.bitstreamBufferPtr; nvenc_encoded_frame encoded_frame { { data_pointer, data_pointer + lock_bitstream.bitstreamSizeInBytes }, lock_bitstream.outputTimeStamp, lock_bitstream.pictureType == NV_ENC_PIC_TYPE_IDR, encoder_state.rfi_needs_confirmation, }; if (encoder_state.rfi_needs_confirmation) { // Invalidation request has been fulfilled, and video network packet will be marked as such encoder_state.rfi_needs_confirmation = false; } encoder_state.last_encoded_frame_index = frame_index; if (encoded_frame.idr) { BOOST_LOG(debug) << "NvEnc: idr frame " << encoded_frame.frame_index; } if (nvenc_failed(nvenc->nvEncUnlockBitstream(encoder, lock_bitstream.outputBitstream))) { BOOST_LOG(error) << "NvEnc: NvEncUnlockBitstream() failed: " << last_nvenc_error_string; } encoder_state.frame_size_logger.collect_and_log(encoded_frame.data.size() / 1000.); return encoded_frame; } bool nvenc_base::invalidate_ref_frames(uint64_t first_frame, uint64_t last_frame) { if (!encoder || !encoder_params.rfi) return false; if (first_frame >= encoder_state.last_rfi_range.first && last_frame <= encoder_state.last_rfi_range.second) { BOOST_LOG(debug) << "NvEnc: rfi request " << first_frame << "-" << last_frame << " already done"; return true; } encoder_state.rfi_needs_confirmation = true; if (last_frame < first_frame) { BOOST_LOG(error) << "NvEnc: invaid rfi request " << first_frame << "-" << last_frame << ", generating IDR"; return false; } BOOST_LOG(debug) << "NvEnc: rfi request " << first_frame << "-" << last_frame << " expanding to last encoded frame " << encoder_state.last_encoded_frame_index; last_frame = encoder_state.last_encoded_frame_index; encoder_state.last_rfi_range = { first_frame, last_frame }; if (last_frame - first_frame + 1 >= encoder_params.ref_frames_in_dpb) { BOOST_LOG(debug) << "NvEnc: rfi request too large, generating IDR"; return false; } for (auto i = first_frame; i <= last_frame; i++) { if (nvenc_failed(nvenc->nvEncInvalidateRefFrames(encoder, i))) { BOOST_LOG(error) << "NvEnc: NvEncInvalidateRefFrames() " << i << " failed: " << last_nvenc_error_string; return false; } } return true; } bool nvenc_base::nvenc_failed(NVENCSTATUS status) { auto status_string = [](NVENCSTATUS status) -> std::string { switch (status) { #define nvenc_status_case(x) \ case x: \ return #x; nvenc_status_case(NV_ENC_SUCCESS); nvenc_status_case(NV_ENC_ERR_NO_ENCODE_DEVICE); nvenc_status_case(NV_ENC_ERR_UNSUPPORTED_DEVICE); nvenc_status_case(NV_ENC_ERR_INVALID_ENCODERDEVICE); nvenc_status_case(NV_ENC_ERR_INVALID_DEVICE); nvenc_status_case(NV_ENC_ERR_DEVICE_NOT_EXIST); nvenc_status_case(NV_ENC_ERR_INVALID_PTR); nvenc_status_case(NV_ENC_ERR_INVALID_EVENT); nvenc_status_case(NV_ENC_ERR_INVALID_PARAM); nvenc_status_case(NV_ENC_ERR_INVALID_CALL); nvenc_status_case(NV_ENC_ERR_OUT_OF_MEMORY); nvenc_status_case(NV_ENC_ERR_ENCODER_NOT_INITIALIZED); nvenc_status_case(NV_ENC_ERR_UNSUPPORTED_PARAM); nvenc_status_case(NV_ENC_ERR_LOCK_BUSY); nvenc_status_case(NV_ENC_ERR_NOT_ENOUGH_BUFFER); nvenc_status_case(NV_ENC_ERR_INVALID_VERSION); nvenc_status_case(NV_ENC_ERR_MAP_FAILED); nvenc_status_case(NV_ENC_ERR_NEED_MORE_INPUT); nvenc_status_case(NV_ENC_ERR_ENCODER_BUSY); nvenc_status_case(NV_ENC_ERR_EVENT_NOT_REGISTERD); nvenc_status_case(NV_ENC_ERR_GENERIC); nvenc_status_case(NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY); nvenc_status_case(NV_ENC_ERR_UNIMPLEMENTED); nvenc_status_case(NV_ENC_ERR_RESOURCE_REGISTER_FAILED); nvenc_status_case(NV_ENC_ERR_RESOURCE_NOT_REGISTERED); nvenc_status_case(NV_ENC_ERR_RESOURCE_NOT_MAPPED); // Newer versions of sdk may add more constants, look for them at the end of NVENCSTATUS enum #undef nvenc_status_case default: return std::to_string(status); } }; last_nvenc_error_string.clear(); if (status != NV_ENC_SUCCESS) { /* This API function gives broken strings more often than not if (nvenc && encoder) { last_nvenc_error_string = nvenc->nvEncGetLastErrorString(encoder); if (!last_nvenc_error_string.empty()) last_nvenc_error_string += " "; } */ last_nvenc_error_string += status_string(status); return true; } return false; } uint32_t nvenc_base::min_struct_version(uint32_t version, uint32_t v11_struct_version, uint32_t v12_struct_version) { assert(minimum_api_version); // Mask off and replace the original NVENCAPI_VERSION version &= ~NVENCAPI_VERSION; version |= minimum_api_version; // If there's a struct version override, apply that too if (v11_struct_version || v12_struct_version) { version &= ~(0xFFu << 16); version |= (((minimum_api_version & 0xFF) >= 12) ? v12_struct_version : v11_struct_version) << 16; } return version; } } // namespace nvenc
26,090
C++
.cpp
543
39.987109
185
0.651954
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,993
wlgrab.cpp
LizardByte_Sunshine/src/platform/linux/wlgrab.cpp
/** * @file src/platform/linux/wlgrab.cpp * @brief Definitions for wlgrab capture. */ #include <thread> #include "src/platform/common.h" #include "src/logging.h" #include "src/video.h" #include "cuda.h" #include "vaapi.h" #include "wayland.h" using namespace std::literals; namespace wl { static int env_width; static int env_height; struct img_t: public platf::img_t { ~img_t() override { delete[] data; data = nullptr; } }; class wlr_t: public platf::display_t { public: int init(platf::mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config) { delay = std::chrono::nanoseconds { 1s } / config.framerate; mem_type = hwdevice_type; if (display.init()) { return -1; } interface.listen(display.registry()); display.roundtrip(); if (!interface[wl::interface_t::XDG_OUTPUT]) { BOOST_LOG(error) << "Missing Wayland wire for xdg_output"sv; return -1; } if (!interface[wl::interface_t::WLR_EXPORT_DMABUF]) { BOOST_LOG(error) << "Missing Wayland wire for wlr-export-dmabuf"sv; return -1; } auto monitor = interface.monitors[0].get(); if (!display_name.empty()) { auto streamedMonitor = util::from_view(display_name); if (streamedMonitor >= 0 && streamedMonitor < interface.monitors.size()) { monitor = interface.monitors[streamedMonitor].get(); } } monitor->listen(interface.output_manager); display.roundtrip(); output = monitor->output; offset_x = monitor->viewport.offset_x; offset_y = monitor->viewport.offset_y; width = monitor->viewport.width; height = monitor->viewport.height; this->env_width = ::wl::env_width; this->env_height = ::wl::env_height; BOOST_LOG(info) << "Selected monitor ["sv << monitor->description << "] for streaming"sv; BOOST_LOG(debug) << "Offset: "sv << offset_x << 'x' << offset_y; BOOST_LOG(debug) << "Resolution: "sv << width << 'x' << height; BOOST_LOG(debug) << "Desktop Resolution: "sv << env_width << 'x' << env_height; return 0; } int dummy_img(platf::img_t *img) override { return 0; } inline platf::capture_e snapshot(const pull_free_image_cb_t &pull_free_image_cb, std::shared_ptr<platf::img_t> &img_out, std::chrono::milliseconds timeout, bool cursor) { auto to = std::chrono::steady_clock::now() + timeout; // Dispatch events until we get a new frame or the timeout expires dmabuf.listen(interface.dmabuf_manager, output, cursor); do { auto remaining_time_ms = std::chrono::duration_cast<std::chrono::milliseconds>(to - std::chrono::steady_clock::now()); if (remaining_time_ms.count() < 0 || !display.dispatch(remaining_time_ms)) { return platf::capture_e::timeout; } } while (dmabuf.status == dmabuf_t::WAITING); auto current_frame = dmabuf.current_frame; if ( dmabuf.status == dmabuf_t::REINIT || current_frame->sd.width != width || current_frame->sd.height != height) { return platf::capture_e::reinit; } return platf::capture_e::ok; } platf::mem_type_e mem_type; std::chrono::nanoseconds delay; wl::display_t display; interface_t interface; dmabuf_t dmabuf; wl_output *output; }; class wlr_ram_t: public wlr_t { public: platf::capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor) override { auto next_frame = std::chrono::steady_clock::now(); sleep_overshoot_logger.reset(); while (true) { auto now = std::chrono::steady_clock::now(); if (next_frame > now) { std::this_thread::sleep_for(next_frame - now); sleep_overshoot_logger.first_point(next_frame); sleep_overshoot_logger.second_point_now_and_log(); } next_frame += delay; if (next_frame < now) { // some major slowdown happened; we couldn't keep up next_frame = now + delay; } std::shared_ptr<platf::img_t> img_out; auto status = snapshot(pull_free_image_cb, img_out, 1000ms, *cursor); switch (status) { case platf::capture_e::reinit: case platf::capture_e::error: case platf::capture_e::interrupted: return status; case platf::capture_e::timeout: if (!push_captured_image_cb(std::move(img_out), false)) { return platf::capture_e::ok; } break; case platf::capture_e::ok: if (!push_captured_image_cb(std::move(img_out), true)) { return platf::capture_e::ok; } break; default: BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']'; return status; } } return platf::capture_e::ok; } platf::capture_e snapshot(const pull_free_image_cb_t &pull_free_image_cb, std::shared_ptr<platf::img_t> &img_out, std::chrono::milliseconds timeout, bool cursor) { auto status = wlr_t::snapshot(pull_free_image_cb, img_out, timeout, cursor); if (status != platf::capture_e::ok) { return status; } auto current_frame = dmabuf.current_frame; auto rgb_opt = egl::import_source(egl_display.get(), current_frame->sd); if (!rgb_opt) { return platf::capture_e::reinit; } if (!pull_free_image_cb(img_out)) { return platf::capture_e::interrupted; } gl::ctx.BindTexture(GL_TEXTURE_2D, (*rgb_opt)->tex[0]); // Don't remove these lines, see https://github.com/LizardByte/Sunshine/issues/453 int w, h; gl::ctx.GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w); gl::ctx.GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h); BOOST_LOG(debug) << "width and height: w "sv << w << " h "sv << h; gl::ctx.GetTextureSubImage((*rgb_opt)->tex[0], 0, 0, 0, 0, width, height, 1, GL_BGRA, GL_UNSIGNED_BYTE, img_out->height * img_out->row_pitch, img_out->data); gl::ctx.BindTexture(GL_TEXTURE_2D, 0); return platf::capture_e::ok; } int init(platf::mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config) { if (wlr_t::init(hwdevice_type, display_name, config)) { return -1; } egl_display = egl::make_display(display.get()); if (!egl_display) { return -1; } auto ctx_opt = egl::make_ctx(egl_display.get()); if (!ctx_opt) { return -1; } ctx = std::move(*ctx_opt); return 0; } std::unique_ptr<platf::avcodec_encode_device_t> make_avcodec_encode_device(platf::pix_fmt_e pix_fmt) override { #ifdef SUNSHINE_BUILD_VAAPI if (mem_type == platf::mem_type_e::vaapi) { return va::make_avcodec_encode_device(width, height, false); } #endif #ifdef SUNSHINE_BUILD_CUDA if (mem_type == platf::mem_type_e::cuda) { return cuda::make_avcodec_encode_device(width, height, false); } #endif return std::make_unique<platf::avcodec_encode_device_t>(); } std::shared_ptr<platf::img_t> alloc_img() override { auto img = std::make_shared<img_t>(); img->width = width; img->height = height; img->pixel_pitch = 4; img->row_pitch = img->pixel_pitch * width; img->data = new std::uint8_t[height * img->row_pitch]; return img; } egl::display_t egl_display; egl::ctx_t ctx; }; class wlr_vram_t: public wlr_t { public: platf::capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor) override { auto next_frame = std::chrono::steady_clock::now(); sleep_overshoot_logger.reset(); while (true) { auto now = std::chrono::steady_clock::now(); if (next_frame > now) { std::this_thread::sleep_for(next_frame - now); sleep_overshoot_logger.first_point(next_frame); sleep_overshoot_logger.second_point_now_and_log(); } next_frame += delay; if (next_frame < now) { // some major slowdown happened; we couldn't keep up next_frame = now + delay; } std::shared_ptr<platf::img_t> img_out; auto status = snapshot(pull_free_image_cb, img_out, 1000ms, *cursor); switch (status) { case platf::capture_e::reinit: case platf::capture_e::error: case platf::capture_e::interrupted: return status; case platf::capture_e::timeout: if (!push_captured_image_cb(std::move(img_out), false)) { return platf::capture_e::ok; } break; case platf::capture_e::ok: if (!push_captured_image_cb(std::move(img_out), true)) { return platf::capture_e::ok; } break; default: BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']'; return status; } } return platf::capture_e::ok; } platf::capture_e snapshot(const pull_free_image_cb_t &pull_free_image_cb, std::shared_ptr<platf::img_t> &img_out, std::chrono::milliseconds timeout, bool cursor) { auto status = wlr_t::snapshot(pull_free_image_cb, img_out, timeout, cursor); if (status != platf::capture_e::ok) { return status; } if (!pull_free_image_cb(img_out)) { return platf::capture_e::interrupted; } auto img = (egl::img_descriptor_t *) img_out.get(); img->reset(); auto current_frame = dmabuf.current_frame; ++sequence; img->sequence = sequence; img->sd = current_frame->sd; // Prevent dmabuf from closing the file descriptors. std::fill_n(current_frame->sd.fds, 4, -1); return platf::capture_e::ok; } std::shared_ptr<platf::img_t> alloc_img() override { auto img = std::make_shared<egl::img_descriptor_t>(); img->width = width; img->height = height; img->sequence = 0; img->serial = std::numeric_limits<decltype(img->serial)>::max(); img->data = nullptr; // File descriptors aren't open std::fill_n(img->sd.fds, 4, -1); return img; } std::unique_ptr<platf::avcodec_encode_device_t> make_avcodec_encode_device(platf::pix_fmt_e pix_fmt) override { #ifdef SUNSHINE_BUILD_VAAPI if (mem_type == platf::mem_type_e::vaapi) { return va::make_avcodec_encode_device(width, height, 0, 0, true); } #endif #ifdef SUNSHINE_BUILD_CUDA if (mem_type == platf::mem_type_e::cuda) { return cuda::make_avcodec_gl_encode_device(width, height, 0, 0); } #endif return std::make_unique<platf::avcodec_encode_device_t>(); } int dummy_img(platf::img_t *img) override { // Empty images are recognized as dummies by the zero sequence number return 0; } std::uint64_t sequence {}; }; } // namespace wl namespace platf { std::shared_ptr<display_t> wl_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) { if (hwdevice_type != platf::mem_type_e::system && hwdevice_type != platf::mem_type_e::vaapi && hwdevice_type != platf::mem_type_e::cuda) { BOOST_LOG(error) << "Could not initialize display with the given hw device type."sv; return nullptr; } if (hwdevice_type == platf::mem_type_e::vaapi || hwdevice_type == platf::mem_type_e::cuda) { auto wlr = std::make_shared<wl::wlr_vram_t>(); if (wlr->init(hwdevice_type, display_name, config)) { return nullptr; } return wlr; } auto wlr = std::make_shared<wl::wlr_ram_t>(); if (wlr->init(hwdevice_type, display_name, config)) { return nullptr; } return wlr; } std::vector<std::string> wl_display_names() { std::vector<std::string> display_names; wl::display_t display; if (display.init()) { return {}; } wl::interface_t interface; interface.listen(display.registry()); display.roundtrip(); if (!interface[wl::interface_t::XDG_OUTPUT]) { BOOST_LOG(warning) << "Missing Wayland wire for xdg_output"sv; return {}; } if (!interface[wl::interface_t::WLR_EXPORT_DMABUF]) { BOOST_LOG(warning) << "Missing Wayland wire for wlr-export-dmabuf"sv; return {}; } wl::env_width = 0; wl::env_height = 0; for (auto &monitor : interface.monitors) { monitor->listen(interface.output_manager); } display.roundtrip(); BOOST_LOG(info) << "-------- Start of Wayland monitor list --------"sv; for (int x = 0; x < interface.monitors.size(); ++x) { auto monitor = interface.monitors[x].get(); wl::env_width = std::max(wl::env_width, (int) (monitor->viewport.offset_x + monitor->viewport.width)); wl::env_height = std::max(wl::env_height, (int) (monitor->viewport.offset_y + monitor->viewport.height)); BOOST_LOG(info) << "Monitor " << x << " is "sv << monitor->name << ": "sv << monitor->description; display_names.emplace_back(std::to_string(x)); } BOOST_LOG(info) << "--------- End of Wayland monitor list ---------"sv; return display_names; } } // namespace platf
13,595
C++
.cpp
351
31.581197
163
0.608447
LizardByte/Sunshine
18,156
876
103
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false