diff --git a/.gitignore b/.gitignore index 354eb09..f5227f7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ -SDK/ Release/ Debug/ src/Release/ diff --git a/SDK/foobar2000/SDK/abort_callback.cpp b/SDK/foobar2000/SDK/abort_callback.cpp new file mode 100644 index 0000000..4e27d52 --- /dev/null +++ b/SDK/foobar2000/SDK/abort_callback.cpp @@ -0,0 +1,24 @@ +#include "foobar2000.h" + +void abort_callback::check() const { + if (is_aborting()) throw exception_aborted(); +} + +void abort_callback::sleep(double p_timeout_seconds) const { + if (!sleep_ex(p_timeout_seconds)) throw exception_aborted(); +} + +bool abort_callback::sleep_ex(double p_timeout_seconds) const { + // return true IF NOT SET (timeout), false if set + return !pfc::event::g_wait_for(get_abort_event(),p_timeout_seconds); +} + +bool abort_callback::waitForEvent( pfc::eventHandle_t evtHandle, double timeOut ) { + int status = pfc::event::g_twoEventWait( this->get_abort_event(), evtHandle, timeOut ); + switch(status) { + case 1: throw exception_aborted(); + case 2: return true; + case 0: return false; + default: uBugCheck(); + } +} diff --git a/SDK/foobar2000/SDK/abort_callback.h b/SDK/foobar2000/SDK/abort_callback.h new file mode 100644 index 0000000..c814055 --- /dev/null +++ b/SDK/foobar2000/SDK/abort_callback.h @@ -0,0 +1,104 @@ +#ifndef _foobar2000_sdk_abort_callback_h_ +#define _foobar2000_sdk_abort_callback_h_ + +namespace foobar2000_io { + +PFC_DECLARE_EXCEPTION(exception_aborted,pfc::exception,"User abort"); + +typedef pfc::eventHandle_t abort_callback_event; + +#ifdef check +#undef check +#endif +//! This class is used to signal underlying worker code whether user has decided to abort a potentially time-consuming operation. \n +//! It is commonly required by all filesystem related or decoding-related operations. \n +//! Code that receives an abort_callback object should periodically check it and abort any operations being performed if it is signaled, typically throwing exception_aborted. \n +//! See abort_callback_impl for an implementation. +class NOVTABLE abort_callback +{ +public: + //! Returns whether user has requested the operation to be aborted. + virtual bool is_aborting() const = 0; + + inline bool is_set() const {return is_aborting();} + + //! Retrieves event object that can be used with some OS calls. The even object becomes signaled when abort is triggered. On win32, this is equivalent to win32 event handle (see: CreateEvent). \n + //! You must not close this handle or call any methods that change this handle's state (SetEvent() or ResetEvent()), you can only wait for it. + virtual abort_callback_event get_abort_event() const = 0; + + inline abort_callback_event get_handle() const {return get_abort_event();} + + //! Checks if user has requested the operation to be aborted, and throws exception_aborted if so. + void check() const; + + //! For compatibility with old code. Do not call. + inline void check_e() const {check();} + + + //! Sleeps p_timeout_seconds or less when aborted, throws exception_aborted on abort. + void sleep(double p_timeout_seconds) const; + //! Sleeps p_timeout_seconds or less when aborted, returns true when execution should continue, false when not. + bool sleep_ex(double p_timeout_seconds) const; + + bool waitForEvent( pfc::eventHandle_t evtHandle, double timeOut ); + bool waitForEvent( pfc::event & evt, double timeOut ) {return waitForEvent( evt.get_handle(), timeOut ); } +protected: + abort_callback() {} + ~abort_callback() {} +}; + + + +//! Implementation of abort_callback interface. +class abort_callback_impl : public abort_callback { +public: + abort_callback_impl() : m_aborting(false) {} + inline void abort() {set_state(true);} + inline void set() {set_state(true);} + inline void reset() {set_state(false);} + + void set_state(bool p_state) {m_aborting = p_state; m_event.set_state(p_state);} + + bool is_aborting() const {return m_aborting;} + + abort_callback_event get_abort_event() const {return m_event.get_handle();} + +private: + abort_callback_impl(const abort_callback_impl &); + const abort_callback_impl & operator=(const abort_callback_impl&); + + volatile bool m_aborting; + pfc::event m_event; +}; + +#ifdef _WIN32 +//! Dummy abort_callback that never gets aborted. \n +//! Slightly more efficient than the regular one especially when you need to regularly create temporary instances of it. +class abort_callback_dummy : public abort_callback { +public: + bool is_aborting() const { return false; } + + abort_callback_event get_abort_event() const { return GetInfiniteWaitEvent();} +}; +#else + +// FIX ME come up with a scheme to produce a persistent infinite wait filedescriptor on non Windows +// Could use /dev/null but still need to open it on upon object creation which defeats the purpose +typedef abort_callback_impl abort_callback_dummy; + +#endif + +} +typedef foobar2000_io::abort_callback_event fb2k_event_handle; +typedef foobar2000_io::abort_callback fb2k_event; +typedef foobar2000_io::abort_callback_impl fb2k_event_impl; + +using namespace foobar2000_io; + +#define FB2K_PFCv2_ABORTER_SCOPE( abortObj ) \ + (abortObj).check(); \ + PP::waitableReadRef_t aborterRef = {(abortObj).get_abort_event()}; \ + PP::aborter aborter_pfcv2( aborterRef ); \ + PP::aborterScope l_aborterScope( aborter_pfcv2 ); + +#endif //_foobar2000_sdk_abort_callback_h_ diff --git a/SDK/foobar2000/SDK/advconfig.cpp b/SDK/foobar2000/SDK/advconfig.cpp new file mode 100644 index 0000000..6da30c7 --- /dev/null +++ b/SDK/foobar2000/SDK/advconfig.cpp @@ -0,0 +1,39 @@ +#include "foobar2000.h" + + +t_uint32 advconfig_entry::get_preferences_flags_() { + { + advconfig_entry_string_v2::ptr ex; + if (service_query_t(ex)) return ex->get_preferences_flags(); + } + { + advconfig_entry_checkbox_v2::ptr ex; + if (service_query_t(ex)) return ex->get_preferences_flags(); + } + return 0; +} + +bool advconfig_entry_checkbox::get_default_state_() { + { + advconfig_entry_checkbox_v2::ptr ex; + if (service_query_t(ex)) return ex->get_default_state(); + } + + bool backup = get_state(); + reset(); + bool rv = get_state(); + set_state(backup); + return rv; +} + +void advconfig_entry_string::get_default_state_(pfc::string_base & out) { + { + advconfig_entry_string_v2::ptr ex; + if (service_query_t(ex)) {ex->get_default_state(out); return;} + } + pfc::string8 backup; + get_state(backup); + reset(); + get_state(out); + set_state(backup); +} diff --git a/SDK/foobar2000/SDK/advconfig.h b/SDK/foobar2000/SDK/advconfig.h new file mode 100644 index 0000000..d2f68ff --- /dev/null +++ b/SDK/foobar2000/SDK/advconfig.h @@ -0,0 +1,311 @@ +//! Entrypoint class for adding items to Advanced Preferences page. \n +//! Implementations must derive from one of subclasses: advconfig_branch, advconfig_entry_checkbox, advconfig_entry_string. \n +//! Implementations are typically registered using static service_factory_single_t, or using provided helper classes in case of standard implementations declared in this header. +class NOVTABLE advconfig_entry : public service_base { +public: + virtual void get_name(pfc::string_base & p_out) = 0; + virtual GUID get_guid() = 0; + virtual GUID get_parent() = 0; + virtual void reset() = 0; + virtual double get_sort_priority() = 0; + + t_uint32 get_preferences_flags_(); + + static bool g_find(service_ptr_t& out, const GUID & id) { + service_enum_t e; service_ptr_t ptr; while(e.next(ptr)) { if (ptr->get_guid() == id) {out = ptr; return true;} } return false; + } + + template static bool g_find_t(outptr & out, const GUID & id) { + service_ptr_t temp; + if (!g_find(temp, id)) return false; + return temp->service_query_t(out); + } + + static const GUID guid_root; + static const GUID guid_branch_tagging,guid_branch_decoding,guid_branch_tools,guid_branch_playback,guid_branch_display; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(advconfig_entry); +}; + +//! Creates a new branch in Advanced Preferences. \n +//! Implementation: see advconfig_branch_impl / advconfig_branch_factory. +class NOVTABLE advconfig_branch : public advconfig_entry { +public: + FB2K_MAKE_SERVICE_INTERFACE(advconfig_branch,advconfig_entry); +}; + +//! Creates a checkbox/radiocheckbox entry in Advanced Preferences. \n +//! The difference between checkboxes and radiocheckboxes is different icon (obviously) and that checking a radiocheckbox unchecks all other radiocheckboxes in the same branch. \n +//! Implementation: see advconfig_entry_checkbox_impl / advconfig_checkbox_factory_t. +class NOVTABLE advconfig_entry_checkbox : public advconfig_entry { +public: + virtual bool get_state() = 0; + virtual void set_state(bool p_state) = 0; + virtual bool is_radio() = 0; + + bool get_default_state_(); + + FB2K_MAKE_SERVICE_INTERFACE(advconfig_entry_checkbox,advconfig_entry); +}; + +class NOVTABLE advconfig_entry_checkbox_v2 : public advconfig_entry_checkbox { + FB2K_MAKE_SERVICE_INTERFACE(advconfig_entry_checkbox_v2, advconfig_entry_checkbox) +public: + virtual bool get_default_state() = 0; + virtual t_uint32 get_preferences_flags() {return 0;} //signals whether changing this setting should trigger playback restart or app restart; see: preferences_state::* constants +}; + +//! Creates a string/integer editbox entry in Advanced Preferences.\n +//! Implementation: see advconfig_entry_string_impl / advconfig_string_factory. +class NOVTABLE advconfig_entry_string : public advconfig_entry { +public: + virtual void get_state(pfc::string_base & p_out) = 0; + virtual void set_state(const char * p_string,t_size p_length = ~0) = 0; + virtual t_uint32 get_flags() = 0; + + void get_default_state_(pfc::string_base & out); + + enum { + flag_is_integer = 1 << 0, + flag_is_signed = 1 << 1, + }; + + FB2K_MAKE_SERVICE_INTERFACE(advconfig_entry_string,advconfig_entry); +}; + +class NOVTABLE advconfig_entry_string_v2 : public advconfig_entry_string { + FB2K_MAKE_SERVICE_INTERFACE(advconfig_entry_string_v2, advconfig_entry_string) +public: + virtual void get_default_state(pfc::string_base & out) = 0; + virtual void validate(pfc::string_base & val) {} + virtual t_uint32 get_preferences_flags() {return 0;} //signals whether changing this setting should trigger playback restart or app restart; see: preferences_state::* constants +}; + + +//! Standard implementation of advconfig_branch. \n +//! Usage: no need to use this class directly - use advconfig_branch_factory instead. +class advconfig_branch_impl : public advconfig_branch { +public: + advconfig_branch_impl(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority) : m_name(p_name), m_guid(p_guid), m_parent(p_parent), m_priority(p_priority) {} + void get_name(pfc::string_base & p_out) {p_out = m_name;} + GUID get_guid() {return m_guid;} + GUID get_parent() {return m_parent;} + void reset() {} + double get_sort_priority() {return m_priority;} +private: + pfc::string8 m_name; + GUID m_guid,m_parent; + const double m_priority; +}; + +//! Standard implementation of advconfig_entry_checkbox. \n +//! p_is_radio parameter controls whether we're implementing a checkbox or a radiocheckbox (see advconfig_entry_checkbox description for more details). +template +class advconfig_entry_checkbox_impl : public advconfig_entry_checkbox_v2 { +public: + advconfig_entry_checkbox_impl(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority,bool p_initialstate) + : m_name(p_name), m_initialstate(p_initialstate), m_state(p_guid,p_initialstate), m_parent(p_parent), m_priority(p_priority) {} + + void get_name(pfc::string_base & p_out) {p_out = m_name;} + GUID get_guid() {return m_state.get_guid();} + GUID get_parent() {return m_parent;} + void reset() {m_state = m_initialstate;} + bool get_state() {return m_state;} + void set_state(bool p_state) {m_state = p_state;} + bool is_radio() {return p_is_radio;} + double get_sort_priority() {return m_priority;} + bool get_state_() const {return m_state;} + bool get_default_state() {return m_initialstate;} + bool get_default_state_() const {return m_initialstate;} + t_uint32 get_preferences_flags() {return prefFlags;} +private: + pfc::string8 m_name; + const bool m_initialstate; + cfg_bool m_state; + GUID m_parent; + const double m_priority; +}; + +//! Service factory helper around standard advconfig_branch implementation. Use this class to register your own Advanced Preferences branches. \n +//! Usage: static advconfig_branch_factory mybranch(name, branchID, parentBranchID, priority); +class advconfig_branch_factory : public service_factory_single_t { +public: + advconfig_branch_factory(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority) + : service_factory_single_t(p_name,p_guid,p_parent,p_priority) {} +}; + +//! Service factory helper around standard advconfig_entry_checkbox implementation. Use this class to register your own Advanced Preferences checkbox/radiocheckbox entries. \n +//! Usage: static advconfig_entry_checkbox mybox(name, itemID, parentID, priority, initialstate); +template +class advconfig_checkbox_factory_t : public service_factory_single_t > { +public: + advconfig_checkbox_factory_t(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority,bool p_initialstate) + : service_factory_single_t >(p_name,p_guid,p_parent,p_priority,p_initialstate) {} + + bool get() const {return this->get_static_instance().get_state_();} + void set(bool val) {this->get_static_instance().set_state(val);} + operator bool() const {return get();} + bool operator=(bool val) {set(val); return val;} +}; + +//! Service factory helper around standard advconfig_entry_checkbox implementation, specialized for checkboxes (rather than radiocheckboxes). See advconfig_checkbox_factory_t<> for more details. +typedef advconfig_checkbox_factory_t advconfig_checkbox_factory; +//! Service factory helper around standard advconfig_entry_checkbox implementation, specialized for radiocheckboxes (rather than standard checkboxes). See advconfig_checkbox_factory_t<> for more details. +typedef advconfig_checkbox_factory_t advconfig_radio_factory; + + +//! Standard advconfig_entry_string implementation. Use advconfig_string_factory to register your own string entries in Advanced Preferences instead of using this class directly. +class advconfig_entry_string_impl : public advconfig_entry_string_v2 { +public: + advconfig_entry_string_impl(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority,const char * p_initialstate, t_uint32 p_prefFlags) + : m_name(p_name), m_parent(p_parent), m_priority(p_priority), m_initialstate(p_initialstate), m_state(p_guid,p_initialstate), m_prefFlags(p_prefFlags) {} + void get_name(pfc::string_base & p_out) {p_out = m_name;} + GUID get_guid() {return m_state.get_guid();} + GUID get_parent() {return m_parent;} + void reset() {core_api::ensure_main_thread();m_state = m_initialstate;} + double get_sort_priority() {return m_priority;} + void get_state(pfc::string_base & p_out) {core_api::ensure_main_thread();p_out = m_state;} + void set_state(const char * p_string,t_size p_length = ~0) {core_api::ensure_main_thread();m_state.set_string(p_string,p_length);} + t_uint32 get_flags() {return 0;} + void get_default_state(pfc::string_base & out) {out = m_initialstate;} + t_uint32 get_preferences_flags() {return m_prefFlags;} +private: + const pfc::string8 m_initialstate, m_name; + cfg_string m_state; + const double m_priority; + const GUID m_parent; + const t_uint32 m_prefFlags; +}; + +//! Service factory helper around standard advconfig_entry_string implementation. Use this class to register your own string entries in Advanced Preferences. \n +//! Usage: static advconfig_string_factory mystring(name, itemID, branchID, priority, initialValue); +class advconfig_string_factory : public service_factory_single_t { +public: + advconfig_string_factory(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority,const char * p_initialstate, t_uint32 p_prefFlags = 0) + : service_factory_single_t(p_name,p_guid,p_parent,p_priority,p_initialstate, p_prefFlags) {} + + void get(pfc::string_base & out) {get_static_instance().get_state(out);} + void set(const char * in) {get_static_instance().set_state(in);} +}; + + +//! Special advconfig_entry_string implementation - implements integer entries. Use advconfig_integer_factory to register your own integer entries in Advanced Preferences instead of using this class directly. +class advconfig_entry_integer_impl : public advconfig_entry_string_v2 { +public: + advconfig_entry_integer_impl(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority,t_uint64 p_initialstate,t_uint64 p_min,t_uint64 p_max, t_uint32 p_prefFlags) + : m_name(p_name), m_parent(p_parent), m_priority(p_priority), m_initval(p_initialstate), m_min(p_min), m_max(p_max), m_state(p_guid,p_initialstate), m_prefFlags(p_prefFlags) {} + void get_name(pfc::string_base & p_out) {p_out = m_name;} + GUID get_guid() {return m_state.get_guid();} + GUID get_parent() {return m_parent;} + void reset() {m_state = m_initval;} + double get_sort_priority() {return m_priority;} + void get_state(pfc::string_base & p_out) {p_out = pfc::format_uint(m_state.get_value());} + void set_state(const char * p_string,t_size p_length) {set_state_int(pfc::atoui64_ex(p_string,p_length));} + t_uint32 get_flags() {return advconfig_entry_string::flag_is_integer;} + + t_uint64 get_state_int() const {return m_state;} + void set_state_int(t_uint64 val) {m_state = pfc::clip_t(val,m_min,m_max);} + + void get_default_state(pfc::string_base & out) { + out = pfc::format_uint(m_initval); + } + void validate(pfc::string_base & val) { + val = pfc::format_uint( pfc::clip_t(pfc::atoui64_ex(val,~0), m_min, m_max) ); + } + t_uint32 get_preferences_flags() {return m_prefFlags;} +private: + cfg_int_t m_state; + const double m_priority; + const t_uint64 m_initval, m_min, m_max; + const GUID m_parent; + const pfc::string8 m_name; + const t_uint32 m_prefFlags; +}; + +//! Service factory helper around integer-specialized advconfig_entry_string implementation. Use this class to register your own integer entries in Advanced Preferences. \n +//! Usage: static advconfig_integer_factory myint(name, itemID, parentID, priority, initialValue, minValue, maxValue); +class advconfig_integer_factory : public service_factory_single_t { +public: + advconfig_integer_factory(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority,t_uint64 p_initialstate,t_uint64 p_min,t_uint64 p_max, t_uint32 p_prefFlags = 0) + : service_factory_single_t(p_name,p_guid,p_parent,p_priority,p_initialstate,p_min,p_max,p_prefFlags) {} + + t_uint64 get() const {return get_static_instance().get_state_int();} + void set(t_uint64 val) {get_static_instance().set_state_int(val);} + + operator t_uint64() const {return get();} + t_uint64 operator=(t_uint64 val) {set(val); return val;} +}; + + +//! Not currently used, reserved for future use. +class NOVTABLE advconfig_entry_enum : public advconfig_entry { +public: + virtual t_size get_value_count() = 0; + virtual void enum_value(pfc::string_base & p_out,t_size p_index) = 0; + virtual t_size get_state() = 0; + virtual void set_state(t_size p_value) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(advconfig_entry_enum,advconfig_entry); +}; + + + + +//! Special version if advconfig_entry_string_impl that allows the value to be retrieved from worker threads. +class advconfig_entry_string_impl_MT : public advconfig_entry_string_v2 { +public: + advconfig_entry_string_impl_MT(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority,const char * p_initialstate, t_uint32 p_prefFlags) + : m_name(p_name), m_parent(p_parent), m_priority(p_priority), m_initialstate(p_initialstate), m_state(p_guid,p_initialstate), m_prefFlags(p_prefFlags) {} + void get_name(pfc::string_base & p_out) {p_out = m_name;} + GUID get_guid() {return m_state.get_guid();} + GUID get_parent() {return m_parent;} + void reset() { + insync(m_sync); + m_state = m_initialstate; + } + double get_sort_priority() {return m_priority;} + void get_state(pfc::string_base & p_out) { + insync(m_sync); + p_out = m_state; + } + void set_state(const char * p_string,t_size p_length = ~0) { + insync(m_sync); + m_state.set_string(p_string,p_length); + } + t_uint32 get_flags() {return 0;} + void get_default_state(pfc::string_base & out) {out = m_initialstate;} + t_uint32 get_preferences_flags() {return m_prefFlags;} +private: + const pfc::string8 m_initialstate, m_name; + cfg_string m_state; + critical_section m_sync; + const double m_priority; + const GUID m_parent; + const t_uint32 m_prefFlags; +}; + +//! Special version if advconfig_string_factory that allows the value to be retrieved from worker threads. +class advconfig_string_factory_MT : public service_factory_single_t { +public: + advconfig_string_factory_MT(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority,const char * p_initialstate, t_uint32 p_prefFlags = 0) + : service_factory_single_t(p_name,p_guid,p_parent,p_priority,p_initialstate, p_prefFlags) {} + + void get(pfc::string_base & out) {get_static_instance().get_state(out);} + void set(const char * in) {get_static_instance().set_state(in);} +}; + + + + +/* + Advanced Preferences variable declaration examples + + static advconfig_string_factory mystring("name goes here",myguid,parentguid,0,"asdf"); + to retrieve state: pfc::string8 val; mystring.get(val); + + static advconfig_checkbox_factory mycheckbox("name goes here",myguid,parentguid,0,false); + to retrieve state: mycheckbox.get(); + + static advconfig_integer_factory myint("name goes here",myguid,parentguid,0,initialValue,minimumValue,maximumValue); + to retrieve state: myint.get(); +*/ diff --git a/SDK/foobar2000/SDK/album_art.cpp b/SDK/foobar2000/SDK/album_art.cpp new file mode 100644 index 0000000..50ec136 --- /dev/null +++ b/SDK/foobar2000/SDK/album_art.cpp @@ -0,0 +1,48 @@ +#include "foobar2000.h" + +bool album_art_editor::g_get_interface(service_ptr_t & out,const char * path) { + service_enum_t e; ptr ptr; + pfc::string_extension ext(path); + while(e.next(ptr)) { + if (ptr->is_our_path(path,ext)) { out = ptr; return true; } + } + return false; +} + +bool album_art_editor::g_is_supported_path(const char * path) { + ptr ptr; return g_get_interface(ptr,path); +} + +album_art_editor_instance_ptr album_art_editor::g_open(file_ptr p_filehint,const char * p_path,abort_callback & p_abort) { + album_art_editor::ptr obj; + if (!g_get_interface(obj, p_path)) throw exception_album_art_unsupported_format(); + return obj->open(p_filehint, p_path, p_abort); +} + + +bool album_art_extractor::g_get_interface(service_ptr_t & out,const char * path) { + service_enum_t e; ptr ptr; + pfc::string_extension ext(path); + while(e.next(ptr)) { + if (ptr->is_our_path(path,ext)) { out = ptr; return true; } + } + return false; +} + +bool album_art_extractor::g_is_supported_path(const char * path) { + ptr ptr; return g_get_interface(ptr,path); +} +album_art_extractor_instance_ptr album_art_extractor::g_open(file_ptr p_filehint,const char * p_path,abort_callback & p_abort) { + album_art_extractor::ptr obj; + if (!g_get_interface(obj, p_path)) throw exception_album_art_unsupported_format(); + return obj->open(p_filehint, p_path, p_abort); +} + + +album_art_extractor_instance_ptr album_art_extractor::g_open_allowempty(file_ptr p_filehint,const char * p_path,abort_callback & p_abort) { + try { + return g_open(p_filehint, p_path, p_abort); + } catch(exception_album_art_not_found) { + return new service_impl_t(); + } +} diff --git a/SDK/foobar2000/SDK/album_art.h b/SDK/foobar2000/SDK/album_art.h new file mode 100644 index 0000000..4d8916d --- /dev/null +++ b/SDK/foobar2000/SDK/album_art.h @@ -0,0 +1,196 @@ +//! Common class for handling picture data. \n +//! Type of contained picture data is unknown and to be determined according to memory block contents by code parsing/rendering the picture. Commonly encountered types are: BMP, PNG, JPEG and GIF. \n +//! Implementation: use album_art_data_impl. +class NOVTABLE album_art_data : public service_base { +public: + //! Retrieves a pointer to a memory block containing the picture. + virtual const void * get_ptr() const = 0; + //! Retrieves size of the memory block containing the picture. + virtual t_size get_size() const = 0; + + //! Determine whether two album_art_data objects store the same picture data. + static bool equals(album_art_data const & v1, album_art_data const & v2) { + const t_size s = v1.get_size(); + if (s != v2.get_size()) return false; + return memcmp(v1.get_ptr(), v2.get_ptr(),s) == 0; + } + bool operator==(const album_art_data & other) const {return equals(*this,other);} + bool operator!=(const album_art_data & other) const {return !equals(*this,other);} + + FB2K_MAKE_SERVICE_INTERFACE(album_art_data,service_base); +}; + +typedef service_ptr_t album_art_data_ptr; + +//! Namespace containing identifiers of album art types. +namespace album_art_ids { + //! Front cover. + static const GUID cover_front = { 0xf1e66f4e, 0xfe09, 0x4b94, { 0x91, 0xa3, 0x67, 0xc2, 0x3e, 0xd1, 0x44, 0x5e } }; + //! Back cover. + static const GUID cover_back = { 0xcb552d19, 0x86d5, 0x434c, { 0xac, 0x77, 0xbb, 0x24, 0xed, 0x56, 0x7e, 0xe4 } }; + //! Picture of a disc or other storage media. + static const GUID disc = { 0x3dba9f36, 0xf928, 0x4fa4, { 0x87, 0x9c, 0xd3, 0x40, 0x47, 0x59, 0x58, 0x7e } }; + //! Album-specific icon (NOT a file type icon). + static const GUID icon = { 0x74cdf5b4, 0x7053, 0x4b3d, { 0x9a, 0x3c, 0x54, 0x69, 0xf5, 0x82, 0x6e, 0xec } }; + //! Artist picture. + static const GUID artist = { 0x9a654042, 0xacd1, 0x43f7, { 0xbf, 0xcf, 0xd3, 0xec, 0xf, 0xfe, 0x40, 0xfa } }; + +}; + +PFC_DECLARE_EXCEPTION(exception_album_art_not_found,exception_io_not_found,"Attached picture not found"); +PFC_DECLARE_EXCEPTION(exception_album_art_unsupported_entry,exception_io_data,"Unsupported attached picture entry"); + +PFC_DECLARE_EXCEPTION(exception_album_art_unsupported_format,exception_io_data,"Attached picture operations not supported for this file format"); + +//! Class encapsulating access to album art stored in a media file. Use album_art_extractor class obtain album_art_extractor_instance referring to specified media file. +class NOVTABLE album_art_extractor_instance : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(album_art_extractor_instance,service_base); +public: + //! Throws exception_album_art_not_found when the requested album art entry could not be found in the referenced media file. + virtual album_art_data_ptr query(const GUID & p_what,abort_callback & p_abort) = 0; + + bool query(const GUID & what, album_art_data::ptr & out, abort_callback & abort) { + try { out = query(what, abort); return true; } catch(exception_album_art_not_found) { return false; } + } +}; + +//! Class encapsulating access to album art stored in a media file. Use album_art_editor class to obtain album_art_editor_instance referring to specified media file. +class NOVTABLE album_art_editor_instance : public album_art_extractor_instance { + FB2K_MAKE_SERVICE_INTERFACE(album_art_editor_instance,album_art_extractor_instance); +public: + //! Throws exception_album_art_unsupported_entry when the file format we're dealing with does not support specific entry. + virtual void set(const GUID & p_what,album_art_data_ptr p_data,abort_callback & p_abort) = 0; + + //! Removes the requested entry. Fails silently when the entry doesn't exist. + virtual void remove(const GUID & p_what) = 0; + + //! Finalizes file tag update operation. + virtual void commit(abort_callback & p_abort) = 0; +}; + +class NOVTABLE album_art_editor_instance_v2 : public album_art_editor_instance { + FB2K_MAKE_SERVICE_INTERFACE(album_art_editor_instance_v2, album_art_editor_instance); +public: + //! Tells the editor to remove all entries, including unsupported picture types that do not translate to fb2k ids. + virtual void remove_all() = 0; +}; + +typedef service_ptr_t album_art_extractor_instance_ptr; +typedef service_ptr_t album_art_editor_instance_ptr; + +//! Entrypoint class for accessing album art extraction functionality. Register your own implementation to allow album art extraction from your media file format. \n +//! If you want to extract album art from a media file, it's recommended that you use album_art_manager API instead of calling album_art_extractor directly. +class NOVTABLE album_art_extractor : public service_base { +public: + //! Returns whether the specified file is one of formats supported by our album_art_extractor implementation. + //! @param p_path Path to file being queried. + //! @param p_extension Extension of file being queried (also present in p_path parameter) - provided as a separate parameter for performance reasons. + virtual bool is_our_path(const char * p_path,const char * p_extension) = 0; + + //! Instantiates album_art_extractor_instance providing access to album art stored in a specified media file. \n + //! Throws one of I/O exceptions on failure; exception_album_art_not_found when the file has no album art record at all. + //! @param p_filehint Optional; specifies a file interface to use for accessing the specified file; can be null - in that case, the implementation will open and close the file internally. + virtual album_art_extractor_instance_ptr open(file_ptr p_filehint,const char * p_path,abort_callback & p_abort) = 0; + + static bool g_get_interface(service_ptr_t & out,const char * path); + static bool g_is_supported_path(const char * path); + static album_art_extractor_instance_ptr g_open(file_ptr p_filehint,const char * p_path,abort_callback & p_abort); + static album_art_extractor_instance_ptr g_open_allowempty(file_ptr p_filehint,const char * p_path,abort_callback & p_abort); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(album_art_extractor); +}; + +//! Entrypoint class for accessing album art editing functionality. Register your own implementation to allow album art editing on your media file format. +class NOVTABLE album_art_editor : public service_base { +public: + //! Returns whether the specified file is one of formats supported by our album_art_editor implementation. + //! @param p_path Path to file being queried. + //! @param p_extension Extension of file being queried (also present in p_path parameter) - provided as a separate parameter for performance reasons. + virtual bool is_our_path(const char * p_path,const char * p_extension) = 0; + + //! Instantiates album_art_editor_instance providing access to album art stored in a specified media file. \n + //! @param p_filehint Optional; specifies a file interface to use for accessing the specified file; can be null - in that case, the implementation will open and close the file internally. + virtual album_art_editor_instance_ptr open(file_ptr p_filehint,const char * p_path,abort_callback & p_abort) = 0; + + //! Helper; attempts to retrieve an album_art_editor service pointer that supports the specified file. + //! @returns True on success, false on failure (no registered album_art_editor supports this file type). + static bool g_get_interface(service_ptr_t & out,const char * path); + //! Helper; returns whether one of registered album_art_editor implementations is capable of opening the specified file. + static bool g_is_supported_path(const char * path); + + static album_art_editor_instance_ptr g_open(file_ptr p_filehint,const char * p_path,abort_callback & p_abort); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(album_art_editor); +}; + + +//! Helper API for extracting album art from APEv2 tags - introduced in 0.9.5. +class NOVTABLE tag_processor_album_art_utils : public service_base { +public: + + //! Throws one of I/O exceptions on failure; exception_album_art_not_found when the file has no album art record at all. + virtual album_art_extractor_instance_ptr open(file_ptr p_file,abort_callback & p_abort) = 0; + + //! \since 1.1.6 + //! Throws exception_not_implemented on earlier than 1.1.6. + virtual album_art_editor_instance_ptr edit(file_ptr p_file,abort_callback & p_abort) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(tag_processor_album_art_utils) +}; + + +//! Album art path list - see album_art_extractor_instance_v2 +class NOVTABLE album_art_path_list : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(album_art_path_list, service_base) +public: + virtual const char * get_path(t_size index) const = 0; + virtual t_size get_count() const = 0; +}; + +//! album_art_extractor_instance extension; lets the frontend query referenced file paths (eg. when using external album art). +class NOVTABLE album_art_extractor_instance_v2 : public album_art_extractor_instance { + FB2K_MAKE_SERVICE_INTERFACE(album_art_extractor_instance_v2, album_art_extractor_instance) +public: + virtual album_art_path_list::ptr query_paths(const GUID & p_what, abort_callback & p_abort) = 0; +}; + + +//! \since 1.0 +//! Provides methods for interfacing with the foobar2000 core album art loader. \n +//! Use this when you need to load album art for a specific group of tracks. +class NOVTABLE album_art_manager_v2 : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(album_art_manager_v2) +public: + //! Instantiates an album art extractor object for the specified group of items. + virtual album_art_extractor_instance_v2::ptr open(metadb_handle_list_cref items, pfc::list_base_const_t const & ids, abort_callback & abort) = 0; + + //! Instantiates an album art extractor object that retrieves stub images. + virtual album_art_extractor_instance_v2::ptr open_stub(abort_callback & abort) = 0; +}; + + +//! \since 1.0 +//! Called when no other album art source (internal, external, other registered fallbacks) returns relevant data for the specified items. \n +//! Can be used to implement online lookup and such. +class NOVTABLE album_art_fallback : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(album_art_fallback) +public: + virtual album_art_extractor_instance_v2::ptr open(metadb_handle_list_cref items, pfc::list_base_const_t const & ids, abort_callback & abort) = 0; +}; + +//! \since 1.1.7 +class NOVTABLE album_art_manager_config : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(album_art_manager_config, service_base) +public: + virtual bool get_external_pattern(pfc::string_base & out, const GUID & type) = 0; + virtual bool use_embedded_pictures() = 0; + virtual bool use_fallbacks() = 0; +}; + +//! \since 1.1.7 +class NOVTABLE album_art_manager_v3 : public album_art_manager_v2 { + FB2K_MAKE_SERVICE_INTERFACE(album_art_manager_v3, album_art_manager_v2) +public: + //! @param config An optional album_art_manager_config object to override global settings. Pass null to use global settings. + virtual album_art_extractor_instance_v2::ptr open_v3(metadb_handle_list_cref items, pfc::list_base_const_t const & ids, album_art_manager_config::ptr config, abort_callback & abort) = 0; +}; diff --git a/SDK/foobar2000/SDK/album_art_helpers.h b/SDK/foobar2000/SDK/album_art_helpers.h new file mode 100644 index 0000000..b85017f --- /dev/null +++ b/SDK/foobar2000/SDK/album_art_helpers.h @@ -0,0 +1,147 @@ +//! Implements album_art_data. +class album_art_data_impl : public album_art_data { +public: + const void * get_ptr() const {return m_content.get_ptr();} + t_size get_size() const {return m_content.get_size();} + + void * get_ptr() {return m_content.get_ptr();} + void set_size(t_size p_size) {m_content.set_size(p_size);} + + //! Reads picture data from the specified stream object. + void from_stream(stream_reader * p_stream,t_size p_bytes,abort_callback & p_abort) { + set_size(p_bytes); p_stream->read_object(get_ptr(),p_bytes,p_abort); + } + + //! Creates an album_art_data object from picture data contained in a memory buffer. + static album_art_data_ptr g_create(const void * p_buffer,t_size p_bytes) { + service_ptr_t instance = new service_impl_t(); + instance->set_size(p_bytes); + memcpy(instance->get_ptr(),p_buffer,p_bytes); + return instance; + } + //! Creates an album_art_data object from picture data contained in a stream. + static album_art_data_ptr g_create(stream_reader * p_stream,t_size p_bytes,abort_callback & p_abort) { + service_ptr_t instance = new service_impl_t(); + instance->from_stream(p_stream,p_bytes,p_abort); + return instance; + } + +private: + pfc::array_t m_content; +}; + + +//! Helper - simple implementation of album_art_extractor_instance. +class album_art_extractor_instance_simple : public album_art_extractor_instance { +public: + void set(const GUID & p_what,album_art_data_ptr p_content) {m_content.set(p_what,p_content);} + bool have_item(const GUID & p_what) {return m_content.have_item(p_what);} + album_art_data_ptr query(const GUID & p_what,abort_callback & p_abort) { + album_art_data_ptr temp; + if (!m_content.query(p_what,temp)) throw exception_album_art_not_found(); + return temp; + } + bool is_empty() const {return m_content.get_count() == 0;} + bool remove(const GUID & p_what) { + return m_content.remove(p_what); + } +private: + pfc::map_t m_content; +}; + +//! Helper implementation of album_art_extractor - reads album art from arbitrary file formats that comply with APEv2 tagging specification. +class album_art_extractor_impl_stdtags : public album_art_extractor { +public: + //! @param exts Semicolon-separated list of file format extensions to support. + album_art_extractor_impl_stdtags(const char * exts) { + pfc::splitStringSimple_toList(m_extensions,';',exts); + } + + bool is_our_path(const char * p_path,const char * p_extension) { + return m_extensions.have_item(p_extension); + } + + album_art_extractor_instance_ptr open(file_ptr p_filehint,const char * p_path,abort_callback & p_abort) { + PFC_ASSERT( is_our_path(p_path, pfc::string_extension(p_path) ) ); + file_ptr l_file ( p_filehint ); + if (l_file.is_empty()) filesystem::g_open_read(l_file, p_path, p_abort); + return static_api_ptr_t()->open( l_file, p_abort ); + } +private: + pfc::avltree_t m_extensions; +}; + +//! Helper implementation of album_art_editor - edits album art from arbitrary file formats that comply with APEv2 tagging specification. +class album_art_editor_impl_stdtags : public album_art_editor { +public: + //! @param exts Semicolon-separated list of file format extensions to support. + album_art_editor_impl_stdtags(const char * exts) { + pfc::splitStringSimple_toList(m_extensions,';',exts); + } + + bool is_our_path(const char * p_path,const char * p_extension) { + return m_extensions.have_item(p_extension); + } + + album_art_editor_instance_ptr open(file_ptr p_filehint,const char * p_path,abort_callback & p_abort) { + PFC_ASSERT( is_our_path(p_path, pfc::string_extension(p_path) ) ); + file_ptr l_file ( p_filehint ); + if (l_file.is_empty()) filesystem::g_open(l_file, p_path, filesystem::open_mode_write_existing, p_abort); + return static_api_ptr_t()->edit( l_file, p_abort ); + } +private: + pfc::avltree_t m_extensions; + +}; + +//! Helper - a more advanced implementation of album_art_extractor_instance. +class album_art_extractor_instance_fileref : public album_art_extractor_instance { +public: + album_art_extractor_instance_fileref(file::ptr f) : m_file(f) {} + + void set(const GUID & p_what,t_filesize p_offset, t_filesize p_size) { + const t_fileref ref = {p_offset, p_size}; + m_data.set(p_what, ref); + m_cache.remove(p_what); + } + + bool have_item(const GUID & p_what) { + return m_data.have_item(p_what); + } + + album_art_data_ptr query(const GUID & p_what,abort_callback & p_abort) { + album_art_data_ptr item; + if (m_cache.query(p_what,item)) return item; + t_fileref ref; + if (!m_data.query(p_what, ref)) throw exception_album_art_not_found(); + m_file->seek(ref.m_offset, p_abort); + item = album_art_data_impl::g_create(m_file.get_ptr(), pfc::downcast_guarded(ref.m_size), p_abort); + m_cache.set(p_what, item); + return item; + } + bool is_empty() const {return m_data.get_count() == 0;} +private: + struct t_fileref { + t_filesize m_offset, m_size; + }; + const file::ptr m_file; + pfc::map_t m_data; + pfc::map_t m_cache; +}; + +//! album_art_path_list implementation helper +class album_art_path_list_impl : public album_art_path_list { +public: + template album_art_path_list_impl(const t_in & in) {pfc::list_to_array(m_data, in);} + const char * get_path(t_size index) const {return m_data[index];} + t_size get_count() const {return m_data.get_size();} +private: + pfc::array_t m_data; +}; + +//! album_art_path_list implementation helper +class album_art_path_list_dummy : public album_art_path_list { +public: + const char * get_path(t_size index) const {uBugCheck();} + t_size get_count() const {return 0;} +}; diff --git a/SDK/foobar2000/SDK/app_close_blocker.cpp b/SDK/foobar2000/SDK/app_close_blocker.cpp new file mode 100644 index 0000000..49dcbc1 --- /dev/null +++ b/SDK/foobar2000/SDK/app_close_blocker.cpp @@ -0,0 +1,12 @@ +#include "foobar2000.h" + +bool app_close_blocker::g_query() +{ + service_ptr_t ptr; + service_enum_t e; + while(e.next(ptr)) + { + if (!ptr->query()) return false; + } + return true; +} \ No newline at end of file diff --git a/SDK/foobar2000/SDK/app_close_blocker.h b/SDK/foobar2000/SDK/app_close_blocker.h new file mode 100644 index 0000000..259109e --- /dev/null +++ b/SDK/foobar2000/SDK/app_close_blocker.h @@ -0,0 +1,65 @@ +//! (DEPRECATED) This service is used to signal whether something is currently preventing main window from being closed and app from being shut down. +class NOVTABLE app_close_blocker : public service_base +{ +public: + //! Checks whether this service is currently preventing main window from being closed and app from being shut down. + virtual bool query() = 0; + + //! Static helper function, checks whether any of registered app_close_blocker services is currently preventing main window from being closed and app from being shut down. + static bool g_query(); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(app_close_blocker); +}; + +//! An interface encapsulating a task preventing the foobar2000 application from being closed. Instances of this class need to be registered using app_close_blocking_task_manager methods. \n +//! Implementation: it's recommended that you derive from app_close_blocking_task_impl class instead of deriving from app_close_blocking_task directly, it manages registration/unregistration behind-the-scenes. +class NOVTABLE app_close_blocking_task { +public: + virtual void query_task_name(pfc::string_base & out) = 0; + +protected: + app_close_blocking_task() {} + ~app_close_blocking_task() {} + + PFC_CLASS_NOT_COPYABLE_EX(app_close_blocking_task); +}; + +//! Entrypoint class for registering app_close_blocking_task instances. Introduced in 0.9.5.1. \n +//! Usage: static_api_ptr_t(). May fail if user runs pre-0.9.5.1. It's recommended that you use app_close_blocking_task_impl class instead of calling app_close_blocking_task_manager directly. +class NOVTABLE app_close_blocking_task_manager : public service_base { +public: + virtual void register_task(app_close_blocking_task * task) = 0; + virtual void unregister_task(app_close_blocking_task * task) = 0; + + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(app_close_blocking_task_manager); +}; + +//! Helper; implements standard functionality required by app_close_blocking_task implementations - registers/unregisters the task on construction/destruction. +class app_close_blocking_task_impl : public app_close_blocking_task { +public: + app_close_blocking_task_impl() { static_api_ptr_t()->register_task(this);} + ~app_close_blocking_task_impl() { static_api_ptr_t()->unregister_task(this);} + + void query_task_name(pfc::string_base & out) { out = ""; } +}; + +class app_close_blocking_task_impl_dynamic : public app_close_blocking_task { +public: + app_close_blocking_task_impl_dynamic() : m_taskActive() {} + ~app_close_blocking_task_impl_dynamic() { toggle_blocking(false); } + + void query_task_name(pfc::string_base & out) { out = ""; } + +protected: + void toggle_blocking(bool state) { + if (state != m_taskActive) { + static_api_ptr_t api; + if (state) api->register_task(this); + else api->unregister_task(this); + m_taskActive = state; + } + } +private: + bool m_taskActive; +}; diff --git a/SDK/foobar2000/SDK/audio_chunk.cpp b/SDK/foobar2000/SDK/audio_chunk.cpp new file mode 100644 index 0000000..6a6db8c --- /dev/null +++ b/SDK/foobar2000/SDK/audio_chunk.cpp @@ -0,0 +1,614 @@ +#include "foobar2000.h" + +void audio_chunk::set_data(const audio_sample * src,t_size samples,unsigned nch,unsigned srate,unsigned channel_config) +{ + t_size size = samples * nch; + set_data_size(size); + if (src) + pfc::memcpy_t(get_data(),src,size); + else + pfc::memset_t(get_data(),(audio_sample)0,size); + set_sample_count(samples); + set_channels(nch,channel_config); + set_srate(srate); +} + +inline bool check_exclusive(unsigned val, unsigned mask) +{ + return (val&mask)!=0 && (val&mask)!=mask; +} + +static void _import8u(uint8_t const * in, audio_sample * out, size_t count) { + for(size_t walk = 0; walk < count; ++walk) { + uint32_t i = *(in++); + i -= 0x80; // to signed + *(out++) = (float) (int32_t) i / (float) 0x80; + } +} + +static void _import8s(uint8_t const * in, audio_sample * out, size_t count) { + for(size_t walk = 0; walk < count; ++walk) { + int32_t i = (int8_t) *(in++); + *(out++) = (float) i / (float) 0x80; + } +} + +static audio_sample _import24s(uint32_t i) { + i ^= 0x800000; // to unsigned + i -= 0x800000; // and back to signed / fill MSBs proper + return (float) (int32_t) i / (float) 0x800000; +} + +static void _import24(const void * in_, audio_sample * out, size_t count) { + const uint8_t * in = (const uint8_t*) in_; +#if 1 + while(count > 0 && !pfc::is_ptr_aligned_t<4>(in)) { + uint32_t i = *(in++); + i |= (uint32_t) *(in++) << 8; + i |= (uint32_t) *(in++) << 16; + *(out++) = _import24s(i); + --count; + } + { + for(size_t loop = count >> 2; loop; --loop) { + uint32_t i1 = * (uint32_t*) in; in += 4; + uint32_t i2 = * (uint32_t*) in; in += 4; + uint32_t i3 = * (uint32_t*) in; in += 4; + *out++ = _import24s( i1 & 0xFFFFFF ); + *out++ = _import24s( (i1 >> 24) | ((i2 & 0xFFFF) << 8) ); + *out++ = _import24s( (i2 >> 16) | ((i3 & 0xFF) << 16) ); + *out++ = _import24s( i3 >> 8 ); + } + count &= 3; + } + for( ; count ; --count) { + uint32_t i = *(in++); + i |= (uint32_t) *(in++) << 8; + i |= (uint32_t) *(in++) << 16; + *(out++) = _import24s(i); + } +#else + if (count > 0) { + int32_t i = *(in++); + i |= (int32_t) *(in++) << 8; + i |= (int32_t) (int8_t) *in << 16; + *out++ = (audio_sample) i / (audio_sample) 0x800000; + --count; + + // Now we have in ptr at offset_of_next - 1 and we can read as int32 then discard the LSBs + for(;count;--count) { + int32_t i = *( int32_t*) in; in += 3; + *out++ = (audio_sample) (i >> 8) / (audio_sample) 0x800000; + } + } +#endif +} + +template static void _import16any(const void * in, audio_sample * out, size_t count) { + uint16_t const * inPtr = (uint16_t const*) in; + const audio_sample factor = 1.0f / (audio_sample) 0x8000; + for(size_t walk = 0; walk < count; ++walk) { + uint16_t v = *inPtr++; + if (byteSwap) v = pfc::byteswap_t(v); + if (!isSigned) v ^= 0x8000; // to signed + *out++ = (audio_sample) (int16_t) v * factor; + } +} + +template static void _import32any(const void * in, audio_sample * out, size_t count) { + uint32_t const * inPtr = (uint32_t const*) in; + const audio_sample factor = 1.0f / (audio_sample) 0x80000000; + for(size_t walk = 0; walk < count; ++walk) { + uint32_t v = *inPtr++; + if (byteSwap) v = pfc::byteswap_t(v); + if (!isSigned) v ^= 0x80000000; // to signed + *out++ = (audio_sample) (int32_t) v * factor; + } +} + +template static void _import24any(const void * in, audio_sample * out, size_t count) { + uint8_t const * inPtr = (uint8_t const*) in; + const audio_sample factor = 1.0f / (audio_sample) 0x800000; + for(size_t walk = 0; walk < count; ++walk) { + uint32_t v; + if (byteSwap) v = (uint32_t) inPtr[2] | ( (uint32_t) inPtr[1] << 8 ) | ( (uint32_t) inPtr[0] << 16 ); + else v = (uint32_t) inPtr[0] | ( (uint32_t) inPtr[1] << 8 ) | ( (uint32_t) inPtr[2] << 16 ); + inPtr += 3; + if (isSigned) v ^= 0x800000; // to unsigned + v -= 0x800000; // then subtract to get proper MSBs + *out++ = (audio_sample) (int32_t) v * factor; + } +} + +void audio_chunk::set_data_fixedpoint_ex(const void * source,t_size size,unsigned srate,unsigned nch,unsigned bps,unsigned flags,unsigned p_channel_config) +{ + PFC_ASSERT( check_exclusive(flags,FLAG_SIGNED|FLAG_UNSIGNED) ); + PFC_ASSERT( check_exclusive(flags,FLAG_LITTLE_ENDIAN|FLAG_BIG_ENDIAN) ); + + bool byteSwap = !!(flags & FLAG_BIG_ENDIAN); + if (pfc::byte_order_is_big_endian) byteSwap = !byteSwap; + + t_size count = size / (bps/8); + set_data_size(count); + audio_sample * buffer = get_data(); + bool isSigned = !!(flags & FLAG_SIGNED); + + switch(bps) + { + case 8: + // byte order irrelevant + if (isSigned) _import8s( (const uint8_t*) source , buffer, count); + else _import8u( (const uint8_t*) source , buffer, count); + break; + case 16: + if (byteSwap) { + if (isSigned) { + _import16any( source, buffer, count ); + } else { + _import16any( source, buffer, count ); + } + } else { + if (isSigned) { + //_import16any( source, buffer, count ); + audio_math::convert_from_int16((const int16_t*)source,count,buffer,1.0); + } else { + _import16any( source, buffer, count); + } + } + break; + case 24: + if (byteSwap) { + if (isSigned) { + _import24any( source, buffer, count ); + } else { + _import24any( source, buffer, count ); + } + } else { + if (isSigned) { + //_import24any( source, buffer, count); + _import24( source, buffer, count); + } else { + _import24any( source, buffer, count); + } + } + break; + case 32: + if (byteSwap) { + if (isSigned) { + _import32any( source, buffer, count ); + } else { + _import32any( source, buffer, count ); + } + } else { + if (isSigned) { + audio_math::convert_from_int32((const int32_t*)source,count,buffer,1.0); + } else { + _import32any( source, buffer, count); + } + } + break; + default: + //unknown size, cant convert + pfc::memset_t(buffer,(audio_sample)0,count); + break; + } + set_sample_count(count/nch); + set_srate(srate); + set_channels(nch,p_channel_config); +} + +void audio_chunk::set_data_fixedpoint_ms(const void * ptr, size_t bytes, unsigned sampleRate, unsigned channels, unsigned bps, unsigned channelConfig) { + //set_data_fixedpoint_ex(ptr,bytes,sampleRate,channels,bps,(bps==8 ? FLAG_UNSIGNED : FLAG_SIGNED) | flags_autoendian(), channelConfig); + PFC_ASSERT( bps != 0 ); + size_t count = bytes / (bps/8); + this->set_data_size( count ); + audio_sample * buffer = this->get_data(); + switch(bps) { + case 8: + _import8u((const uint8_t*)ptr, buffer, count); + break; + case 16: + audio_math::convert_from_int16((const int16_t*) ptr, count, buffer, 1.0); + break; + case 24: + _import24( ptr, buffer, count); + break; + case 32: + audio_math::convert_from_int32((const int32_t*) ptr, count, buffer, 1.0); + break; + default: + PFC_ASSERT(!"Unknown bit depth!"); + memset(buffer, 0, sizeof(audio_sample) * count); + break; + } + set_sample_count(count/channels); + set_srate(sampleRate); + set_channels(channels,channelConfig); +} + +void audio_chunk::set_data_fixedpoint_signed(const void * ptr,t_size bytes,unsigned sampleRate,unsigned channels,unsigned bps,unsigned channelConfig) { + PFC_ASSERT( bps != 0 ); + size_t count = bytes / (bps/8); + this->set_data_size( count ); + audio_sample * buffer = this->get_data(); + switch(bps) { + case 8: + _import8s((const uint8_t*)ptr, buffer, count); + break; + case 16: + audio_math::convert_from_int16((const int16_t*) ptr, count, buffer, 1.0); + break; + case 24: + _import24( ptr, buffer, count); + break; + case 32: + audio_math::convert_from_int32((const int32_t*) ptr, count, buffer, 1.0); + break; + default: + PFC_ASSERT(!"Unknown bit depth!"); + memset(buffer, 0, sizeof(audio_sample) * count); + break; + } + set_sample_count(count/channels); + set_srate(sampleRate); + set_channels(channels,channelConfig); +} + +void audio_chunk::set_data_int16(const int16_t * src,t_size samples,unsigned nch,unsigned srate,unsigned channel_config) { + const size_t count = samples * nch; + this->set_data_size( count ); + audio_sample * buffer = this->get_data(); + audio_math::convert_from_int16(src, count, buffer, 1.0); + set_sample_count(samples); + set_srate(srate); + set_channels(nch,channel_config); +} + +template +static void process_float_multi(audio_sample * p_out,const t_float * p_in,const t_size p_count) +{ + for(size_t n=0;n +static void process_float_multi_swap(audio_sample * p_out,const t_float * p_in,const t_size p_count) +{ + for(size_t n=0;n(ptr),count); + else + process_float_multi(out,reinterpret_cast(ptr),count); + } + else if (bps == 64) + { + if (use_swap) + process_float_multi_swap(out,reinterpret_cast(ptr),count); + else + process_float_multi(out,reinterpret_cast(ptr),count); + } else if (bps == 16) { + const uint16_t * in = reinterpret_cast(ptr); + if (use_swap) { + for(size_t walk = 0; walk < count; ++walk) out[walk] = audio_math::decodeFloat16(pfc::byteswap_t(in[walk])); + } else { + for(size_t walk = 0; walk < count; ++walk) out[walk] = audio_math::decodeFloat16(in[walk]); + } + } else if (bps == 24) { + const uint8_t * in = reinterpret_cast(ptr); + if (use_swap) { + for(size_t walk = 0; walk < count; ++walk) out[walk] = audio_math::decodeFloat24ptrbs(&in[walk*3]); + } else { + for(size_t walk = 0; walk < count; ++walk) out[walk] = audio_math::decodeFloat24ptr(&in[walk*3]); + } + } else pfc::throw_exception_with_message< exception_io_data >("invalid bit depth"); + + set_sample_count(count/nch); + set_srate(srate); + set_channels(nch,p_channel_config); +} + +bool audio_chunk::is_valid() const +{ + unsigned nch = get_channels(); + if (nch==0 || nch>256) return false; + if (!g_is_valid_sample_rate(get_srate())) return false; + t_size samples = get_sample_count(); + if (samples==0 || samples >= 0x80000000 / (sizeof(audio_sample) * nch) ) return false; + t_size size = get_data_size(); + if (samples * nch > size) return false; + if (!get_data()) return false; + return true; +} + +bool audio_chunk::is_spec_valid() const { + return this->get_spec().is_valid(); +} + +void audio_chunk::pad_with_silence_ex(t_size samples,unsigned hint_nch,unsigned hint_srate) { + if (is_empty()) + { + if (hint_srate && hint_nch) { + return set_data(0,samples,hint_nch,hint_srate); + } else throw exception_io_data(); + } + else + { + if (hint_srate && hint_srate != get_srate()) samples = MulDiv_Size(samples,get_srate(),hint_srate); + if (samples > get_sample_count()) + { + t_size old_size = get_sample_count() * get_channels(); + t_size new_size = samples * get_channels(); + set_data_size(new_size); + pfc::memset_t(get_data() + old_size,(audio_sample)0,new_size - old_size); + set_sample_count(samples); + } + } +} + +void audio_chunk::pad_with_silence(t_size samples) { + if (samples > get_sample_count()) + { + t_size old_size = get_sample_count() * get_channels(); + t_size new_size = pfc::multiply_guarded(samples,(size_t)get_channels()); + set_data_size(new_size); + pfc::memset_t(get_data() + old_size,(audio_sample)0,new_size - old_size); + set_sample_count(samples); + } +} + +void audio_chunk::set_silence(t_size samples) { + t_size items = samples * get_channels(); + set_data_size(items); + pfc::memset_null_t(get_data(), items); + set_sample_count(samples); +} + +void audio_chunk::set_silence_seconds( double seconds ) { + set_silence( (size_t) audio_math::time_to_samples( seconds, this->get_sample_rate() ) ); +} + +void audio_chunk::insert_silence_fromstart(t_size samples) { + t_size old_size = get_sample_count() * get_channels(); + t_size delta = samples * get_channels(); + t_size new_size = old_size + delta; + set_data_size(new_size); + audio_sample * ptr = get_data(); + pfc::memmove_t(ptr+delta,ptr,old_size); + pfc::memset_t(ptr,(audio_sample)0,delta); + set_sample_count(get_sample_count() + samples); +} + +bool audio_chunk::process_skip(double & skipDuration) { + t_uint64 skipSamples = audio_math::time_to_samples(skipDuration, get_sample_rate()); + if (skipSamples == 0) {skipDuration = 0; return true;} + const t_size mySamples = get_sample_count(); + if (skipSamples < mySamples) { + skip_first_samples((t_size)skipSamples); + skipDuration = 0; + return true; + } + if (skipSamples == mySamples) { + skipDuration = 0; + return false; + } + skipDuration -= audio_math::samples_to_time(mySamples, get_sample_rate()); + return false; +} + +t_size audio_chunk::skip_first_samples(t_size samples_delta) +{ + t_size samples_old = get_sample_count(); + if (samples_delta >= samples_old) + { + set_sample_count(0); + set_data_size(0); + return samples_old; + } + else + { + t_size samples_new = samples_old - samples_delta; + unsigned nch = get_channels(); + audio_sample * ptr = get_data(); + pfc::memmove_t(ptr,ptr+nch*samples_delta,nch*samples_new); + set_sample_count(samples_new); + set_data_size(nch*samples_new); + return samples_delta; + } +} + +audio_sample audio_chunk::get_peak(audio_sample p_peak) const { + return pfc::max_t(p_peak, get_peak()); +} + +audio_sample audio_chunk::get_peak() const { + return audio_math::calculate_peak(get_data(),get_sample_count() * get_channels()); +} + +void audio_chunk::scale(audio_sample p_value) +{ + audio_sample * ptr = get_data(); + audio_math::scale(ptr,get_sample_count() * get_channels(),ptr,p_value); +} + + +namespace { + +struct sampleToIntDesc { + unsigned bps, bpsValid; + bool useUpperBits; + float scale; +}; +template class sampleToInt { +public: + sampleToInt(sampleToIntDesc const & d) { + clipLo = - ( (int_t) 1 << (d.bpsValid-1)); + clipHi = ( (int_t) 1 << (d.bpsValid-1)) - 1; + scale = (float) ( (int64_t) 1 << (d.bpsValid - 1) ) * d.scale; + if (d.useUpperBits) { + shift = d.bps - d.bpsValid; + } else { + shift = 0; + } + } + inline int_t operator() (audio_sample s) const { + int_t v; + if (sizeof(int_t) > 4) v = (int_t) audio_math::rint64( s * scale ); + else v = (int_t)audio_math::rint32( s * scale ); + return pfc::clip_t( v, clipLo, clipHi) << shift; + } +private: + int_t clipLo, clipHi; + int8_t shift; + float scale; +}; +} +static void render_24bit(const audio_sample * in, t_size inLen, void * out, sampleToIntDesc const & d) { + t_uint8 * outWalk = reinterpret_cast(out); + sampleToInt gen(d); + for(t_size walk = 0; walk < inLen; ++walk) { + int32_t v = gen(in[walk]); + *(outWalk ++) = (t_uint8) (v & 0xFF); + *(outWalk ++) = (t_uint8) ((v >> 8) & 0xFF); + *(outWalk ++) = (t_uint8) ((v >> 16) & 0xFF); + } +} +static void render_8bit(const audio_sample * in, t_size inLen, void * out, sampleToIntDesc const & d) { + sampleToInt gen(d); + t_int8 * outWalk = reinterpret_cast(out); + for(t_size walk = 0; walk < inLen; ++walk) { + *outWalk++ = (t_int8)gen(in[walk]); + } +} +static void render_16bit(const audio_sample * in, t_size inLen, void * out, sampleToIntDesc const & d) { + sampleToInt gen(d); + int16_t * outWalk = reinterpret_cast(out); + for(t_size walk = 0; walk < inLen; ++walk) { + *outWalk++ = (int16_t)gen(in[walk]); + } +} + +template +static void render_32bit_(const audio_sample * in, t_size inLen, void * out, sampleToIntDesc const & d) { + sampleToInt gen(d); // must use int64 for clipping + int32_t * outWalk = reinterpret_cast(out); + for(t_size walk = 0; walk < inLen; ++walk) { + *outWalk++ = (int32_t)gen(in[walk]); + } +} + +bool audio_chunk::g_toFixedPoint(const audio_sample * in, void * out, size_t count, uint32_t bps, uint32_t bpsValid, bool useUpperBits, float scale) { + const sampleToIntDesc d = {bps, bpsValid, useUpperBits, scale}; + if (bps == 0) { + PFC_ASSERT(!"How did we get here?"); + return false; + } else if (bps <= 8) { + render_8bit(in, count, out, d); + } else if (bps <= 16) { + render_16bit(in, count, out, d); + } else if (bps <= 24) { + render_24bit(in, count, out, d); + } else if (bps <= 32) { + if (bpsValid <= 28) { // for speed + render_32bit_(in, count, out, d); + } else { + render_32bit_(in, count, out, d); + } + } else { + PFC_ASSERT(!"How did we get here?"); + return false; + } + + return true; +} + +bool audio_chunk::toFixedPoint(class mem_block_container & out, uint32_t bps, uint32_t bpsValid, bool useUpperBits, float scale) const { + bps = (bps + 7) & ~7; + if (bps < bpsValid) return false; + const size_t count = get_sample_count() * get_channel_count(); + out.set_size( count * (bps/8) ); + return g_toFixedPoint(get_data(), out.get_ptr(), count, bps, bpsValid, useUpperBits, scale); +} + +bool audio_chunk::to_raw_data(mem_block_container & out, t_uint32 bps, bool useUpperBits, float scale) const { + uint32_t bpsValid = bps; + bps = (bps + 7) & ~7; + const size_t count = get_sample_count() * get_channel_count(); + out.set_size( count * (bps/8) ); + void * outPtr = out.get_ptr(); + audio_sample const * inPtr = get_data(); + if (bps == 32) { + float * f = (float*) outPtr; + for(size_t w = 0; w < count; ++w) f[w] = inPtr[w] * scale; + return true; + } else { + return g_toFixedPoint(inPtr, outPtr, count, bps, bpsValid, useUpperBits, scale); + } +} + +audio_chunk::spec_t audio_chunk::makeSpec(uint32_t rate, uint32_t channels) { + return makeSpec( rate, channels, g_guess_channel_config(channels) ); +} + +audio_chunk::spec_t audio_chunk::makeSpec(uint32_t rate, uint32_t channels, uint32_t mask) { + spec_t spec = {}; + spec.sampleRate = rate; spec.chanCount = channels; spec.chanMask = mask; + return spec; +} + +bool audio_chunk::spec_t::equals( const spec_t & v1, const spec_t & v2 ) { + return v1.sampleRate == v2.sampleRate && v1.chanCount == v2.chanCount && v1.chanMask == v2.chanMask; +} + +audio_chunk::spec_t audio_chunk::get_spec() const { + spec_t spec = {}; + spec.sampleRate = this->get_sample_rate(); + spec.chanCount = this->get_channel_count(); + spec.chanMask = this->get_channel_config(); + return spec; +} +void audio_chunk::set_spec(const spec_t & spec) { + set_sample_rate(spec.sampleRate); + set_channels( spec.chanCount, spec.chanMask ); +} + +bool audio_chunk::spec_t::is_valid() const { + if (this->chanCount==0 || this->chanCount>256) return false; + if (!audio_chunk::g_is_valid_sample_rate(this->sampleRate)) return false; + return true; +} + +double duration_counter::query() const { + double acc = m_offset; + for(t_map::const_iterator walk = m_sampleCounts.first(); walk.is_valid(); ++walk) { + acc += audio_math::samples_to_time(walk->m_value, walk->m_key); + } + return acc; +} + +uint64_t duration_counter::queryAsSampleCount( uint32_t rate ) { + uint64_t samples = 0; + double acc = m_offset; + for(t_map::const_iterator walk = m_sampleCounts.first(); walk.is_valid(); ++walk) { + if (walk->m_key == rate) samples += walk->m_value; + else acc += audio_math::samples_to_time(walk->m_value, walk->m_key); + } + return samples + audio_math::time_to_samples(acc, rate ); +} diff --git a/SDK/foobar2000/SDK/audio_chunk.h b/SDK/foobar2000/SDK/audio_chunk.h new file mode 100644 index 0000000..35763cf --- /dev/null +++ b/SDK/foobar2000/SDK/audio_chunk.h @@ -0,0 +1,381 @@ +//! Thrown when audio_chunk sample rate or channel mapping changes in mid-stream and the code receiving audio_chunks can't deal with that scenario. +PFC_DECLARE_EXCEPTION(exception_unexpected_audio_format_change, exception_io_data, "Unexpected audio format change" ); + +//! Interface to container of a chunk of audio data. See audio_chunk_impl for an implementation. +class NOVTABLE audio_chunk { +public: + + enum { + sample_rate_min = 1000, sample_rate_max = 2822400 + }; + static bool g_is_valid_sample_rate(t_uint32 p_val) {return p_val >= sample_rate_min && p_val <= sample_rate_max;} + + //! Channel map flag declarations. Note that order of interleaved channel data in the stream is same as order of these flags. + enum + { + channel_front_left = 1<<0, + channel_front_right = 1<<1, + channel_front_center = 1<<2, + channel_lfe = 1<<3, + channel_back_left = 1<<4, + channel_back_right = 1<<5, + channel_front_center_left = 1<<6, + channel_front_center_right = 1<<7, + channel_back_center = 1<<8, + channel_side_left = 1<<9, + channel_side_right = 1<<10, + channel_top_center = 1<<11, + channel_top_front_left = 1<<12, + channel_top_front_center = 1<<13, + channel_top_front_right = 1<<14, + channel_top_back_left = 1<<15, + channel_top_back_center = 1<<16, + channel_top_back_right = 1<<17, + + channel_config_mono = channel_front_center, + channel_config_stereo = channel_front_left | channel_front_right, + channel_config_5point1 = channel_front_left | channel_front_right | channel_front_center | channel_lfe | channel_back_left | channel_back_right, + channel_config_5point1_side = channel_front_left | channel_front_right | channel_front_center | channel_lfe | channel_side_left | channel_side_right, + channel_config_7point1 = channel_config_5point1 | channel_side_left | channel_side_right, + + defined_channel_count = 18, + }; + + //! Helper function; guesses default channel map for the specified channel count. Returns 0 on failure. + static unsigned g_guess_channel_config(unsigned count); + //! Helper function; determines channel map for the specified channel count according to Xiph specs. Throws exception_io_data on failure. + static unsigned g_guess_channel_config_xiph(unsigned count); + + //! Helper function; translates audio_chunk channel map to WAVEFORMATEXTENSIBLE channel map. + static uint32_t g_channel_config_to_wfx(unsigned p_config); + //! Helper function; translates WAVEFORMATEXTENSIBLE channel map to audio_chunk channel map. + static unsigned g_channel_config_from_wfx(uint32_t p_wfx); + + //! Extracts flag describing Nth channel from specified map. Usable to figure what specific channel in a stream means. + static unsigned g_extract_channel_flag(unsigned p_config,unsigned p_index); + //! Counts channels specified by channel map. + static unsigned g_count_channels(unsigned p_config); + //! Calculates index of a channel specified by p_flag in a stream where channel map is described by p_config. + static unsigned g_channel_index_from_flag(unsigned p_config,unsigned p_flag); + + static const char * g_channel_name(unsigned p_flag); + static const char * g_channel_name_byidx(unsigned p_index); + static unsigned g_find_channel_idx(unsigned p_flag); + static void g_formatChannelMaskDesc(unsigned flags, pfc::string_base & out); + + + + //! Retrieves audio data buffer pointer (non-const version). Returned pointer is for temporary use only; it is valid until next set_data_size call, or until the object is destroyed. \n + //! Size of returned buffer is equal to get_data_size() return value (in audio_samples). Amount of actual data may be smaller, depending on sample count and channel count. Conditions where sample count * channel count are greater than data size should not be possible. + virtual audio_sample * get_data() = 0; + //! Retrieves audio data buffer pointer (const version). Returned pointer is for temporary use only; it is valid until next set_data_size call, or until the object is destroyed. \n + //! Size of returned buffer is equal to get_data_size() return value (in audio_samples). Amount of actual data may be smaller, depending on sample count and channel count. Conditions where sample count * channel count are greater than data size should not be possible. + virtual const audio_sample * get_data() const = 0; + //! Retrieves size of allocated buffer space, in audio_samples. + virtual t_size get_data_size() const = 0; + //! Resizes audio data buffer to specified size. Throws std::bad_alloc on failure. + virtual void set_data_size(t_size p_new_size) = 0; + //! Sanity helper, same as set_data_size. + void allocate(size_t size) { set_data_size( size ); } + + //! Retrieves sample rate of contained audio data. + virtual unsigned get_srate() const = 0; + //! Sets sample rate of contained audio data. + virtual void set_srate(unsigned val) = 0; + //! Retrieves channel count of contained audio data. + virtual unsigned get_channels() const = 0; + //! Helper - for consistency - same as get_channels(). + inline unsigned get_channel_count() const {return get_channels();} + //! Retrieves channel map of contained audio data. Conditions where number of channels specified by channel map don't match get_channels() return value should not be possible. + virtual unsigned get_channel_config() const = 0; + //! Sets channel count / channel map. + virtual void set_channels(unsigned p_count,unsigned p_config) = 0; + + //! Retrieves number of valid samples in the buffer. \n + //! Note that a "sample" means a unit of interleaved PCM data representing states of each channel at given point of time, not a single PCM value. \n + //! For an example, duration of contained audio data is equal to sample count / sample rate, while actual size of contained data is equal to sample count * channel count. + virtual t_size get_sample_count() const = 0; + + //! Sets number of valid samples in the buffer. WARNING: sample count * channel count should never be above allocated buffer size. + virtual void set_sample_count(t_size val) = 0; + + //! Helper, same as get_srate(). + inline unsigned get_sample_rate() const {return get_srate();} + //! Helper, same as set_srate(). + inline void set_sample_rate(unsigned val) {set_srate(val);} + + //! Helper; sets channel count to specified value and uses default channel map for this channel count. + void set_channels(unsigned val) {set_channels(val,g_guess_channel_config(val));} + + + //! Helper; resizes audio data buffer when its current size is smaller than requested. + inline void grow_data_size(t_size p_requested) {if (p_requested > get_data_size()) set_data_size(p_requested);} + + + //! Retrieves duration of contained audio data, in seconds. + inline double get_duration() const + { + double rv = 0; + t_size srate = get_srate (), samples = get_sample_count(); + if (srate>0 && samples>0) rv = (double)samples/(double)srate; + return rv; + } + + //! Returns whether the chunk is empty (contains no audio data). + inline bool is_empty() const {return get_channels()==0 || get_srate()==0 || get_sample_count()==0;} + + //! Returns whether the chunk contents are valid (for bug check purposes). + bool is_valid() const; + + //! Returns whether the chunk contains valid sample rate & channel info (but allows an empty chunk). + bool is_spec_valid() const; + + //! Returns actual amount of audio data contained in the buffer (sample count * channel count). Must not be greater than data size (see get_data_size()). + size_t get_used_size() const {return get_sample_count() * get_channels();} + //! Same as get_used_size(); old confusingly named version. + size_t get_data_length() const {return get_sample_count() * get_channels();} +#pragma deprecated( get_data_length ) + + //! Resets all audio_chunk data. + inline void reset() { + set_sample_count(0); + set_srate(0); + set_channels(0); + set_data_size(0); + } + + //! Helper, sets chunk data to contents of specified buffer, with specified number of channels / sample rate / channel map. + void set_data(const audio_sample * src,t_size samples,unsigned nch,unsigned srate,unsigned channel_config); + + //! Helper, sets chunk data to contents of specified buffer, with specified number of channels / sample rate, using default channel map for specified channel count. + inline void set_data(const audio_sample * src,t_size samples,unsigned nch,unsigned srate) {set_data(src,samples,nch,srate,g_guess_channel_config(nch));} + + void set_data_int16(const int16_t * src,t_size samples,unsigned nch,unsigned srate,unsigned channel_config); + + //! Helper, sets chunk data to contents of specified buffer, using default win32/wav conventions for signed/unsigned switch. + inline void set_data_fixedpoint(const void * ptr,t_size bytes,unsigned srate,unsigned nch,unsigned bps,unsigned channel_config) { + this->set_data_fixedpoint_ms(ptr, bytes, srate, nch, bps, channel_config); + } + + void set_data_fixedpoint_signed(const void * ptr,t_size bytes,unsigned srate,unsigned nch,unsigned bps,unsigned channel_config); + + enum + { + FLAG_LITTLE_ENDIAN = 1, + FLAG_BIG_ENDIAN = 2, + FLAG_SIGNED = 4, + FLAG_UNSIGNED = 8, + }; + + inline static unsigned flags_autoendian() { + return pfc::byte_order_is_big_endian ? FLAG_BIG_ENDIAN : FLAG_LITTLE_ENDIAN; + } + + void set_data_fixedpoint_ex(const void * ptr,t_size bytes,unsigned p_sample_rate,unsigned p_channels,unsigned p_bits_per_sample,unsigned p_flags,unsigned p_channel_config);//p_flags - see FLAG_* above + + void set_data_fixedpoint_ms(const void * ptr, size_t bytes, unsigned sampleRate, unsigned channels, unsigned bps, unsigned channelConfig); + + void set_data_floatingpoint_ex(const void * ptr,t_size bytes,unsigned p_sample_rate,unsigned p_channels,unsigned p_bits_per_sample,unsigned p_flags,unsigned p_channel_config);//signed/unsigned flags dont apply + + inline void set_data_32(const float * src,t_size samples,unsigned nch,unsigned srate) {return set_data((const audio_sample*)src,samples,nch,srate);} + + void pad_with_silence_ex(t_size samples,unsigned hint_nch,unsigned hint_srate); + void pad_with_silence(t_size samples); + void insert_silence_fromstart(t_size samples); + t_size skip_first_samples(t_size samples); + void set_silence(t_size samples); + void set_silence_seconds( double seconds ); + + bool process_skip(double & skipDuration); + + //! Simple function to get original PCM stream back. Assumes host's endianness, integers are signed - including the 8bit mode; 32bit mode assumed to be float. + //! @returns false when the conversion could not be performed because of unsupported bit depth etc. + bool to_raw_data(class mem_block_container & out, t_uint32 bps, bool useUpperBits = true, float scale = 1.0) const; + + //! Convert audio_chunk contents to fixed-point PCM format. + //! @param useUpperBits relevant if bps != bpsValid, signals whether upper or lower bits of each sample should be used. + bool toFixedPoint(class mem_block_container & out, uint32_t bps, uint32_t bpsValid, bool useUpperBits = true, float scale = 1.0) const; + + //! Convert a buffer of audio_samples to fixed-point PCM format. + //! @param useUpperBits relevant if bps != bpsValid, signals whether upper or lower bits of each sample should be used. + static bool g_toFixedPoint(const audio_sample * in, void * out, size_t count, uint32_t bps, uint32_t bpsValid, bool useUpperBits = true, float scale = 1.0); + + + //! Helper, calculates peak value of data in the chunk. The optional parameter specifies initial peak value, to simplify calling code. + audio_sample get_peak(audio_sample p_peak) const; + audio_sample get_peak() const; + + //! Helper function; scales entire chunk content by specified value. + void scale(audio_sample p_value); + + //! Helper; copies content of another audio chunk to this chunk. + void copy(const audio_chunk & p_source) { + set_data(p_source.get_data(),p_source.get_sample_count(),p_source.get_channels(),p_source.get_srate(),p_source.get_channel_config()); + } + + const audio_chunk & operator=(const audio_chunk & p_source) { + copy(p_source); + return *this; + } + + struct spec_t { + uint32_t sampleRate; + uint32_t chanCount, chanMask; + + static bool equals( const spec_t & v1, const spec_t & v2 ); + bool operator==(const spec_t & other) const { return equals(*this, other);} + bool operator!=(const spec_t & other) const { return !equals(*this, other);} + bool is_valid() const; + }; + static spec_t makeSpec(uint32_t rate, uint32_t channels); + static spec_t makeSpec(uint32_t rate, uint32_t channels, uint32_t chanMask); + + spec_t get_spec() const; + void set_spec(const spec_t &); +protected: + audio_chunk() {} + ~audio_chunk() {} +}; + +//! Implementation of audio_chunk. Takes pfc allocator template as template parameter. +template > +class audio_chunk_impl_t : public audio_chunk { + typedef audio_chunk_impl_t t_self; + container_t m_data; + unsigned m_srate,m_nch,m_setup; + t_size m_samples; +public: + audio_chunk_impl_t() : m_srate(0), m_nch(0), m_samples(0), m_setup(0) {} + audio_chunk_impl_t(const audio_sample * src,unsigned samples,unsigned nch,unsigned srate) : m_srate(0), m_nch(0), m_samples(0) + {set_data(src,samples,nch,srate);} + audio_chunk_impl_t(const audio_chunk & p_source) : m_srate(0), m_nch(0), m_samples(0), m_setup(0) {copy(p_source);} + audio_chunk_impl_t(const t_self & p_source) : m_srate(0), m_nch(0), m_samples(0), m_setup(0) {copy(p_source);} + + virtual audio_sample * get_data() {return m_data.get_ptr();} + virtual const audio_sample * get_data() const {return m_data.get_ptr();} + virtual t_size get_data_size() const {return m_data.get_size();} + virtual void set_data_size(t_size new_size) {m_data.set_size(new_size);} + + virtual unsigned get_srate() const {return m_srate;} + virtual void set_srate(unsigned val) {m_srate=val;} + virtual unsigned get_channels() const {return m_nch;} + virtual unsigned get_channel_config() const {return m_setup;} + virtual void set_channels(unsigned val,unsigned setup) {m_nch = val;m_setup = setup;} + void set_channels(unsigned val) {set_channels(val,g_guess_channel_config(val));} + + virtual t_size get_sample_count() const {return m_samples;} + virtual void set_sample_count(t_size val) {m_samples = val;} + + const t_self & operator=(const audio_chunk & p_source) {copy(p_source);return *this;} + const t_self & operator=(const t_self & p_source) {copy(p_source);return *this;} +}; + +typedef audio_chunk_impl_t<> audio_chunk_impl; +typedef audio_chunk_impl_t > audio_chunk_fast_impl; + +//! Implements const methods of audio_chunk only, referring to an external buffer. For temporary use only (does not maintain own storage), e.g.: somefunc( audio_chunk_temp_impl(mybuffer,....) ); +class audio_chunk_memref_impl : public audio_chunk { +public: + audio_chunk_memref_impl(const audio_sample * p_data,t_size p_samples,t_uint32 p_sample_rate,t_uint32 p_channels,t_uint32 p_channel_config) : + m_data(p_data), m_samples(p_samples), m_sample_rate(p_sample_rate), m_channels(p_channels), m_channel_config(p_channel_config) + { + PFC_ASSERT(is_valid()); + } + + audio_sample * get_data() {throw pfc::exception_not_implemented();} + const audio_sample * get_data() const {return m_data;} + t_size get_data_size() const {return m_samples * m_channels;} + void set_data_size(t_size p_new_size) {throw pfc::exception_not_implemented();} + + unsigned get_srate() const {return m_sample_rate;} + void set_srate(unsigned val) {throw pfc::exception_not_implemented();} + unsigned get_channels() const {return m_channels;} + unsigned get_channel_config() const {return m_channel_config;} + void set_channels(unsigned p_count,unsigned p_config) {throw pfc::exception_not_implemented();} + + t_size get_sample_count() const {return m_samples;} + + void set_sample_count(t_size val) {throw pfc::exception_not_implemented();} + +private: + t_size m_samples; + t_uint32 m_sample_rate,m_channels,m_channel_config; + const audio_sample * m_data; +}; + + +// Compatibility typedefs. +typedef audio_chunk_fast_impl audio_chunk_impl_temporary; +typedef audio_chunk_impl audio_chunk_i; +typedef audio_chunk_memref_impl audio_chunk_temp_impl; + +//! Duration counter class - accumulates duration using sample values, without any kind of rounding error accumulation. +class duration_counter { +public: + duration_counter() : m_offset() { + } + void set(double v) { + m_sampleCounts.remove_all(); + m_offset = v; + } + void reset() { + set(0); + } + + void add(double v) {m_offset += v;} + void subtract(double v) {m_offset -= v;} + + double query() const; + uint64_t queryAsSampleCount( uint32_t rate ); + + void add(const audio_chunk & c) { + add(c.get_sample_count(), c.get_sample_rate()); + } + void add(t_uint64 sampleCount, t_uint32 sampleRate) { + PFC_ASSERT( sampleRate > 0 ); + if (sampleRate > 0 && sampleCount > 0) { + m_sampleCounts.find_or_add(sampleRate) += sampleCount; + } + } + void add(const duration_counter & other) { + add(other.m_offset); + for(t_map::const_iterator walk = other.m_sampleCounts.first(); walk.is_valid(); ++walk) { + add(walk->m_value, walk->m_key); + } + } + void subtract(const duration_counter & other) { + subtract(other.m_offset); + for(t_map::const_iterator walk = other.m_sampleCounts.first(); walk.is_valid(); ++walk) { + subtract(walk->m_value, walk->m_key); + } + } + void subtract(t_uint64 sampleCount, t_uint32 sampleRate) { + PFC_ASSERT( sampleRate > 0 ); + if (sampleRate > 0 && sampleCount > 0) { + t_uint64 * val = m_sampleCounts.query_ptr(sampleRate); + if (val == NULL) throw pfc::exception_invalid_params(); + if (*val < sampleCount) throw pfc::exception_invalid_params(); + else if (*val == sampleCount) { + m_sampleCounts.remove(sampleRate); + } else { + *val -= sampleCount; + } + + } + } + void subtract(const audio_chunk & c) { + subtract(c.get_sample_count(), c.get_sample_rate()); + } + template duration_counter & operator+=(const t_source & source) {add(source); return *this;} + template duration_counter & operator-=(const t_source & source) {subtract(source); return *this;} + template duration_counter & operator=(const t_source & source) {reset(); add(source); return *this;} +private: + double m_offset; + typedef pfc::map_t t_map; + t_map m_sampleCounts; +}; + +class audio_chunk_partial_ref : public audio_chunk_temp_impl { +public: + audio_chunk_partial_ref(const audio_chunk & chunk, t_size base, t_size count) : audio_chunk_temp_impl(chunk.get_data() + base * chunk.get_channels(), count, chunk.get_sample_rate(), chunk.get_channels(), chunk.get_channel_config()) {} +}; diff --git a/SDK/foobar2000/SDK/audio_chunk_channel_config.cpp b/SDK/foobar2000/SDK/audio_chunk_channel_config.cpp new file mode 100644 index 0000000..5693fbc --- /dev/null +++ b/SDK/foobar2000/SDK/audio_chunk_channel_config.cpp @@ -0,0 +1,212 @@ +#include "foobar2000.h" + +#ifdef _WIN32 +#include +#include + +#if 0 +#define SPEAKER_FRONT_LEFT 0x1 +#define SPEAKER_FRONT_RIGHT 0x2 +#define SPEAKER_FRONT_CENTER 0x4 +#define SPEAKER_LOW_FREQUENCY 0x8 +#define SPEAKER_BACK_LEFT 0x10 +#define SPEAKER_BACK_RIGHT 0x20 +#define SPEAKER_FRONT_LEFT_OF_CENTER 0x40 +#define SPEAKER_FRONT_RIGHT_OF_CENTER 0x80 +#define SPEAKER_BACK_CENTER 0x100 +#define SPEAKER_SIDE_LEFT 0x200 +#define SPEAKER_SIDE_RIGHT 0x400 +#define SPEAKER_TOP_CENTER 0x800 +#define SPEAKER_TOP_FRONT_LEFT 0x1000 +#define SPEAKER_TOP_FRONT_CENTER 0x2000 +#define SPEAKER_TOP_FRONT_RIGHT 0x4000 +#define SPEAKER_TOP_BACK_LEFT 0x8000 +#define SPEAKER_TOP_BACK_CENTER 0x10000 +#define SPEAKER_TOP_BACK_RIGHT 0x20000 + +static struct {DWORD m_wfx; unsigned m_native; } const g_translation_table[] = +{ + {SPEAKER_FRONT_LEFT, audio_chunk::channel_front_left}, + {SPEAKER_FRONT_RIGHT, audio_chunk::channel_front_right}, + {SPEAKER_FRONT_CENTER, audio_chunk::channel_front_center}, + {SPEAKER_LOW_FREQUENCY, audio_chunk::channel_lfe}, + {SPEAKER_BACK_LEFT, audio_chunk::channel_back_left}, + {SPEAKER_BACK_RIGHT, audio_chunk::channel_back_right}, + {SPEAKER_FRONT_LEFT_OF_CENTER, audio_chunk::channel_front_center_left}, + {SPEAKER_FRONT_RIGHT_OF_CENTER, audio_chunk::channel_front_center_right}, + {SPEAKER_BACK_CENTER, audio_chunk::channel_back_center}, + {SPEAKER_SIDE_LEFT, audio_chunk::channel_side_left}, + {SPEAKER_SIDE_RIGHT, audio_chunk::channel_side_right}, + {SPEAKER_TOP_CENTER, audio_chunk::channel_top_center}, + {SPEAKER_TOP_FRONT_LEFT, audio_chunk::channel_top_front_left}, + {SPEAKER_TOP_FRONT_CENTER, audio_chunk::channel_top_front_center}, + {SPEAKER_TOP_FRONT_RIGHT, audio_chunk::channel_top_front_right}, + {SPEAKER_TOP_BACK_LEFT, audio_chunk::channel_top_back_left}, + {SPEAKER_TOP_BACK_CENTER, audio_chunk::channel_top_back_center}, + {SPEAKER_TOP_BACK_RIGHT, audio_chunk::channel_top_back_right}, +}; + +#endif +#endif + +// foobar2000 channel flags are 1:1 identical to Windows WFX ones. +uint32_t audio_chunk::g_channel_config_to_wfx(unsigned p_config) +{ + return p_config; +#if 0 + DWORD ret = 0; + unsigned n; + for(n=0;n= PFC_TABSIZE(g_audio_channel_config_table)) return 0; + return g_audio_channel_config_table[count]; +} + +unsigned audio_chunk::g_guess_channel_config_xiph(unsigned count) { + if (count == 0 || count >= PFC_TABSIZE(g_audio_channel_config_table_xiph)) throw exception_io_data(); + return g_audio_channel_config_table_xiph[count]; +} + +unsigned audio_chunk::g_channel_index_from_flag(unsigned p_config,unsigned p_flag) { + unsigned index = 0; + for(unsigned walk = 0; walk < 32; walk++) { + unsigned query = 1 << walk; + if (p_flag & query) return index; + if (p_config & query) index++; + } + return ~0; +} + +unsigned audio_chunk::g_extract_channel_flag(unsigned p_config,unsigned p_index) +{ + unsigned toskip = p_index; + unsigned flag = 1; + while(flag) + { + if (p_config & flag) + { + if (toskip == 0) break; + toskip--; + } + flag <<= 1; + } + return flag; +} + +unsigned audio_chunk::g_count_channels(unsigned p_config) +{ + return pfc::countBits32(p_config); +} + +static const char * const chanNames[] = { + "FL", //channel_front_left = 1<<0, + "FR", //channel_front_right = 1<<1, + "FC", //channel_front_center = 1<<2, + "LFE", //channel_lfe = 1<<3, + "BL", //channel_back_left = 1<<4, + "BR", //channel_back_right = 1<<5, + "FCL", //channel_front_center_left = 1<<6, + "FCR", //channel_front_center_right = 1<<7, + "BC", //channel_back_center = 1<<8, + "SL", //channel_side_left = 1<<9, + "SR", //channel_side_right = 1<<10, + "TC", //channel_top_center = 1<<11, + "TFL", //channel_top_front_left = 1<<12, + "TFC", //channel_top_front_center = 1<<13, + "TFR", //channel_top_front_right = 1<<14, + "TBL", //channel_top_back_left = 1<<15, + "TBC", //channel_top_back_center = 1<<16, + "TBR", //channel_top_back_right = 1<<17, +}; + +unsigned audio_chunk::g_find_channel_idx(unsigned p_flag) { + unsigned rv = 0; + if ((p_flag & 0xFFFF) == 0) { + rv += 16; p_flag >>= 16; + } + if ((p_flag & 0xFF) == 0) { + rv += 8; p_flag >>= 8; + } + if ((p_flag & 0xF) == 0) { + rv += 4; p_flag >>= 4; + } + if ((p_flag & 0x3) == 0) { + rv += 2; p_flag >>= 2; + } + if ((p_flag & 0x1) == 0) { + rv += 1; p_flag >>= 1; + } + PFC_ASSERT( p_flag & 1 ); + return rv; +} + +const char * audio_chunk::g_channel_name(unsigned p_flag) { + return g_channel_name_byidx(g_find_channel_idx(p_flag)); +} + +const char * audio_chunk::g_channel_name_byidx(unsigned p_index) { + if (p_index < PFC_TABSIZE(chanNames)) return chanNames[p_index]; + else return "?"; +} + +void audio_chunk::g_formatChannelMaskDesc(unsigned flags, pfc::string_base & out) { + out.reset(); + unsigned idx = 0; + while(flags) { + if (flags & 1) { + if (!out.is_empty()) out << " "; + out << g_channel_name_byidx(idx); + } + flags >>= 1; + ++idx; + } +} \ No newline at end of file diff --git a/SDK/foobar2000/SDK/audio_postprocessor.h b/SDK/foobar2000/SDK/audio_postprocessor.h new file mode 100644 index 0000000..7e13643 --- /dev/null +++ b/SDK/foobar2000/SDK/audio_postprocessor.h @@ -0,0 +1,25 @@ +//! This class handles conversion of audio data (audio_chunk) to various linear PCM types, with optional dithering. + +class NOVTABLE audio_postprocessor : public service_base +{ +public: + //! Processes one chunk of audio data. + //! @param p_chunk Chunk of audio data to process. + //! @param p_output Receives output linear signed PCM data. + //! @param p_out_bps Desired bit depth of output. + //! @param p_out_bps_physical Desired physical word width of output. Must be either 8, 16, 24 or 32, greater or equal to p_out_bps. This is typically set to same value as p_out_bps. + //! @param p_dither Indicates whether dithering should be used. Note that dithering is CPU-heavy. + //! @param p_prescale Value to scale all audio samples by when converting. Set to 1.0 to do nothing. + + virtual void run(const audio_chunk & p_chunk, + mem_block_container & p_output, + t_uint32 p_out_bps, + t_uint32 p_out_bps_physical, + bool p_dither, + audio_sample p_prescale + ) = 0; + + + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(audio_postprocessor); +}; diff --git a/SDK/foobar2000/SDK/autoplaylist.h b/SDK/foobar2000/SDK/autoplaylist.h new file mode 100644 index 0000000..6f11cbf --- /dev/null +++ b/SDK/foobar2000/SDK/autoplaylist.h @@ -0,0 +1,102 @@ +/* + Autoplaylist APIs + These APIs were introduced in foobar2000 0.9.5, to reduce amount of code required to create your own autoplaylists. Creation of autoplaylists is was also possible before through playlist lock APIs. + In most cases, you'll want to turn regular playlists into autoplaylists using the following code: + static_api_ptr_t()->add_client_simple(querypattern, sortpattern, playlistindex, forceSort ? autoplaylist_flag_sort : 0); + If you require more advanced functionality, such as using your own code to filter which part of user's Media Library should be placed in specific autoplaylist, you must implement autoplaylist_client (to let autoplaylist manager invoke your handlers when needed) / autoplaylist_client_factory (to re-instantiate your autoplaylist_client after a foobar2000 restart cycle). +*/ + +enum { + //! When set, core will keep the autoplaylist sorted and prevent user from reordering it. + autoplaylist_flag_sort = 1 << 0, +}; +//! Main class controlling autoplaylist behaviors. Implemented by autoplaylist client in scenarios where simple query/sort strings are not enough (core provides a standard implementation for simple queries). +class NOVTABLE autoplaylist_client : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(autoplaylist_client,service_base) +public: + virtual GUID get_guid() = 0; + //! Provides a boolean mask of which items from the specified list should appear in this autoplaylist. + virtual void filter(metadb_handle_list_cref data, bool * out) = 0; + //! Return true when you have filled p_orderbuffer with a permutation to apply to p_items, false when you don't support sorting (core's own sort scheme will be applied). + virtual bool sort(metadb_handle_list_cref p_items,t_size * p_orderbuffer) = 0; + //! Retrieves your configuration data to be used later when re-instantiating your autoplaylist_client after a restart. + virtual void get_configuration(stream_writer * p_stream,abort_callback & p_abort) = 0; + + virtual void show_ui(t_size p_source_playlist) = 0; + + //! Helper. + template void get_configuration(t_array & p_out) { + PFC_STATIC_ASSERT( sizeof(p_out[0]) == 1 ); + typedef pfc::array_t t_temp; t_temp temp; + get_configuration(&stream_writer_buffer_append_ref_t(temp),abort_callback_dummy()); + p_out = temp; + } +}; + +typedef service_ptr_t autoplaylist_client_ptr; + +//! \since 0.9.5.3 +class NOVTABLE autoplaylist_client_v2 : public autoplaylist_client { + FB2K_MAKE_SERVICE_INTERFACE(autoplaylist_client_v2, autoplaylist_client); +public: + //! Sets a completion_notify object that the autoplaylist_client implementation should call when its filtering behaviors have changed so the whole playlist needs to be rebuilt. \n + //! completion_notify::on_completion() status parameter meaning: \n + //! 0.9.5.3 : ignored. \n + //! 0.9.5.4 and newer: set to 1 to indicate that your configuration has changed as well (for an example as a result of user edits) to get a get_configuration() call as well as cause the playlist to be rebuilt; set to zero otherwise - when the configuration hasn't changed but the playlist needs to be rebuilt as a result of some other event. + virtual void set_full_refresh_notify(completion_notify::ptr notify) = 0; + + //! Returns whether the show_ui() method is available / does anything useful with our implementation (not everyone implements show_ui). + virtual bool show_ui_available() = 0; + + //! Returns a human-readable autoplaylist implementer's label to display in playlist's context menu / description / etc. + virtual void get_display_name(pfc::string_base & out) = 0; +}; + +//! Class needed to re-instantiate autoplaylist_client after a restart. Not directly needed to set up an autoplaylist_client, but without it, your autoplaylist will be lost after a restart. +class NOVTABLE autoplaylist_client_factory : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(autoplaylist_client_factory) +public: + //! Must return same GUID as your autoplaylist_client::get_guid() + virtual GUID get_guid() = 0; + //! Instantiates your autoplaylist_client with specified configuration. + virtual autoplaylist_client_ptr instantiate(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) = 0; +}; + +PFC_DECLARE_EXCEPTION(exception_autoplaylist,pfc::exception,"Autoplaylist error") + +PFC_DECLARE_EXCEPTION(exception_autoplaylist_already_owned,exception_autoplaylist,"This playlist is already an autoplaylist") +PFC_DECLARE_EXCEPTION(exception_autoplaylist_not_owned,exception_autoplaylist,"This playlist is not an autoplaylist") +PFC_DECLARE_EXCEPTION(exception_autoplaylist_lock_failure,exception_autoplaylist,"Playlist could not be locked") + + +//! Primary class for managing autoplaylists. Implemented by core, do not reimplement; instantiate using static_api_ptr_t. +class NOVTABLE autoplaylist_manager : public service_base { +public: + //! Throws exception_autoplaylist or one of its subclasses on failure. + //! @param p_flags See autoplaylist_flag_* constants. + virtual void add_client(autoplaylist_client_ptr p_client,t_size p_playlist,t_uint32 p_flags) = 0; + virtual bool is_client_present(t_size p_playlist) = 0; + //! Throws exception_autoplaylist or one of its subclasses on failure (eg. not an autoplaylist). + virtual autoplaylist_client_ptr query_client(t_size p_playlist) = 0; + virtual void remove_client(t_size p_playlist) = 0; + //! Helper; sets up an autoplaylist using standard autoplaylist_client implementation based on simple query/sort strings. When using this, you don't need to maintain own autoplaylist_client/autoplaylist_client_factory implementations, and autoplaylists that you create will not be lost when your DLL is removed, as opposed to using add_client() directly. + //! Throws exception_autoplaylist or one of its subclasses on failure. + //! @param p_flags See autoplaylist_flag_* constants. + virtual void add_client_simple(const char * p_query,const char * p_sort,t_size p_playlist,t_uint32 p_flags) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(autoplaylist_manager) +}; + +//! \since 0.9.5.4 +//! Extended version of autoplaylist_manager, available from 0.9.5.4 up, with methods allowing modification of autoplaylist flags. +class NOVTABLE autoplaylist_manager_v2 : public autoplaylist_manager { + FB2K_MAKE_SERVICE_INTERFACE(autoplaylist_manager_v2, autoplaylist_manager) +public: + virtual t_uint32 get_client_flags(t_size playlist) = 0; + virtual void set_client_flags(t_size playlist, t_uint32 newFlags) = 0; + + //! For use with autoplaylist client configuration dialogs. It's recommended not to call this from anything else. + virtual t_uint32 get_client_flags(autoplaylist_client::ptr client) = 0; + //! For use with autoplaylist client configuration dialogs. It's recommended not to call this from anything else. + virtual void set_client_flags(autoplaylist_client::ptr client, t_uint32 newFlags) = 0; +}; diff --git a/SDK/foobar2000/SDK/cfg_var.cpp b/SDK/foobar2000/SDK/cfg_var.cpp new file mode 100644 index 0000000..6887813 --- /dev/null +++ b/SDK/foobar2000/SDK/cfg_var.cpp @@ -0,0 +1,60 @@ +#include "foobar2000.h" + +cfg_var_reader * cfg_var_reader::g_list = NULL; +cfg_var_writer * cfg_var_writer::g_list = NULL; + +void cfg_var_reader::config_read_file(stream_reader * p_stream,abort_callback & p_abort) +{ + pfc::map_t vars; + for(cfg_var_reader * walk = g_list; walk != NULL; walk = walk->m_next) { + vars.set(walk->m_guid,walk); + } + for(;;) { + + GUID guid; + t_uint32 size; + + if (p_stream->read(&guid,sizeof(guid),p_abort) != sizeof(guid)) break; + guid = pfc::byteswap_if_be_t(guid); + p_stream->read_lendian_t(size,p_abort); + + cfg_var_reader * var; + if (vars.query(guid,var)) { + stream_reader_limited_ref wrapper(p_stream,size); + try { + var->set_data_raw(&wrapper,size,p_abort); + } catch(exception_io_data) {} + wrapper.flush_remaining(p_abort); + } else { + p_stream->skip_object(size,p_abort); + } + } +} + +void cfg_var_writer::config_write_file(stream_writer * p_stream,abort_callback & p_abort) { + cfg_var_writer * ptr; + pfc::array_t temp; + for(ptr = g_list; ptr; ptr = ptr->m_next) { + temp.set_size(0); + { + stream_writer_buffer_append_ref_t > stream(temp); + ptr->get_data_raw(&stream,p_abort); + } + p_stream->write_lendian_t(ptr->m_guid,p_abort); + p_stream->write_lendian_t(pfc::downcast_guarded(temp.get_size()),p_abort); + if (temp.get_size() > 0) { + p_stream->write_object(temp.get_ptr(),temp.get_size(),p_abort); + } + } +} + + +void cfg_string::get_data_raw(stream_writer * p_stream,abort_callback & p_abort) { + p_stream->write_object(get_ptr(),length(),p_abort); +} + +void cfg_string::set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) { + pfc::string8_fastalloc temp; + p_stream->read_string_raw(temp,p_abort); + set_string(temp); +} diff --git a/SDK/foobar2000/SDK/cfg_var.h b/SDK/foobar2000/SDK/cfg_var.h new file mode 100644 index 0000000..22161df --- /dev/null +++ b/SDK/foobar2000/SDK/cfg_var.h @@ -0,0 +1,289 @@ +#ifndef _FOOBAR2000_SDK_CFG_VAR_H_ +#define _FOOBAR2000_SDK_CFG_VAR_H_ + +#define CFG_VAR_ASSERT_SAFEINIT PFC_ASSERT(!core_api::are_services_available());/*imperfect check for nonstatic instantiation*/ + + +//! Reader part of cfg_var object. In most cases, you should use cfg_var instead of using cfg_var_reader directly. +class NOVTABLE cfg_var_reader { +public: + //! @param p_guid GUID of the variable, used to identify variable implementations owning specific configuration file entries when reading the configuration file back. You must generate a new GUID every time you declare a new cfg_var. + cfg_var_reader(const GUID & guid) : m_guid(guid) { CFG_VAR_ASSERT_SAFEINIT; m_next = g_list; g_list = this; } + ~cfg_var_reader() { CFG_VAR_ASSERT_SAFEINIT; } + + //! Sets state of the variable. Called only from main thread, when reading configuration file. + //! @param p_stream Stream containing new state of the variable. + //! @param p_sizehint Number of bytes contained in the stream; reading past p_sizehint bytes will fail (EOF). + virtual void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) = 0; + + //! For internal use only, do not call. + static void config_read_file(stream_reader * p_stream,abort_callback & p_abort); + + const GUID m_guid; +private: + static cfg_var_reader * g_list; + cfg_var_reader * m_next; + + PFC_CLASS_NOT_COPYABLE_EX(cfg_var_reader) +}; + +//! Writer part of cfg_var object. In most cases, you should use cfg_var instead of using cfg_var_writer directly. +class NOVTABLE cfg_var_writer { +public: + //! @param p_guid GUID of the variable, used to identify variable implementations owning specific configuration file entries when reading the configuration file back. You must generate a new GUID every time you declare a new cfg_var. + cfg_var_writer(const GUID & guid) : m_guid(guid) { CFG_VAR_ASSERT_SAFEINIT; m_next = g_list; g_list = this;} + ~cfg_var_writer() { CFG_VAR_ASSERT_SAFEINIT; } + + //! Retrieves state of the variable. Called only from main thread, when writing configuration file. + //! @param p_stream Stream receiving state of the variable. + virtual void get_data_raw(stream_writer * p_stream,abort_callback & p_abort) = 0; + + //! For internal use only, do not call. + static void config_write_file(stream_writer * p_stream,abort_callback & p_abort); + + const GUID m_guid; +private: + static cfg_var_writer * g_list; + cfg_var_writer * m_next; + + PFC_CLASS_NOT_COPYABLE_EX(cfg_var_writer) +}; + +//! Base class for configuration variable classes; provides self-registration mechaisms and methods to set/retrieve configuration data; those methods are automatically called for all registered instances by backend when configuration file is being read or written.\n +//! Note that cfg_var class and its derivatives may be only instantiated statically (as static objects or members of other static objects), NEVER dynamically (operator new, local variables, members of objects instantiated as such). +class NOVTABLE cfg_var : public cfg_var_reader, public cfg_var_writer { +protected: + //! @param p_guid GUID of the variable, used to identify variable implementations owning specific configuration file entries when reading the configuration file back. You must generate a new GUID every time you declare a new cfg_var. + cfg_var(const GUID & p_guid) : cfg_var_reader(p_guid), cfg_var_writer(p_guid) {} +public: + GUID get_guid() const {return cfg_var_reader::m_guid;} +}; + +//! Generic integer config variable class. Template parameter can be used to specify integer type to use.\n +//! Note that cfg_var class and its derivatives may be only instantiated statically (as static objects or members of other static objects), NEVER dynamically (operator new, local variables, members of objects instantiated as such). +template +class cfg_int_t : public cfg_var { +private: + t_inttype m_val; +protected: + void get_data_raw(stream_writer * p_stream,abort_callback & p_abort) {p_stream->write_lendian_t(m_val,p_abort);} + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) { + t_inttype temp; + p_stream->read_lendian_t(temp,p_abort);//alter member data only on success, this will throw an exception when something isn't right + m_val = temp; + } + +public: + //! @param p_guid GUID of the variable, used to identify variable implementations owning specific configuration file entries when reading the configuration file back. You must generate a new GUID every time you declare a new cfg_var. + //! @param p_default Default value of the variable. + explicit inline cfg_int_t(const GUID & p_guid,t_inttype p_default) : cfg_var(p_guid), m_val(p_default) {} + + inline const cfg_int_t & operator=(const cfg_int_t & p_val) {m_val=p_val.m_val;return *this;} + inline t_inttype operator=(t_inttype p_val) {m_val=p_val;return m_val;} + + inline operator t_inttype() const {return m_val;} + + inline t_inttype get_value() const {return m_val;} +}; + +typedef cfg_int_t cfg_int; +typedef cfg_int_t cfg_uint; +//! Since relevant byteswapping functions also understand GUIDs, this can be abused to declare a cfg_guid. +typedef cfg_int_t cfg_guid; +typedef cfg_int_t cfg_bool; + +//! String config variable. Stored in the stream with int32 header containing size in bytes, followed by non-null-terminated UTF-8 data.\n +//! Note that cfg_var class and its derivatives may be only instantiated statically (as static objects or members of other static objects), NEVER dynamically (operator new, local variables, members of objects instantiated as such). +class cfg_string : public cfg_var, public pfc::string8 { +protected: + void get_data_raw(stream_writer * p_stream,abort_callback & p_abort); + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort); + +public: + //! @param p_guid GUID of the variable, used to identify variable implementations owning specific configuration file entries when reading the configuration file back. You must generate a new GUID every time you declare a new cfg_var. + //! @param p_defaultval Default/initial value of the variable. + explicit inline cfg_string(const GUID & p_guid,const char * p_defaultval) : cfg_var(p_guid), pfc::string8(p_defaultval) {} + + inline const cfg_string& operator=(const cfg_string & p_val) {set_string(p_val);return *this;} + inline const cfg_string& operator=(const char* p_val) {set_string(p_val);return *this;} + + inline operator const char * () const {return get_ptr();} +}; + + +class cfg_string_mt : public cfg_var { +protected: + void get_data_raw(stream_writer * p_stream,abort_callback & p_abort) { + insync(m_sync); + p_stream->write_object(m_val.get_ptr(),m_val.length(),p_abort); + } + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) { + pfc::string8_fastalloc temp; + p_stream->read_string_raw(temp,p_abort); + set(temp); + } +public: + cfg_string_mt(const GUID & id, const char * defVal) : cfg_var(id), m_val(defVal) {} + void get(pfc::string_base & out) const { + insync(m_sync); + out = m_val; + } + void set(const char * val, t_size valLen = ~0) { + insync(m_sync); + m_val.set_string(val, valLen); + } +private: + mutable critical_section m_sync; + pfc::string8 m_val; +}; + +//! Struct config variable template. Warning: not endian safe, should be used only for nonportable code.\n +//! Note that cfg_var class and its derivatives may be only instantiated statically (as static objects or members of other static objects), NEVER dynamically (operator new, local variables, members of objects instantiated as such). +template +class cfg_struct_t : public cfg_var { +private: + t_struct m_val; +protected: + + void get_data_raw(stream_writer * p_stream,abort_callback & p_abort) {p_stream->write_object(&m_val,sizeof(m_val),p_abort);} + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) { + t_struct temp; + p_stream->read_object(&temp,sizeof(temp),p_abort); + m_val = temp; + } +public: + //! @param p_guid GUID of the variable, used to identify variable implementations owning specific configuration file entries when reading the configuration file back. You must generate a new GUID every time you declare a new cfg_var. + inline cfg_struct_t(const GUID & p_guid,const t_struct & p_val) : cfg_var(p_guid), m_val(p_val) {} + //! @param p_guid GUID of the variable, used to identify variable implementations owning specific configuration file entries when reading the configuration file back. You must generate a new GUID every time you declare a new cfg_var. + inline cfg_struct_t(const GUID & p_guid,int filler) : cfg_var(p_guid) {memset(&m_val,filler,sizeof(t_struct));} + + inline const cfg_struct_t & operator=(const cfg_struct_t & p_val) {m_val = p_val.get_value();return *this;} + inline const cfg_struct_t & operator=(const t_struct & p_val) {m_val = p_val;return *this;} + + inline const t_struct& get_value() const {return m_val;} + inline t_struct& get_value() {return m_val;} + inline operator t_struct() const {return m_val;} +}; + + +template +class cfg_objList : public cfg_var, public pfc::list_t { +public: + typedef cfg_objList t_self; + cfg_objList(const GUID& guid) : cfg_var(guid) {} + template cfg_objList(const GUID& guid, const TSource (& source)[Count]) : cfg_var(guid) { + reset(source); + } + template void reset(const TSource (& source)[Count]) { + this->set_size(Count); for(t_size walk = 0; walk < Count; ++walk) (*this)[walk] = source[walk]; + } + void get_data_raw(stream_writer * p_stream,abort_callback & p_abort) { + stream_writer_formatter<> out(*p_stream,p_abort); + out << pfc::downcast_guarded(this->get_size()); + for(t_size walk = 0; walk < this->get_size(); ++walk) out << (*this)[walk]; + } + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) { + try { + stream_reader_formatter<> in(*p_stream,p_abort); + t_uint32 count; in >> count; + this->set_count(count); + for(t_uint32 walk = 0; walk < count; ++walk) in >> (*this)[walk]; + } catch(...) { + this->remove_all(); + throw; + } + } + template t_self & operator=(t_in const & source) {this->remove_all(); this->add_items(source); return *this;} + template t_self & operator+=(t_in const & p_source) {this->add_item(p_source); return *this;} + template t_self & operator|=(t_in const & p_source) {this->add_items(p_source); return *this;} +}; +template +class cfg_objListEx : public cfg_var, public TList { +public: + typedef cfg_objListEx t_self; + cfg_objListEx(const GUID & guid) : cfg_var(guid) {} + void get_data_raw(stream_writer * p_stream, abort_callback & p_abort) { + stream_writer_formatter<> out(*p_stream,p_abort); + out << pfc::downcast_guarded(this->get_count()); + for(typename TList::const_iterator walk = this->first(); walk.is_valid(); ++walk) out << *walk; + } + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) { + this->remove_all(); + stream_reader_formatter<> in(*p_stream,p_abort); + t_uint32 count; in >> count; + for(t_uint32 walk = 0; walk < count; ++walk) { + typename TList::t_item item; in >> item; this->add_item(item); + } + } + template t_self & operator=(t_in const & source) {this->remove_all(); this->add_items(source); return *this;} + template t_self & operator+=(t_in const & p_source) {this->add_item(p_source); return *this;} + template t_self & operator|=(t_in const & p_source) {this->add_items(p_source); return *this;} +}; + +template +class cfg_obj : public cfg_var, public TObj { +public: + cfg_obj(const GUID& guid) : cfg_var(guid), TObj() {} + template cfg_obj(const GUID& guid,const TInitData& initData) : cfg_var(guid), TObj(initData) {} + + TObj & val() {return *this;} + TObj const & val() const {return *this;} + + void get_data_raw(stream_writer * p_stream,abort_callback & p_abort) { + stream_writer_formatter<> out(*p_stream,p_abort); + const TObj * ptr = this; + out << *ptr; + } + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) { + stream_reader_formatter<> in(*p_stream,p_abort); + TObj * ptr = this; + in >> *ptr; + } +}; + +template class cfg_objListImporter : private cfg_var_reader { +public: + typedef cfg_objList TMasterVar; + cfg_objListImporter(TMasterVar & var, const GUID & guid) : m_var(var), cfg_var_reader(guid) {} + + private: + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) { + TImport temp; + try { + stream_reader_formatter<> in(*p_stream,p_abort); + t_uint32 count; in >> count; + m_var.set_count(count); + for(t_uint32 walk = 0; walk < count; ++walk) { + in >> temp; + m_var[walk] = temp; + } + } catch(...) { + m_var.remove_all(); + throw; + } + } + TMasterVar & m_var; +}; +template class cfg_objMap : private cfg_var, public TMap { +public: + cfg_objMap(const GUID & id) : cfg_var(id) {} +private: + void get_data_raw(stream_writer * p_stream,abort_callback & p_abort) { + stream_writer_formatter<> out(*p_stream, p_abort); + out << pfc::downcast_guarded(this->get_count()); + for(typename TMap::const_iterator walk = this->first(); walk.is_valid(); ++walk) { + out << walk->m_key << walk->m_value; + } + } + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) { + this->remove_all(); + stream_reader_formatter<> in(*p_stream, p_abort); + t_uint32 count; in >> count; + for(t_uint32 walk = 0; walk < count; ++walk) { + typename TMap::t_key key; in >> key; PFC_ASSERT( !this->have_item(key) ); + try { in >> this->find_or_add( key ); } catch(...) { this->remove(key); throw; } + } + } +}; + +#endif diff --git a/SDK/foobar2000/SDK/chapterizer.cpp b/SDK/foobar2000/SDK/chapterizer.cpp new file mode 100644 index 0000000..4c0a865 --- /dev/null +++ b/SDK/foobar2000/SDK/chapterizer.cpp @@ -0,0 +1,96 @@ +#include "foobar2000.h" + +void chapter_list::copy(const chapter_list & p_source) +{ + t_size n, count = p_source.get_chapter_count(); + set_chapter_count(count); + for(n=0;n & p_out,const char * p_path) +{ + service_ptr_t ptr; + service_enum_t e; + while(e.next(ptr)) { + if (ptr->is_our_path(p_path)) { + p_out = ptr; + return true; + } + } + return false; +} + +bool chapterizer::g_is_pregap_capable(const char * p_path) { + service_ptr_t ptr; + service_enum_t e; + while(e.next(ptr)) { + if (ptr->supports_pregaps() && ptr->is_our_path(p_path)) { + return true; + } + } + return false; +} + +cuesheet_format_index_time::cuesheet_format_index_time(double p_time) +{ + t_uint64 ticks = audio_math::time_to_samples(p_time,75); + t_uint64 seconds = ticks / 75; ticks %= 75; + t_uint64 minutes = seconds / 60; seconds %= 60; + m_buffer << pfc::format_uint(minutes,2) << ":" << pfc::format_uint(seconds,2) << ":" << pfc::format_uint(ticks,2); +} + +double cuesheet_parse_index_time_e(const char * p_string,t_size p_length) +{ + return (double) cuesheet_parse_index_time_ticks_e(p_string,p_length) / 75.0; +} + +unsigned cuesheet_parse_index_time_ticks_e(const char * p_string,t_size p_length) +{ + p_length = pfc::strlen_max(p_string,p_length); + t_size ptr = 0; + t_size splitmarks[2]; + t_size splitptr = 0; + for(ptr=0;ptr= 2) throw std::runtime_error("invalid INDEX time syntax"); + splitmarks[splitptr++] = ptr; + } + else if (!pfc::char_is_numeric(p_string[ptr])) throw std::runtime_error("invalid INDEX time syntax"); + } + + t_size minutes_base = 0, minutes_length = 0, seconds_base = 0, seconds_length = 0, frames_base = 0, frames_length = 0; + + switch(splitptr) + { + case 0: + frames_base = 0; + frames_length = p_length; + break; + case 1: + seconds_base = 0; + seconds_length = splitmarks[0]; + frames_base = splitmarks[0] + 1; + frames_length = p_length - frames_base; + break; + case 2: + minutes_base = 0; + minutes_length = splitmarks[0]; + seconds_base = splitmarks[0] + 1; + seconds_length = splitmarks[1] - seconds_base; + frames_base = splitmarks[1] + 1; + frames_length = p_length - frames_base; + break; + } + + unsigned ret = 0; + + if (frames_length > 0) ret += pfc::atoui_ex(p_string + frames_base,frames_length); + if (seconds_length > 0) ret += 75 * pfc::atoui_ex(p_string + seconds_base,seconds_length); + if (minutes_length > 0) ret += 60 * 75 * pfc::atoui_ex(p_string + minutes_base,minutes_length); + + return ret; +} + diff --git a/SDK/foobar2000/SDK/chapterizer.h b/SDK/foobar2000/SDK/chapterizer.h new file mode 100644 index 0000000..4dad7b0 --- /dev/null +++ b/SDK/foobar2000/SDK/chapterizer.h @@ -0,0 +1,97 @@ +//! Interface for object storing list of chapters. +class NOVTABLE chapter_list { +public: + //! Returns number of chapters. + virtual t_size get_chapter_count() const = 0; + //! Queries description of specified chapter. + //! @param p_chapter Index of chapter to query, greater or equal zero and less than get_chapter_count() value. If p_chapter value is out of valid range, results are undefined (e.g. crash). + //! @returns reference to file_info object describing specified chapter (length part of file_info indicates distance between beginning of this chapter and next chapter mark). Returned reference value for temporary use only, becomes invalid after any non-const operation on the chapter_list object. + virtual const file_info & get_info(t_size p_chapter) const = 0; + + //! Sets number of chapters. + virtual void set_chapter_count(t_size p_count) = 0; + //! Modifies description of specified chapter. + //! @param p_chapter_index Index of chapter to modify, greater or equal zero and less than get_chapter_count() value. If p_chapter value is out of valid range, results are undefined (e.g. crash). + //! @param p_info New chapter description. Note that length part of file_info is used to calculate chapter marks. + virtual void set_info(t_size p_chapter,const file_info & p_info) = 0; + + virtual double get_pregap() const = 0; + virtual void set_pregap(double val) = 0; + + //! Copies contents of specified chapter_list object to this object. + void copy(const chapter_list & p_source); + + inline const chapter_list & operator=(const chapter_list & p_source) {copy(p_source); return *this;} + +protected: + chapter_list() {} + ~chapter_list() {} +}; + +//! Implements chapter_list. +template +class chapter_list_impl_t : public chapter_list { +public: + chapter_list_impl_t() : m_pregap() {} + typedef chapter_list_impl_t t_self; + chapter_list_impl_t(const chapter_list & p_source) : m_pregap() {copy(p_source);} + + const t_self & operator=(const chapter_list & p_source) {copy(p_source); return *this;} + + t_size get_chapter_count() const {return m_infos.get_size();} + const file_info & get_info(t_size p_chapter) const {return m_infos[p_chapter];} + + void set_chapter_count(t_size p_count) {m_infos.set_size(p_count);} + void set_info(t_size p_chapter,const file_info & p_info) {m_infos[p_chapter] = p_info;} + file_info_ & get_info_(t_size p_chapter) {return m_infos[p_chapter];} + + double get_pregap() const {return m_pregap;} + void set_pregap(double val) {PFC_ASSERT(val >= 0); m_pregap = val;} +private: + pfc::array_t m_infos; + double m_pregap; +}; + +typedef chapter_list_impl_t<> chapter_list_impl; + + +//! This service implements chapter list editing operations for various file formats, e.g. for MP4 chapters or CD images with embedded cuesheets. Used by converter "encode single file with chapters" feature. +class NOVTABLE chapterizer : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(chapterizer); +public: + //! Tests whether specified path is supported by this implementation. + //! @param p_ext Extension of the file being processed. + virtual bool is_our_path(const char * p_path) = 0; + + //! Writes new chapter list to specified file. + //! @param p_path Path of file to modify. + //! @param p_list New chapter list to write. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void set_chapters(const char * p_path,chapter_list const & p_list,abort_callback & p_abort) = 0; + //! Retrieves chapter list from specified file. + //! @param p_path Path of file to examine. + //! @param p_list Object receiving chapter list. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void get_chapters(const char * p_path,chapter_list & p_list,abort_callback & p_abort) = 0; + + virtual bool supports_pregaps() = 0; + + //! Static helper, tries to find chapterizer interface that supports specified file. + static bool g_find(service_ptr_t & p_out,const char * p_path); + + static bool g_is_pregap_capable(const char * p_path); +}; + + + +unsigned cuesheet_parse_index_time_ticks_e(const char * p_string,t_size p_length); +double cuesheet_parse_index_time_e(const char * p_string,t_size p_length); + +class cuesheet_format_index_time +{ +public: + cuesheet_format_index_time(double p_time); + inline operator const char*() const {return m_buffer;} +private: + pfc::string_formatter m_buffer; +}; diff --git a/SDK/foobar2000/SDK/commandline.cpp b/SDK/foobar2000/SDK/commandline.cpp new file mode 100644 index 0000000..af8be2b --- /dev/null +++ b/SDK/foobar2000/SDK/commandline.cpp @@ -0,0 +1,12 @@ +#include "foobar2000.h" + +void commandline_handler_metadb_handle::on_file(const char * url) { + metadb_handle_list handles; + try { + static_api_ptr_t()->path_to_handles_simple(url, handles); + } catch(std::exception const & e) { + console::complain("Path evaluation failure", e); + return; + } + for(t_size walk = 0; walk < handles.get_size(); ++walk) on_file(handles[walk]); +} diff --git a/SDK/foobar2000/SDK/commandline.h b/SDK/foobar2000/SDK/commandline.h new file mode 100644 index 0000000..067ccaa --- /dev/null +++ b/SDK/foobar2000/SDK/commandline.h @@ -0,0 +1,41 @@ +class NOVTABLE commandline_handler : public service_base +{ +public: + enum result + { + RESULT_NOT_OURS,//not our command + RESULT_PROCESSED,//command processed + RESULT_PROCESSED_EXPECT_FILES,//command processed, we want to takeover file urls after this command + }; + virtual result on_token(const char * token)=0; + virtual void on_file(const char * url) {};//optional + virtual void on_files_done() {};//optional + virtual bool want_directories() {return false;} + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(commandline_handler); +}; + +class commandline_handler_metadb_handle : public commandline_handler//helper +{ +protected: + virtual void on_file(const char * url); + virtual bool want_directories() {return true;} +public: + virtual result on_token(const char * token)=0; + virtual void on_files_done() {}; + + virtual void on_file(const metadb_handle_ptr & ptr)=0; +}; + +/* + +how commandline_handler is used: + + scenario #1: + creation => on_token() => deletion + scenario #2: + creation => on_token() returning RESULT_PROCESSED_EXPECT_FILES => on_file(), on_file().... => on_files_done() => deletion +*/ + +template +class commandline_handler_factory_t : public service_factory_t {}; diff --git a/SDK/foobar2000/SDK/completion_notify.cpp b/SDK/foobar2000/SDK/completion_notify.cpp new file mode 100644 index 0000000..21d9adc --- /dev/null +++ b/SDK/foobar2000/SDK/completion_notify.cpp @@ -0,0 +1,87 @@ +#include "foobar2000.h" + +namespace { + class main_thread_callback_myimpl : public main_thread_callback { + public: + void callback_run() { + m_notify->on_completion(m_code); + } + + main_thread_callback_myimpl(completion_notify_ptr p_notify,unsigned p_code) : m_notify(p_notify), m_code(p_code) {} + private: + completion_notify_ptr m_notify; + unsigned m_code; + }; +} + +void completion_notify::g_signal_completion_async(completion_notify_ptr p_notify,unsigned p_code) { + if (p_notify.is_valid()) { + static_api_ptr_t()->add_callback(new service_impl_t(p_notify,p_code)); + } +} + +void completion_notify::on_completion_async(unsigned p_code) { + static_api_ptr_t()->add_callback(new service_impl_t(this,p_code)); +} + + +completion_notify::ptr completion_notify_receiver::create_or_get_task(unsigned p_id) { + completion_notify_orphanable_ptr ptr; + if (!m_tasks.query(p_id,ptr)) { + ptr = completion_notify_create(this,p_id); + m_tasks.set(p_id,ptr); + } + return ptr; +} + +completion_notify_ptr completion_notify_receiver::create_task(unsigned p_id) { + completion_notify_orphanable_ptr ptr; + if (m_tasks.query(p_id,ptr)) ptr->orphan(); + ptr = completion_notify_create(this,p_id); + m_tasks.set(p_id,ptr); + return ptr; +} + +bool completion_notify_receiver::have_task(unsigned p_id) const { + return m_tasks.have_item(p_id); +} + +void completion_notify_receiver::orphan_task(unsigned p_id) { + completion_notify_orphanable_ptr ptr; + if (m_tasks.query(p_id,ptr)) { + ptr->orphan(); + m_tasks.remove(p_id); + } +} + +completion_notify_receiver::~completion_notify_receiver() { + orphan_all_tasks(); +} + +void completion_notify_receiver::orphan_all_tasks() { + m_tasks.enumerate(orphanfunc); + m_tasks.remove_all(); +} + +namespace { + using namespace fb2k; + + class completion_notify_func : public completion_notify { + public: + void on_completion(unsigned p_code) { + m_func(p_code); + } + + completionNotifyFunc_t m_func; + }; +} + +namespace fb2k { + + completion_notify::ptr makeCompletionNotify( completionNotifyFunc_t func ) { + service_ptr_t n = new service_impl_t< completion_notify_func >; + n->m_func = func; + return n; + } + +} diff --git a/SDK/foobar2000/SDK/completion_notify.h b/SDK/foobar2000/SDK/completion_notify.h new file mode 100644 index 0000000..599e96a --- /dev/null +++ b/SDK/foobar2000/SDK/completion_notify.h @@ -0,0 +1,83 @@ +#include + +//! Generic service for receiving notifications about async operation completion. Used by various other services. +class completion_notify : public service_base { +public: + //! Called when an async operation has been completed. Note that on_completion is always called from main thread. You can use on_completion_async() helper if you need to signal completion while your context is in another thread.\n + //! IMPLEMENTATION WARNING: If process being completed creates a window taking caller's window as parent, you must not destroy the parent window inside on_completion(). If you need to do so, use PostMessage() or main_thread_callback to delay the deletion. + //! @param p_code Context-specific status code. Possible values depend on the operation being performed. + virtual void on_completion(unsigned p_code) = 0; + + //! Helper. Queues a notification, using main_thread_callback. + void on_completion_async(unsigned p_code); + + //! Helper. Checks for null ptr and calls on_completion_async when the ptr is not null. + static void g_signal_completion_async(service_ptr_t p_notify,unsigned p_code); + + FB2K_MAKE_SERVICE_INTERFACE(completion_notify,service_base); +}; + +//! Implementation helper. +class completion_notify_dummy : public completion_notify { +public: + void on_completion(unsigned p_code) {} +}; + +//! Implementation helper. +class completion_notify_orphanable : public completion_notify { +public: + virtual void orphan() = 0; +}; + +//! Helper implementation. +//! IMPLEMENTATION WARNING: If process being completed creates a window taking caller's window as parent, you must not destroy the parent window inside on_task_completion(). If you need to do so, use PostMessage() or main_thread_callback to delay the deletion. +template +class completion_notify_impl : public completion_notify_orphanable { +public: + void on_completion(unsigned p_code) { + if (m_receiver != NULL) { + m_receiver->on_task_completion(m_taskid,p_code); + } + } + void setup(t_receiver * p_receiver, unsigned p_task_id) {m_receiver = p_receiver; m_taskid = p_task_id;} + void orphan() {m_receiver = NULL; m_taskid = 0;} +private: + t_receiver * m_receiver; + unsigned m_taskid; +}; + +template +service_nnptr_t completion_notify_create(t_receiver * p_receiver,unsigned p_taskid) { + service_nnptr_t > instance = new service_impl_t >(); + instance->setup(p_receiver,p_taskid); + return instance; +} + +typedef service_ptr_t completion_notify_ptr; +typedef service_ptr_t completion_notify_orphanable_ptr; +typedef service_nnptr_t completion_notify_nnptr; +typedef service_nnptr_t completion_notify_orphanable_nnptr; + +//! Helper base class for classes that manage nonblocking tasks and get notified back thru completion_notify interface. +class completion_notify_receiver { +public: + completion_notify::ptr create_or_get_task(unsigned p_id); + completion_notify_ptr create_task(unsigned p_id); + bool have_task(unsigned p_id) const; + void orphan_task(unsigned p_id); + ~completion_notify_receiver(); + void orphan_all_tasks(); + + virtual void on_task_completion(unsigned p_id,unsigned p_status) {} +private: + static void orphanfunc(unsigned,completion_notify_orphanable_nnptr p_item) {p_item->orphan();} + pfc::map_t m_tasks; +}; + +namespace fb2k { + + typedef std::function completionNotifyFunc_t; + + //! Modern completion_notify helper + completion_notify::ptr makeCompletionNotify( completionNotifyFunc_t ); +} diff --git a/SDK/foobar2000/SDK/component.h b/SDK/foobar2000/SDK/component.h new file mode 100644 index 0000000..04efdb3 --- /dev/null +++ b/SDK/foobar2000/SDK/component.h @@ -0,0 +1,57 @@ +#include "foobar2000.h" + +// This is a helper class that gets reliably static-instantiated in all components so any special code that must be executed on startup can be shoved into its constructor. +class foobar2000_component_globals { +public: + foobar2000_component_globals() { +#ifdef _MSC_VER +#ifndef _DEBUG + ::OverrideCrtAbort(); +#endif +#endif + } +}; + +class NOVTABLE foobar2000_client +{ +public: + typedef service_factory_base* pservice_factory_base; + + enum { + FOOBAR2000_CLIENT_VERSION_COMPATIBLE = 72, + FOOBAR2000_CLIENT_VERSION = FOOBAR2000_TARGET_VERSION, + }; + virtual t_uint32 get_version() = 0; + virtual pservice_factory_base get_service_list() = 0; + + virtual void get_config(stream_writer * p_stream,abort_callback & p_abort) = 0; + virtual void set_config(stream_reader * p_stream,abort_callback & p_abort) = 0; + virtual void set_library_path(const char * path,const char * name) = 0; + virtual void services_init(bool val) = 0; + virtual bool is_debug() = 0; +protected: + foobar2000_client() {} + ~foobar2000_client() {} +}; + +class NOVTABLE foobar2000_api { +public: + virtual service_class_ref service_enum_find_class(const GUID & p_guid) = 0; + virtual bool service_enum_create(service_ptr_t & p_out,service_class_ref p_class,t_size p_index) = 0; + virtual t_size service_enum_get_count(service_class_ref p_class) = 0; + virtual HWND get_main_window()=0; + virtual bool assert_main_thread()=0; + virtual bool is_main_thread()=0; + virtual bool is_shutting_down()=0; + virtual const char * get_profile_path()=0; + virtual bool is_initializing() = 0; + + //New in 0.9.6 + virtual bool is_portable_mode_enabled() = 0; + virtual bool is_quiet_mode_enabled() = 0; +protected: + foobar2000_api() {} + ~foobar2000_api() {} +}; + +extern foobar2000_api * g_foobar2000_api; diff --git a/SDK/foobar2000/SDK/component_client.h b/SDK/foobar2000/SDK/component_client.h new file mode 100644 index 0000000..a0cfb6b --- /dev/null +++ b/SDK/foobar2000/SDK/component_client.h @@ -0,0 +1,6 @@ +#ifndef _COMPONENT_CLIENT_H_ +#define _COMPONENT_CLIENT_H_ + + + +#endif //_COMPONENT_CLIENT_H_ \ No newline at end of file diff --git a/SDK/foobar2000/SDK/components_menu.h b/SDK/foobar2000/SDK/components_menu.h new file mode 100644 index 0000000..5c10027 --- /dev/null +++ b/SDK/foobar2000/SDK/components_menu.h @@ -0,0 +1,7 @@ +#ifndef _COMPONENTS_MENU_H_ +#define _COMPONENTS_MENU_H_ + +#error deprecated, see menu_item.h + + +#endif \ No newline at end of file diff --git a/SDK/foobar2000/SDK/componentversion.cpp b/SDK/foobar2000/SDK/componentversion.cpp new file mode 100644 index 0000000..56fdda6 --- /dev/null +++ b/SDK/foobar2000/SDK/componentversion.cpp @@ -0,0 +1,37 @@ +#include "foobar2000.h" + +bool component_installation_validator::test_my_name(const char * fn) { + const char * path = core_api::get_my_full_path(); + path += pfc::scan_filename(path); + bool retVal = ( strcmp(path, fn) == 0 ); + PFC_ASSERT( retVal ); + return retVal; +} +bool component_installation_validator::have_other_file(const char * fn) { + for(int retry = 0;;) { + pfc::string_formatter path = core_api::get_my_full_path(); + path.truncate(path.scan_filename()); + path << fn; + try { + try { + abort_callback_dummy aborter; + bool v = filesystem::g_exists(path, aborter); + PFC_ASSERT( v ); + return v; + } catch(std::exception const & e) { + FB2K_console_formatter() << "Component integrity check error: " << e << " (on: " << fn << ")"; + throw; + } + } catch(exception_io_denied) { + continue; + } catch(exception_io_sharing_violation) { + continue; + } catch(exception_io_file_corrupted) { // happens + return false; + } catch(...) { + uBugCheck(); + } + if (++retry == 10) uBugCheck(); + Sleep(100); + } +} diff --git a/SDK/foobar2000/SDK/componentversion.h b/SDK/foobar2000/SDK/componentversion.h new file mode 100644 index 0000000..f8cbb9f --- /dev/null +++ b/SDK/foobar2000/SDK/componentversion.h @@ -0,0 +1,93 @@ +//! Entrypoint interface for declaring component's version information. Instead of implementing this directly, use DECLARE_COMPONENT_VERSION(). +class NOVTABLE componentversion : public service_base { +public: + virtual void get_file_name(pfc::string_base & out)=0; + virtual void get_component_name(pfc::string_base & out)=0; + virtual void get_component_version(pfc::string_base & out)=0; + virtual void get_about_message(pfc::string_base & out)=0;//about message uses "\n" for line separators + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(componentversion); +}; + +//! Implementation helper. You typically want to use DECLARE_COMPONENT_VERSION() instead. +class componentversion_impl_simple : public componentversion { + const char * name,*version,*about; +public: + //do not derive/override + virtual void get_file_name(pfc::string_base & out) {out.set_string(core_api::get_my_file_name());} + virtual void get_component_name(pfc::string_base & out) {out.set_string(name?name:"");} + virtual void get_component_version(pfc::string_base & out) {out.set_string(version?version:"");} + virtual void get_about_message(pfc::string_base & out) {out.set_string(about?about:"");} + explicit componentversion_impl_simple(const char * p_name,const char * p_version,const char * p_about) : name(p_name), version(p_version), about(p_about ? p_about : "") {} +}; + +//! Implementation helper. You typically want to use DECLARE_COMPONENT_VERSION() instead. +class componentversion_impl_copy : public componentversion { + pfc::string8 name,version,about; +public: + //do not derive/override + virtual void get_file_name(pfc::string_base & out) {out.set_string(core_api::get_my_file_name());} + virtual void get_component_name(pfc::string_base & out) {out.set_string(name);} + virtual void get_component_version(pfc::string_base & out) {out.set_string(version);} + virtual void get_about_message(pfc::string_base & out) {out.set_string(about);} + explicit componentversion_impl_copy(const char * p_name,const char * p_version,const char * p_about) : name(p_name), version(p_version), about(p_about ? p_about : "") {} +}; + +typedef service_factory_single_transparent_t __componentversion_impl_simple_factory; +typedef service_factory_single_transparent_t __componentversion_impl_copy_factory; + +class componentversion_impl_simple_factory : public __componentversion_impl_simple_factory { +public: + componentversion_impl_simple_factory(const char * p_name,const char * p_version,const char * p_about) : __componentversion_impl_simple_factory(p_name,p_version,p_about) {} +}; + +class componentversion_impl_copy_factory : public __componentversion_impl_copy_factory { +public: + componentversion_impl_copy_factory(const char * p_name,const char * p_version,const char * p_about) : __componentversion_impl_copy_factory(p_name,p_version,p_about) {} +}; + +//! Use this to declare your component's version information. Parameters must ba plain const char * string constants. \n +//! You should have only one DECLARE_COMPONENT_VERSION() per component DLL. Having more than one will confuse component updater's version matching. \n +//! Please keep your version numbers formatted as: N[.N[.N....]][ alpha|beta|RC[ N[.N...]] \n +//! Sample version numbers, in ascending order: 0.9 < 0.10 < 1.0 alpha 1 < 1.0 alpha 2 < 1.0 beta 1 < 1.0 RC < 1.0 RC1 < 1.0 < 1.1 < 1.10 \n +//! For a working sample of how foobar2000 sorts version numbers, see http://www.foobar2000.org/versionator.php \n +//! Example: DECLARE_COMPONENT_VERSION("blah","1.3.3.7","") +#define DECLARE_COMPONENT_VERSION(NAME,VERSION,ABOUT) \ + namespace {class componentversion_myimpl : public componentversion { public: componentversion_myimpl() {PFC_ASSERT( ABOUT );} \ + void get_file_name(pfc::string_base & out) {out = core_api::get_my_file_name();} \ + void get_component_name(pfc::string_base & out) {out = NAME;} \ + void get_component_version(pfc::string_base & out) {out = VERSION;} \ + void get_about_message(pfc::string_base & out) {out = ABOUT;} \ + }; static service_factory_single_t g_componentversion_myimpl_factory; } + // static componentversion_impl_simple_factory g_componentversion_service(NAME,VERSION,ABOUT); + +//! Same as DECLARE_COMPONENT_VERSION(), but parameters can be dynamically generated strings rather than compile-time constants. +#define DECLARE_COMPONENT_VERSION_COPY(NAME,VERSION,ABOUT) \ + static componentversion_impl_copy_factory g_componentversion_service(NAME,VERSION,ABOUT); + + +//! \since 1.0 +//! Allows components to cleanly abort app startup in case the installation appears to have become corrupted. +class component_installation_validator : public service_base { +public: + virtual bool is_installed_correctly() = 0; + + static bool test_my_name(const char * fn); + static bool have_other_file(const char * fn); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(component_installation_validator) +}; + +//! Simple implementation of component_installation_validator that makes sure that our component DLL has not been renamed around by idiot users. +class component_installation_validator_filename : public component_installation_validator { +public: + component_installation_validator_filename(const char * dllName) : m_dllName(dllName) {} + bool is_installed_correctly() { + return test_my_name(m_dllName); + } +private: + const char * const m_dllName; +}; + +#define VALIDATE_COMPONENT_FILENAME(FN) \ + static service_factory_single_t g_component_installation_validator_filename(FN); diff --git a/SDK/foobar2000/SDK/config_io_callback.h b/SDK/foobar2000/SDK/config_io_callback.h new file mode 100644 index 0000000..7fb7db2 --- /dev/null +++ b/SDK/foobar2000/SDK/config_io_callback.h @@ -0,0 +1,23 @@ +//! Implementing this interface lets you maintain your own configuration files rather than depending on the cfg_var system. \n +//! Note that you must not make assumptions about what happens first: config_io_callback::on_read(), initialization of cfg_var values or config_io_callback::on_read() in other components. Order of these things is undefined and will change with each run. \n +//! Use service_factory_single_t to register your implementations. Do not call other people's implementations, core is responsible for doing that when appropriate. +class NOVTABLE config_io_callback : public service_base { +public: + //! Called on startup. You can read your configuration file from here. \n + //! Hint: use core_api::get_profile_path() to retrieve the path of the folder where foobar2000 configuration files are stored. + virtual void on_read() = 0; + //! Called typically on shutdown but you should expect a call at any point after on_read(). You can write your configuration file from here. + //! Hint: use core_api::get_profile_path() to retrieve the path of the folder where foobar2000 configuration files are stored. + //! @param reset If set to true, our configuration is being reset, so you should wipe your files rather than rewrite them with current configuration. + virtual void on_write(bool reset) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(config_io_callback); +}; + +//! \since 1.0 +class NOVTABLE config_io_callback_v2 : public config_io_callback { + FB2K_MAKE_SERVICE_INTERFACE(config_io_callback_v2, config_io_callback) +public: + //! Implement optionally. Called to quickly flush recent configuration changes. If your instance of config_io_callback needs to perform timeconsuming tasks when saving, you should skip implementing this method entirely. + virtual void on_quicksave() = 0; +}; diff --git a/SDK/foobar2000/SDK/config_object.cpp b/SDK/foobar2000/SDK/config_object.cpp new file mode 100644 index 0000000..36ff51d --- /dev/null +++ b/SDK/foobar2000/SDK/config_object.cpp @@ -0,0 +1,214 @@ +#include "foobar2000.h" + +void config_object_notify_manager::g_on_changed(const service_ptr_t & p_object) +{ + if (core_api::assert_main_thread()) + { + service_enum_t e; + service_ptr_t ptr; + while(e.next(ptr)) + ptr->on_changed(p_object); + } +} + +bool config_object::g_find(service_ptr_t & p_out,const GUID & p_guid) +{ + service_ptr_t ptr; + service_enum_t e; + while(e.next(ptr)) + { + if (ptr->get_guid() == p_guid) + { + p_out = ptr; + return true; + } + } + return false; +} + +void config_object::g_get_data_string(const GUID & p_guid,pfc::string_base & p_out) +{ + service_ptr_t ptr; + if (!g_find(ptr,p_guid)) throw exception_service_not_found(); + ptr->get_data_string(p_out); +} + +void config_object::g_set_data_string(const GUID & p_guid,const char * p_data,t_size p_length) +{ + service_ptr_t ptr; + if (!g_find(ptr,p_guid)) throw exception_service_not_found(); + ptr->set_data_string(p_data,p_length); +} + +void config_object::get_data_int32(t_int32 & p_out) +{ + t_int32 temp; + get_data_struct_t(temp); + byte_order::order_le_to_native_t(temp); + p_out = temp; +} + +void config_object::set_data_int32(t_int32 p_val) +{ + t_int32 temp = p_val; + byte_order::order_native_to_le_t(temp); + set_data_struct_t(temp); +} + +bool config_object::get_data_bool_simple(bool p_default) { + try { + bool ret = p_default; + get_data_bool(ret); + return ret; + } catch(...) {return p_default;} +} + +t_int32 config_object::get_data_int32_simple(t_int32 p_default) { + try { + t_int32 ret = p_default; + get_data_int32(ret); + return ret; + } catch(...) {return p_default;} +} + +void config_object::g_get_data_int32(const GUID & p_guid,t_int32 & p_out) { + service_ptr_t ptr; + if (!g_find(ptr,p_guid)) throw exception_service_not_found(); + ptr->get_data_int32(p_out); +} + +void config_object::g_set_data_int32(const GUID & p_guid,t_int32 p_val) { + service_ptr_t ptr; + if (!g_find(ptr,p_guid)) throw exception_service_not_found(); + ptr->set_data_int32(p_val); +} + +bool config_object::g_get_data_bool_simple(const GUID & p_guid,bool p_default) +{ + service_ptr_t ptr; + if (!g_find(ptr,p_guid)) throw exception_service_not_found(); + return ptr->get_data_bool_simple(p_default); +} + +t_int32 config_object::g_get_data_int32_simple(const GUID & p_guid,t_int32 p_default) +{ + service_ptr_t ptr; + if (!g_find(ptr,p_guid)) throw exception_service_not_found(); + return ptr->get_data_int32_simple(p_default); +} + +void config_object::get_data_bool(bool & p_out) {get_data_struct_t(p_out);} +void config_object::set_data_bool(bool p_val) {set_data_struct_t(p_val);} + +void config_object::g_get_data_bool(const GUID & p_guid,bool & p_out) {g_get_data_struct_t(p_guid,p_out);} +void config_object::g_set_data_bool(const GUID & p_guid,bool p_val) {g_set_data_struct_t(p_guid,p_val);} + +namespace { + class stream_writer_string : public stream_writer { + public: + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + m_out.add_string((const char*)p_buffer,p_bytes); + } + stream_writer_string(pfc::string_base & p_out) : m_out(p_out) {m_out.reset();} + private: + pfc::string_base & m_out; + }; + + class stream_writer_fixedbuffer : public stream_writer { + public: + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + if (p_bytes > 0) { + if (p_bytes > m_bytes - m_bytes_read) throw pfc::exception_overflow(); + memcpy((t_uint8*)m_out,p_buffer,p_bytes); + m_bytes_read += p_bytes; + } + } + stream_writer_fixedbuffer(void * p_out,t_size p_bytes,t_size & p_bytes_read) : m_out(p_out), m_bytes(p_bytes), m_bytes_read(p_bytes_read) {m_bytes_read = 0;} + private: + void * m_out; + t_size m_bytes; + t_size & m_bytes_read; + }; + + + + class stream_writer_get_length : public stream_writer { + public: + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + m_length += p_bytes; + } + stream_writer_get_length(t_size & p_length) : m_length(p_length) {m_length = 0;} + private: + t_size & m_length; + }; +}; + +t_size config_object::get_data_raw(void * p_out,t_size p_bytes) { + t_size ret = 0; + stream_writer_fixedbuffer stream(p_out,p_bytes,ret); + abort_callback_dummy aborter; + get_data(&stream,aborter); + return ret; +} + +t_size config_object::get_data_raw_length() { + t_size ret = 0; + stream_writer_get_length stream(ret); + abort_callback_dummy aborter; + get_data(&stream,aborter); + return ret; +} + +void config_object::set_data_raw(const void * p_data,t_size p_bytes, bool p_notify) { + stream_reader_memblock_ref stream(p_data,p_bytes); + abort_callback_dummy aborter; + set_data(&stream,aborter,p_notify); +} + +void config_object::set_data_string(const char * p_data,t_size p_length) { + set_data_raw(p_data,pfc::strlen_max(p_data,p_length)); +} + +void config_object::get_data_string(pfc::string_base & p_out) { + stream_writer_string stream(p_out); + abort_callback_dummy aborter; + get_data(&stream,aborter); +} + + +//config_object_impl stuff + + +void config_object_impl::get_data(stream_writer * p_stream,abort_callback & p_abort) const { + insync(m_sync); + p_stream->write_object(m_data.get_ptr(),m_data.get_size(),p_abort); +} + +void config_object_impl::set_data(stream_reader * p_stream,abort_callback & p_abort,bool p_notify) { + core_api::ensure_main_thread(); + + { + insync(m_sync); + m_data.set_size(0); + enum {delta = 1024}; + t_uint8 buffer[delta]; + for(;;) + { + t_size delta_done = p_stream->read(buffer,delta,p_abort); + + if (delta_done > 0) + { + m_data.append_fromptr(buffer,delta_done); + } + + if (delta_done != delta) break; + } + } + + if (p_notify) config_object_notify_manager::g_on_changed(this); +} + +config_object_impl::config_object_impl(const GUID & p_guid,const void * p_data,t_size p_bytes) : cfg_var(p_guid) +{ + m_data.set_data_fromptr((const t_uint8*)p_data,p_bytes); +} diff --git a/SDK/foobar2000/SDK/config_object.h b/SDK/foobar2000/SDK/config_object.h new file mode 100644 index 0000000..f1733c9 --- /dev/null +++ b/SDK/foobar2000/SDK/config_object.h @@ -0,0 +1,85 @@ +#ifndef _CONFIG_OBJECT_H_ +#define _CONFIG_OBJECT_H_ + +class config_object; + +class NOVTABLE config_object_notify_manager : public service_base +{ +public: + virtual void on_changed(const service_ptr_t & p_object) = 0; + static void g_on_changed(const service_ptr_t & p_object); + + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(config_object_notify_manager); +}; + +class NOVTABLE config_object : public service_base +{ +public: + //interface + virtual GUID get_guid() const = 0; + virtual void get_data(stream_writer * p_stream,abort_callback & p_abort) const = 0; + virtual void set_data(stream_reader * p_stream,abort_callback & p_abort,bool p_sendnotify = true) = 0; + + //helpers + static bool g_find(service_ptr_t & p_out,const GUID & p_guid); + + void set_data_raw(const void * p_data,t_size p_bytes,bool p_sendnotify = true); + t_size get_data_raw(void * p_out,t_size p_bytes); + t_size get_data_raw_length(); + + template void get_data_struct_t(T& p_out); + template void set_data_struct_t(const T& p_in); + template static void g_get_data_struct_t(const GUID & p_guid,T & p_out); + template static void g_set_data_struct_t(const GUID & p_guid,const T & p_in); + + void set_data_string(const char * p_data,t_size p_length); + void get_data_string(pfc::string_base & p_out); + + void get_data_bool(bool & p_out); + void set_data_bool(bool p_val); + void get_data_int32(t_int32 & p_out); + void set_data_int32(t_int32 p_val); + bool get_data_bool_simple(bool p_default); + t_int32 get_data_int32_simple(t_int32 p_default); + + static void g_get_data_string(const GUID & p_guid,pfc::string_base & p_out); + static void g_set_data_string(const GUID & p_guid,const char * p_data,t_size p_length = ~0); + + static void g_get_data_bool(const GUID & p_guid,bool & p_out); + static void g_set_data_bool(const GUID & p_guid,bool p_val); + static void g_get_data_int32(const GUID & p_guid,t_int32 & p_out); + static void g_set_data_int32(const GUID & p_guid,t_int32 p_val); + static bool g_get_data_bool_simple(const GUID & p_guid,bool p_default); + static t_int32 g_get_data_int32_simple(const GUID & p_guid,t_int32 p_default); + + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(config_object); +}; + +class standard_config_objects +{ +public: + static const GUID bool_remember_window_positions, bool_ui_always_on_top,bool_playlist_stop_after_current; + static const GUID bool_playback_follows_cursor, bool_cursor_follows_playback; + static const GUID bool_show_keyboard_shortcuts_in_menus; + static const GUID string_gui_last_directory_media,string_gui_last_directory_playlists; + static const GUID int32_dynamic_bitrate_display_rate; + + + inline static bool query_show_keyboard_shortcuts_in_menus() {return config_object::g_get_data_bool_simple(standard_config_objects::bool_show_keyboard_shortcuts_in_menus,true);} + inline static bool query_remember_window_positions() {return config_object::g_get_data_bool_simple(standard_config_objects::bool_remember_window_positions,true);} + +}; + +class config_object_notify : public service_base +{ +public: + virtual t_size get_watched_object_count() = 0; + virtual GUID get_watched_object(t_size p_index) = 0; + virtual void on_watched_object_changed(const service_ptr_t & p_object) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(config_object_notify); +}; + +#endif // _CONFIG_OBJECT_H_ diff --git a/SDK/foobar2000/SDK/config_object_impl.h b/SDK/foobar2000/SDK/config_object_impl.h new file mode 100644 index 0000000..7aa2958 --- /dev/null +++ b/SDK/foobar2000/SDK/config_object_impl.h @@ -0,0 +1,173 @@ +#ifndef _CONFIG_OBJECT_IMPL_H_ +#define _CONFIG_OBJECT_IMPL_H_ + +//template function bodies from config_object class + +template +void config_object::get_data_struct_t(T& p_out) { + if (get_data_raw(&p_out,sizeof(T)) != sizeof(T)) throw exception_io_data_truncation(); +} + +template +void config_object::set_data_struct_t(const T& p_in) { + return set_data_raw(&p_in,sizeof(T)); +} + +template +void config_object::g_get_data_struct_t(const GUID & p_guid,T & p_out) { + service_ptr_t ptr; + if (!g_find(ptr,p_guid)) throw exception_service_not_found(); + return ptr->get_data_struct_t(p_out); +} + +template +void config_object::g_set_data_struct_t(const GUID & p_guid,const T & p_in) { + service_ptr_t ptr; + if (!g_find(ptr,p_guid)) throw exception_service_not_found(); + return ptr->set_data_struct_t(p_in); +} + + +class config_object_impl : public config_object, private cfg_var +{ +public: + GUID get_guid() const {return cfg_var::get_guid();} + void get_data(stream_writer * p_stream,abort_callback & p_abort) const ; + void set_data(stream_reader * p_stream,abort_callback & p_abort,bool p_notify); + + config_object_impl(const GUID & p_guid,const void * p_data,t_size p_bytes); +private: + + //cfg_var methods + void get_data_raw(stream_writer * p_stream,abort_callback & p_abort) {get_data(p_stream,p_abort);} + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) {set_data(p_stream,p_abort,false);} + + mutable critical_section m_sync; + pfc::array_t m_data; +}; + +typedef service_factory_single_transparent_t config_object_factory; + +template +class config_object_fixed_const_impl_t : public config_object { +public: + config_object_fixed_const_impl_t(const GUID & p_guid, const void * p_data) : m_guid(p_guid) {memcpy(m_data,p_data,p_size);} + GUID get_guid() const {return m_guid;} + + void get_data(stream_writer * p_stream, abort_callback & p_abort) const { p_stream->write_object(m_data,p_size,p_abort); } + void set_data(stream_reader * p_stream, abort_callback & p_abort, bool p_notify) { PFC_ASSERT(!"Should not get here."); } + +private: + t_uint8 m_data[p_size]; + const GUID m_guid; +}; + +template +class config_object_fixed_impl_t : public config_object, private cfg_var { +public: + GUID get_guid() const {return cfg_var::get_guid();} + + void get_data(stream_writer * p_stream,abort_callback & p_abort) const { + insync(m_sync); + p_stream->write_object(m_data,p_size,p_abort); + } + + void set_data(stream_reader * p_stream,abort_callback & p_abort,bool p_notify) { + core_api::ensure_main_thread(); + + { + t_uint8 temp[p_size]; + p_stream->read_object(temp,p_size,p_abort); + insync(m_sync); + memcpy(m_data,temp,p_size); + } + + if (p_notify) config_object_notify_manager::g_on_changed(this); + } + + config_object_fixed_impl_t (const GUID & p_guid,const void * p_data) + : cfg_var(p_guid) + { + memcpy(m_data,p_data,p_size); + } + +private: + //cfg_var methods + void get_data_raw(stream_writer * p_stream,abort_callback & p_abort) {get_data(p_stream,p_abort);} + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) {set_data(p_stream,p_abort,false);} + + mutable critical_section m_sync; + t_uint8 m_data[p_size]; + +}; + +template class _config_object_fixed_impl_switch; +template class _config_object_fixed_impl_switch { public: typedef config_object_fixed_impl_t type; }; +template class _config_object_fixed_impl_switch { public: typedef config_object_fixed_const_impl_t type; }; + +template +class config_object_fixed_factory_t : public service_factory_single_transparent_t< typename _config_object_fixed_impl_switch::type > +{ +public: + config_object_fixed_factory_t(const GUID & p_guid,const void * p_initval) + : + service_factory_single_transparent_t< typename _config_object_fixed_impl_switch::type > + (p_guid,p_initval) + {} +}; + + +class config_object_string_factory : public config_object_factory +{ +public: + config_object_string_factory(const GUID & p_guid,const char * p_string,t_size p_string_length = ~0) + : config_object_factory(p_guid,p_string,pfc::strlen_max(p_string,~0)) {} + +}; + +template +class config_object_bool_factory_t : public config_object_fixed_factory_t<1,isConst> { +public: + config_object_bool_factory_t(const GUID & p_guid,bool p_initval) + : config_object_fixed_factory_t<1,isConst>(p_guid,&p_initval) {} +}; +typedef config_object_bool_factory_t<> config_object_bool_factory; + +template +class config_object_int_factory_t : public config_object_fixed_factory_t +{ +private: + struct t_initval + { + T m_initval; + t_initval(T p_initval) : m_initval(p_initval) {byte_order::order_native_to_le_t(m_initval);} + T * get_ptr() {return &m_initval;} + }; +public: + config_object_int_factory_t(const GUID & p_guid,T p_initval) + : config_object_fixed_factory_t(p_guid,t_initval(p_initval).get_ptr() ) + {} +}; + +typedef config_object_int_factory_t config_object_int32_factory; + + + +class config_object_notify_impl_simple : public config_object_notify +{ +public: + t_size get_watched_object_count() {return 1;} + GUID get_watched_object(t_size p_index) {return m_guid;} + void on_watched_object_changed(const service_ptr_t & p_object) {m_func(p_object);} + + typedef void (*t_func)(const service_ptr_t &); + + config_object_notify_impl_simple(const GUID & p_guid,t_func p_func) : m_guid(p_guid), m_func(p_func) {} +private: + GUID m_guid; + t_func m_func; +}; + +typedef service_factory_single_transparent_t config_object_notify_simple_factory; + +#endif //_CONFIG_OBJECT_IMPL_H_ diff --git a/SDK/foobar2000/SDK/console.cpp b/SDK/foobar2000/SDK/console.cpp new file mode 100644 index 0000000..57d1431 --- /dev/null +++ b/SDK/foobar2000/SDK/console.cpp @@ -0,0 +1,50 @@ +#include "foobar2000.h" + + +void console::info(const char * p_message) {print(p_message);} +void console::error(const char * p_message) {complain("Error", p_message);} +void console::warning(const char * p_message) {complain("Warning", p_message);} + +void console::info_location(const playable_location & src) {print_location(src);} +void console::info_location(const metadb_handle_ptr & src) {print_location(src);} + +void console::print_location(const metadb_handle_ptr & src) +{ + print_location(src->get_location()); +} + +void console::print_location(const playable_location & src) +{ + FB2K_console_formatter() << src; +} + +void console::complain(const char * what, const char * msg) { + FB2K_console_formatter() << what << ": " << msg; +} +void console::complain(const char * what, std::exception const & e) { + complain(what, e.what()); +} + +void console::print(const char* p_message) +{ + if (core_api::are_services_available()) { + service_ptr_t ptr; + service_enum_t e; + while(e.next(ptr)) ptr->print(p_message,~0); + } +} + +void console::printf(const char* p_format,...) +{ + va_list list; + va_start(list,p_format); + printfv(p_format,list); + va_end(list); +} + +void console::printfv(const char* p_format,va_list p_arglist) +{ + pfc::string8_fastalloc temp; + uPrintfV(temp,p_format,p_arglist); + print(temp); +} \ No newline at end of file diff --git a/SDK/foobar2000/SDK/console.h b/SDK/foobar2000/SDK/console.h new file mode 100644 index 0000000..286e2d4 --- /dev/null +++ b/SDK/foobar2000/SDK/console.h @@ -0,0 +1,46 @@ +//! Namespace with functions for sending text to console. All functions are fully multi-thread safe, though they must not be called during dll initialization or deinitialization (e.g. static object constructors or destructors) when service system is not available. +namespace console +{ + void info(const char * p_message); + void error(const char * p_message); + void warning(const char * p_message); + void info_location(const playable_location & src); + void info_location(const metadb_handle_ptr & src); + void print_location(const playable_location & src); + void print_location(const metadb_handle_ptr & src); + + void print(const char*); + void printf(const char*,...); + void printfv(const char*,va_list p_arglist); + + //! Usage: console::formatter() << "blah " << somenumber << " asdf" << somestring; + class formatter : public pfc::string_formatter { + public: + ~formatter() {if (!is_empty()) console::print(get_ptr());} + }; +#define FB2K_console_formatter() ::console::formatter()._formatter() + + void complain(const char * what, const char * msg); + void complain(const char * what, std::exception const & e); + + class timer_scope { + public: + timer_scope(const char * name) : m_name(name) {m_timer.start();} + ~timer_scope() { + try { + FB2K_console_formatter() << m_name << ": " << pfc::format_time_ex(m_timer.query(), 6); + } catch(...) {} + } + private: + pfc::hires_timer m_timer; + const char * const m_name; + }; +}; + +//! Interface receiving console output. Do not call directly; use console namespace functions instead. +class NOVTABLE console_receiver : public service_base { +public: + virtual void print(const char * p_message,t_size p_message_length) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(console_receiver); +}; diff --git a/SDK/foobar2000/SDK/contextmenu.h b/SDK/foobar2000/SDK/contextmenu.h new file mode 100644 index 0000000..bff8b3e --- /dev/null +++ b/SDK/foobar2000/SDK/contextmenu.h @@ -0,0 +1,337 @@ +//! Reserved for future use. +typedef void * t_glyph; + + +class NOVTABLE contextmenu_item_node { +public: + enum t_flags { + FLAG_CHECKED = 1, + FLAG_DISABLED = 2, + FLAG_GRAYED = 4, + FLAG_DISABLED_GRAYED = FLAG_DISABLED|FLAG_GRAYED, + FLAG_RADIOCHECKED = 8, //new in 0.9.5.2 - overrides FLAG_CHECKED, set together with FLAG_CHECKED for backwards compatibility. + }; + + enum t_type { + type_group, + type_command, + type_separator, + + //for compatibility + TYPE_POPUP = type_group,TYPE_COMMAND = type_command,TYPE_SEPARATOR = type_separator, + }; + + virtual bool get_display_data(pfc::string_base & p_out,unsigned & p_displayflags,metadb_handle_list_cref p_data,const GUID & p_caller) = 0; + virtual t_type get_type() = 0; + virtual void execute(metadb_handle_list_cref p_data,const GUID & p_caller) = 0; + virtual t_glyph get_glyph(metadb_handle_list_cref p_data,const GUID & p_caller) {return 0;}//RESERVED + virtual t_size get_children_count() = 0; + virtual contextmenu_item_node * get_child(t_size p_index) = 0; + virtual bool get_description(pfc::string_base & p_out) = 0; + virtual GUID get_guid() = 0; + virtual bool is_mappable_shortcut() = 0; + +protected: + contextmenu_item_node() {} + ~contextmenu_item_node() {} +}; + +class NOVTABLE contextmenu_item_node_root : public contextmenu_item_node +{ +public: + virtual ~contextmenu_item_node_root() {} +}; + +class NOVTABLE contextmenu_item_node_leaf : public contextmenu_item_node +{ +public: + t_type get_type() {return TYPE_COMMAND;} + t_size get_children_count() {return 0;} + contextmenu_item_node * get_child(t_size) {return NULL;} +}; + +class NOVTABLE contextmenu_item_node_root_leaf : public contextmenu_item_node_root +{ +public: + t_type get_type() {return TYPE_COMMAND;} + t_size get_children_count() {return 0;} + contextmenu_item_node * get_child(t_size) {return NULL;} +}; + +class NOVTABLE contextmenu_item_node_popup : public contextmenu_item_node +{ +public: + t_type get_type() {return TYPE_POPUP;} + void execute(metadb_handle_list_cref data,const GUID & caller) {} + bool get_description(pfc::string_base & p_out) {return false;} +}; + +class NOVTABLE contextmenu_item_node_root_popup : public contextmenu_item_node_root +{ +public: + t_type get_type() {return TYPE_POPUP;} + void execute(metadb_handle_list_cref data,const GUID & caller) {} + bool get_description(pfc::string_base & p_out) {return false;} +}; + +class contextmenu_item_node_separator : public contextmenu_item_node +{ +public: + t_type get_type() {return TYPE_SEPARATOR;} + void execute(metadb_handle_list_cref data,const GUID & caller) {} + bool get_description(pfc::string_base & p_out) {return false;} + t_size get_children_count() {return 0;} + bool get_display_data(pfc::string_base & p_out,unsigned & p_displayflags,metadb_handle_list_cref p_data,const GUID & p_caller) + { + p_displayflags = 0; + p_out = "---"; + return true; + } + contextmenu_item_node * get_child(t_size) {return NULL;} + GUID get_guid() {return pfc::guid_null;} + bool is_mappable_shortcut() {return false;} +}; + +/*! +Service class for declaring context menu commands.\n +See contextmenu_item_simple for implementation helper without dynamic menu generation features.\n +All methods are valid from main app thread only. +*/ +class NOVTABLE contextmenu_item : public service_base { +public: + enum t_enabled_state { + FORCE_OFF, + DEFAULT_OFF, + DEFAULT_ON, + }; + + //! Retrieves number of menu items provided by this contextmenu_item implementation. + virtual unsigned get_num_items() = 0; + //! Instantiates a context menu item (including sub-node tree for items that contain dynamically-generated sub-items). + virtual contextmenu_item_node_root * instantiate_item(unsigned p_index,metadb_handle_list_cref p_data,const GUID & p_caller) = 0; + //! Retrieves GUID of the context menu item. + virtual GUID get_item_guid(unsigned p_index) = 0; + //! Retrieves human-readable name of the context menu item. + virtual void get_item_name(unsigned p_index,pfc::string_base & p_out) = 0; + //! Obsolete since v1.0, don't use or override in new components. + virtual void get_item_default_path(unsigned p_index,pfc::string_base & p_out) {p_out = "";} + //! Retrieves item's description to show in the status bar. Set p_out to the string to be displayed and return true if you provide a description, return false otherwise. + virtual bool get_item_description(unsigned p_index,pfc::string_base & p_out) = 0; + //! Controls default state of context menu preferences for this item: \n + //! Return DEFAULT_ON to show this item in the context menu by default - useful for most cases. \n + //! Return DEFAULT_OFF to hide this item in the context menu by default - useful for rarely used utility commands. \n + //! Return FORCE_OFF to hide this item by default and prevent the user from making it visible (very rarely used). \n + //! Values returned by this method should be constant for this context menu item and not change later. Do not use this to conditionally hide the item - return false from get_display_data() instead. + virtual t_enabled_state get_enabled_state(unsigned p_index) = 0; + //! Executes the menu item command without going thru the instantiate_item path. For items with dynamically-generated sub-items, p_node is identifies of the sub-item command to execute. + virtual void item_execute_simple(unsigned p_index,const GUID & p_node,metadb_handle_list_cref p_data,const GUID & p_caller) = 0; + + bool item_get_display_data_root(pfc::string_base & p_out,unsigned & displayflags,unsigned p_index,metadb_handle_list_cref p_data,const GUID & p_caller); + bool item_get_display_data(pfc::string_base & p_out,unsigned & displayflags,unsigned p_index,const GUID & p_node,metadb_handle_list_cref p_data,const GUID & p_caller); + + GUID get_parent_fallback(); + GUID get_parent_(); + + //! Deprecated - use caller_active_playlist_selection instead. + static const GUID caller_playlist; + + static const GUID caller_active_playlist_selection, caller_active_playlist, caller_playlist_manager, caller_now_playing, caller_keyboard_shortcut_list, caller_media_library_viewer; + static const GUID caller_undefined; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(contextmenu_item); +}; + +//! \since 1.0 +class NOVTABLE contextmenu_item_v2 : public contextmenu_item { + FB2K_MAKE_SERVICE_INTERFACE(contextmenu_item_v2, contextmenu_item) +public: + virtual double get_sort_priority() {return 0;} + virtual GUID get_parent() {return get_parent_fallback();} +}; + +//! contextmenu_item implementation helper for implementing non-dynamically-generated context menu items; derive from this instead of from contextmenu_item directly if your menu items are static. +class NOVTABLE contextmenu_item_simple : public contextmenu_item_v2 { +private: +public: + //! Same as contextmenu_item_node::t_flags. + enum t_flags + { + FLAG_CHECKED = 1, + FLAG_DISABLED = 2, + FLAG_GRAYED = 4, + FLAG_DISABLED_GRAYED = FLAG_DISABLED|FLAG_GRAYED, + FLAG_RADIOCHECKED = 8, //new in 0.9.5.2 - overrides FLAG_CHECKED, set together with FLAG_CHECKED for backwards compatibility. + }; + + + // Functions to be overridden by implementers (some are not mandatory). + virtual t_enabled_state get_enabled_state(unsigned p_index) {return contextmenu_item::DEFAULT_ON;} + virtual unsigned get_num_items() = 0; + virtual void get_item_name(unsigned p_index,pfc::string_base & p_out) = 0; + virtual void context_command(unsigned p_index,metadb_handle_list_cref p_data,const GUID& p_caller) = 0; + virtual bool context_get_display(unsigned p_index,metadb_handle_list_cref p_data,pfc::string_base & p_out,unsigned & p_displayflags,const GUID & p_caller) { + PFC_ASSERT(p_index>=0 && p_indexget_display_data(m_index,p_data,p_out,p_displayflags,p_caller);} + void execute(metadb_handle_list_cref p_data,const GUID & p_caller) {m_owner->context_command(m_index,p_data,p_caller);} + bool get_description(pfc::string_base & p_out) {return m_owner->get_item_description(m_index,p_out);} + GUID get_guid() {return pfc::guid_null;} + bool is_mappable_shortcut() {return m_owner->item_is_mappable_shortcut(m_index);} + private: + service_ptr_t m_owner; + unsigned m_index; + }; + + contextmenu_item_node_root * instantiate_item(unsigned p_index,metadb_handle_list_cref p_data,const GUID & p_caller) + { + return new contextmenu_item_node_impl(this,p_index); + } + + + void item_execute_simple(unsigned p_index,const GUID & p_node,metadb_handle_list_cref p_data,const GUID & p_caller) + { + if (p_node == pfc::guid_null) + context_command(p_index,p_data,p_caller); + } + + virtual bool item_is_mappable_shortcut(unsigned p_index) + { + return true; + } + + + virtual bool get_display_data(unsigned n,metadb_handle_list_cref data,pfc::string_base & p_out,unsigned & displayflags,const GUID & caller) + { + bool rv = false; + assert(n>=0 && n0) + { + rv = context_get_display(n,data,p_out,displayflags,caller); + } + return rv; + } + +}; + + +//! Helper. +template +class contextmenu_item_factory_t : public service_factory_single_t {}; + + +//! Helper. +#define DECLARE_CONTEXT_MENU_ITEM(P_CLASSNAME,P_NAME,P_DEFAULTPATH,P_FUNC,P_GUID,P_DESCRIPTION) \ + namespace { \ + class P_CLASSNAME : public contextmenu_item_simple { \ + public: \ + unsigned get_num_items() {return 1;} \ + void get_item_name(unsigned p_index,pfc::string_base & p_out) {p_out = P_NAME;} \ + void get_item_default_path(unsigned p_index,pfc::string_base & p_out) {p_out = P_DEFAULTPATH;} \ + void context_command(unsigned p_index,metadb_handle_list_cref p_data,const GUID& p_caller) {P_FUNC(p_data);} \ + GUID get_item_guid(unsigned p_index) {return P_GUID;} \ + bool get_item_description(unsigned p_index,pfc::string_base & p_out) {if (P_DESCRIPTION[0] == 0) return false;p_out = P_DESCRIPTION; return true;} \ + }; \ + static contextmenu_item_factory_t g_##P_CLASSNAME##_factory; \ + } + + + + +//! New in 0.9.5.1. Static methods safe to use in prior versions as it will use slow fallback mode when the service isn't present. \n +//! Functionality provided by menu_item_resolver methods isn't much different from just walking all registered contextmenu_item / mainmenu_commands implementations to find the command we want, but it uses a hint map to locate the service we're looking for without walking all of them which may be significantly faster in certain scenarios. +class menu_item_resolver : public service_base { +public: + virtual bool resolve_context_command(const GUID & id, service_ptr_t & out, t_uint32 & out_index) = 0; + virtual bool resolve_main_command(const GUID & id, service_ptr_t & out, t_uint32 & out_index) = 0; + + static bool g_resolve_context_command(const GUID & id, service_ptr_t & out, t_uint32 & out_index); + static bool g_resolve_main_command(const GUID & id, service_ptr_t & out, t_uint32 & out_index); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(menu_item_resolver) +}; + +//! \since 1.0 +class NOVTABLE contextmenu_group : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(contextmenu_group); +public: + virtual GUID get_guid() = 0; + virtual GUID get_parent() = 0; + virtual double get_sort_priority() = 0; +}; + +//! \since 1.0 +class NOVTABLE contextmenu_group_popup : public contextmenu_group { + FB2K_MAKE_SERVICE_INTERFACE(contextmenu_group_popup, contextmenu_group) +public: + virtual void get_display_string(pfc::string_base & out) = 0; + void get_name(pfc::string_base & out) {get_display_string(out);} +}; + +class contextmenu_groups { +public: + static const GUID root, utilities, tagging, tagging_pictures, replaygain, fileoperations, playbackstatistics, properties, convert, legacy; +}; + +class contextmenu_group_impl : public contextmenu_group { +public: + contextmenu_group_impl(const GUID & guid, const GUID & parent, double sortPriority = 0) : m_guid(guid), m_parent(parent), m_sortPriority(sortPriority) {} + GUID get_guid() {return m_guid;} + GUID get_parent() {return m_parent;} + double get_sort_priority() {return m_sortPriority;} +private: + const GUID m_guid, m_parent; + const double m_sortPriority; +}; + +class contextmenu_group_popup_impl : public contextmenu_group_popup { +public: + contextmenu_group_popup_impl(const GUID & guid, const GUID & parent, const char * name, double sortPriority = 0) : m_guid(guid), m_parent(parent), m_sortPriority(sortPriority), m_name(name) {} + GUID get_guid() {return m_guid;} + GUID get_parent() {return m_parent;} + double get_sort_priority() {return m_sortPriority;} + void get_display_string(pfc::string_base & out) {out = m_name;} +private: + const GUID m_guid, m_parent; + const double m_sortPriority; + const char * const m_name; +}; + + + +namespace contextmenu_priorities { + enum { + root_queue = -100, + root_main = -50, + root_tagging, + root_fileoperations, + root_convert, + root_utilities, + root_replaygain, + root_playbackstatistics, + root_legacy = 99, + root_properties = 100, + tagging_pictures = 100, + }; +}; + + + +class contextmenu_group_factory : public service_factory_single_t { +public: + contextmenu_group_factory(const GUID & guid, const GUID & parent, double sortPriority = 0) : service_factory_single_t(guid, parent, sortPriority) {} +}; + +class contextmenu_group_popup_factory : public service_factory_single_t { +public: + contextmenu_group_popup_factory(const GUID & guid, const GUID & parent, const char * name, double sortPriority = 0) : service_factory_single_t(guid, parent, name, sortPriority) {} +}; diff --git a/SDK/foobar2000/SDK/contextmenu_manager.h b/SDK/foobar2000/SDK/contextmenu_manager.h new file mode 100644 index 0000000..2683633 --- /dev/null +++ b/SDK/foobar2000/SDK/contextmenu_manager.h @@ -0,0 +1,128 @@ +class NOVTABLE keyboard_shortcut_manager : public service_base +{ +public: + static bool g_get(service_ptr_t & p_out) {return service_enum_create_t(p_out,0);} + + enum shortcut_type + { + TYPE_MAIN, + TYPE_CONTEXT, + TYPE_CONTEXT_PLAYLIST, + TYPE_CONTEXT_NOW_PLAYING, + }; + + + virtual bool process_keydown(shortcut_type type,const pfc::list_base_const_t & data,unsigned keycode)=0; + virtual bool process_keydown_ex(shortcut_type type,const pfc::list_base_const_t & data,unsigned keycode,const GUID & caller)=0; + bool on_keydown(shortcut_type type,WPARAM wp); + bool on_keydown_context(const pfc::list_base_const_t & data,WPARAM wp,const GUID & caller); + + bool on_keydown_auto(WPARAM wp); + bool on_keydown_auto_playlist(WPARAM wp); + bool on_keydown_auto_context(const pfc::list_base_const_t & data,WPARAM wp,const GUID & caller); + + bool on_keydown_restricted_auto(WPARAM wp); + bool on_keydown_restricted_auto_playlist(WPARAM wp); + bool on_keydown_restricted_auto_context(const pfc::list_base_const_t & data,WPARAM wp,const GUID & caller); + + virtual bool get_key_description_for_action(const GUID & p_command,const GUID & p_subcommand, pfc::string_base & out, shortcut_type type, bool is_global)=0; + + static bool is_text_key(t_uint32 vkCode); + static bool is_typing_key(t_uint32 vkCode); + static bool is_typing_key_combo(t_uint32 vkCode, t_uint32 modifiers); + static bool is_typing_modifier(t_uint32 flags); + static bool is_typing_message(HWND editbox, const MSG * msg); + static bool is_typing_message(const MSG * msg); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(keyboard_shortcut_manager); +}; + + +//! New in 0.9.5. +class keyboard_shortcut_manager_v2 : public keyboard_shortcut_manager { +public: + //! Deprecates old keyboard_shortcut_manager methods. If the action requires selected items, they're obtained from ui_selection_manager API automatically. + virtual bool process_keydown_simple(t_uint32 keycode) = 0; + + //! Helper for use with message filters. + bool pretranslate_message(const MSG * msg, HWND thisPopupWnd); + + FB2K_MAKE_SERVICE_INTERFACE(keyboard_shortcut_manager_v2,keyboard_shortcut_manager); +}; + +class NOVTABLE contextmenu_node { +public: + virtual contextmenu_item_node::t_type get_type()=0; + virtual const char * get_name()=0; + virtual t_size get_num_children()=0;//TYPE_POPUP only + virtual contextmenu_node * get_child(t_size n)=0;//TYPE_POPUP only + virtual unsigned get_display_flags()=0;//TYPE_COMMAND/TYPE_POPUP only, see contextmenu_item::FLAG_* + virtual unsigned get_id()=0;//TYPE_COMMAND only, returns zero-based index (helpful for win32 menu command ids) + virtual void execute()=0;//TYPE_COMMAND only + virtual bool get_description(pfc::string_base & out)=0;//TYPE_COMMAND only + virtual bool get_full_name(pfc::string_base & out)=0;//TYPE_COMMAND only + virtual void * get_glyph()=0;//RESERVED, do not use +protected: + contextmenu_node() {} + ~contextmenu_node() {} +}; + + + +class NOVTABLE contextmenu_manager : public service_base +{ +public: + enum + { + flag_show_shortcuts = 1 << 0, + flag_show_shortcuts_global = 1 << 1, + //! \since 1.0 + //! To control which commands are shown, you should specify either flag_view_reduced or flag_view_full. If neither is specified, the implementation will decide automatically based on shift key being pressed, for backwards compatibility. + flag_view_reduced = 1 << 2, + //! \since 1.0 + //! To control which commands are shown, you should specify either flag_view_reduced or flag_view_full. If neither is specified, the implementation will decide automatically based on shift key being pressed, for backwards compatibility. + flag_view_full = 1 << 3, + + //for compatibility + FLAG_SHOW_SHORTCUTS = 1, + FLAG_SHOW_SHORTCUTS_GLOBAL = 2, + }; + + virtual void init_context(metadb_handle_list_cref data,unsigned flags) = 0; + virtual void init_context_playlist(unsigned flags) = 0; + virtual contextmenu_node * get_root() = 0;//releasing contextmenu_manager service releaases nodes; root may be null in case of error or something + virtual contextmenu_node * find_by_id(unsigned id)=0; + virtual void set_shortcut_preference(const keyboard_shortcut_manager::shortcut_type * data,unsigned count)=0; + + + + static void g_create(service_ptr_t & p_out) {standard_api_create_t(p_out);} + +#ifdef WIN32 + static void win32_build_menu(HMENU menu,contextmenu_node * parent,int base_id,int max_id);//menu item identifiers are base_id<=N in fb2k profile folder. + inline pfc::string8 pathInProfile(const char * fileName) { pfc::string8 p( core_api::get_profile_path() ); p.add_filename( fileName ); return std::move(p); } + + //! Returns whether foobar2000 has been installed in "portable" mode. + bool is_portable_mode_enabled(); + + //! Returns whether foobar2000 is currently running in quiet mode. \n + //! Quiet mode bypasses all GUI features, disables Media Library and does not save any changes to app configuration. \n + //! Your component should not display any forms of user interface when running in quiet mode, as well as avoid saving configuration on its own (no need to worry if you only rely on cfg_vars or config_io_callback, they will simply be ignored on shutdown). + bool is_quiet_mode_enabled(); +}; + +#endif diff --git a/SDK/foobar2000/SDK/coreversion.h b/SDK/foobar2000/SDK/coreversion.h new file mode 100644 index 0000000..3cfb421 --- /dev/null +++ b/SDK/foobar2000/SDK/coreversion.h @@ -0,0 +1,36 @@ +class NOVTABLE core_version_info : public service_base { +public: + virtual const char * get_version_string() = 0; + static const char * g_get_version_string() {return static_api_ptr_t()->get_version_string();} + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(core_version_info); +}; + +struct t_core_version_data { + t_uint32 m_major, m_minor1, m_minor2, m_minor3; +}; + +//! New (0.9.4.2) +class NOVTABLE core_version_info_v2 : public core_version_info { +public: + virtual const char * get_name() = 0;//"foobar2000" + virtual const char * get_version_as_text() = 0;//"N.N.N.N" + virtual t_core_version_data get_version() = 0; + + //! Determine whether running foobar2000 version is newer or equal to the specified version, eg. test_version(0,9,5,0) for 0.9.5. + bool test_version(t_uint32 major, t_uint32 minor1, t_uint32 minor2, t_uint32 minor3) { + const t_core_version_data v = get_version(); + if (v.m_major < major) return false; + else if (v.m_major > major) return true; + // major version matches + else if (v.m_minor1 < minor1) return false; + else if (v.m_minor1 > minor1) return true; + // minor1 version matches + else if (v.m_minor2 < minor2) return false; + else if (v.m_minor2 > minor2) return true; + // minor2 version matches + else if (v.m_minor3 < minor3) return false; + else return true; + } + + FB2K_MAKE_SERVICE_INTERFACE(core_version_info_v2, core_version_info); +}; diff --git a/SDK/foobar2000/SDK/decode_postprocessor.h b/SDK/foobar2000/SDK/decode_postprocessor.h new file mode 100644 index 0000000..2e34d54 --- /dev/null +++ b/SDK/foobar2000/SDK/decode_postprocessor.h @@ -0,0 +1,161 @@ +//! \since 1.1 +//! This service is essentially a special workaround to easily decode DTS/HDCD content stored in files pretending to contain plain PCM data. \n +//! Callers: Instead of calling this directly, you probably want to use input_postprocessed template. \n +//! Implementers: This service is called only by specific decoders, not by all of them! Implementing your own to provide additional functionality is not recommended! +class decode_postprocessor_instance : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(decode_postprocessor_instance, service_base); +public: + enum { + //! End of stream. Flush any buffered data during this call. + flag_eof = 1 << 0, + //! Stream has already been altered by another instance. + flag_altered = 1 << 1, + }; + //! @returns True if the chunk list has been altered by the call, false if not - to tell possible other running instances whether the stream has already been altered or not. + virtual bool run(dsp_chunk_list & p_chunk_list,t_uint32 p_flags,abort_callback & p_abort) = 0; + virtual bool get_dynamic_info(file_info & p_out) = 0; + virtual void flush() = 0; + virtual double get_buffer_ahead() = 0; +}; + +//! \since 1.1 +//! Entrypoint class for instantiating decode_postprocessor_instance. See decode_postprocessor_instance documentation for more information. \n +//! Instead of calling this directly, you probably want to use input_postprocessed template. +class decode_postprocessor_entry : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(decode_postprocessor_entry) +public: + virtual bool instantiate(const file_info & info, decode_postprocessor_instance::ptr & out) = 0; +}; + + +//! Helper class for managing decode_postprocessor_instance objects. See also: input_postprocessed. +class decode_postprocessor { +public: + typedef decode_postprocessor_instance::ptr item; + void initialize(const file_info & info) { + m_items.remove_all(); + service_enum_t e; + decode_postprocessor_entry::ptr ptr; + while(e.next(ptr)) { + item i; + if (ptr->instantiate(info, i)) m_items += i; + } + } + void run(dsp_chunk_list & p_chunk_list,bool p_eof,abort_callback & p_abort) { + t_uint32 flags = p_eof ? decode_postprocessor_instance::flag_eof : 0; + for(t_size walk = 0; walk < m_items.get_size(); ++walk) { + if (m_items[walk]->run(p_chunk_list, flags, p_abort)) flags |= decode_postprocessor_instance::flag_altered; + } + } + void flush() { + for(t_size walk = 0; walk < m_items.get_size(); ++walk) { + m_items[walk]->flush(); + } + } + static bool should_bother() { + return service_factory_base::is_service_present(decode_postprocessor_entry::class_guid); + } + bool is_active() const { + return m_items.get_size() > 0; + } + bool get_dynamic_info(file_info & p_out) { + bool rv = false; + for(t_size walk = 0; walk < m_items.get_size(); ++walk) { + if (m_items[walk]->get_dynamic_info(p_out)) rv = true; + } + return rv; + } + void close() { + m_items.remove_all(); + } + double get_buffer_ahead() { + double acc = 0; + for(t_size walk = 0; walk < m_items.get_size(); ++walk) { + pfc::max_acc(acc, m_items[walk]->get_buffer_ahead()); + } + return acc; + } +private: + pfc::list_t m_items; +}; + +//! Generic template to add decode_postprocessor support to your input class. Works with both single-track and multi-track inputs. +template class input_postprocessed : public baseclass { +public: + void decode_initialize(t_uint32 p_subsong,unsigned p_flags,abort_callback & p_abort) { + m_chunks.remove_all(); + m_haveEOF = false; + m_toSkip = 0; + m_postproc.close(); + if ((p_flags & input_flag_no_postproc) == 0 && m_postproc.should_bother()) { + file_info_impl info; + this->get_info(p_subsong, info, p_abort); + m_postproc.initialize(info); + } + baseclass::decode_initialize(p_subsong, p_flags, p_abort); + } + void decode_initialize(unsigned p_flags,abort_callback & p_abort) { + m_chunks.remove_all(); + m_haveEOF = false; + m_toSkip = 0; + m_postproc.close(); + if ((p_flags & input_flag_no_postproc) == 0 && m_postproc.should_bother()) { + file_info_impl info; + this->get_info(info, p_abort); + m_postproc.initialize(info); + } + baseclass::decode_initialize(p_flags, p_abort); + } + bool decode_run(audio_chunk & p_chunk,abort_callback & p_abort) { + if (m_postproc.is_active()) { + for(;;) { + p_abort.check(); + if (m_chunks.get_count() > 0) { + audio_chunk * c = m_chunks.get_item(0); + if (m_toSkip > 0) { + if (!c->process_skip(m_toSkip)) { + m_chunks.remove_by_idx(0); + continue; + } + } + p_chunk = *c; + m_chunks.remove_by_idx(0); + return true; + } + if (m_haveEOF) return false; + if (!baseclass::decode_run(*m_chunks.insert_item(0), p_abort)) { + m_haveEOF = true; + m_chunks.remove_by_idx(0); + } + m_postproc.run(m_chunks, m_haveEOF, p_abort); + } + } else { + return baseclass::decode_run(p_chunk, p_abort); + } + } + bool decode_run_raw(audio_chunk & p_chunk, mem_block_container & p_raw, abort_callback & p_abort) { + if (m_postproc.is_active()) { + throw pfc::exception_not_implemented(); + } else { + return baseclass::decode_run_raw(p_chunk, p_raw, p_abort); + } + } + bool decode_get_dynamic_info(file_info & p_out, double & p_timestamp_delta) { + bool rv = baseclass::decode_get_dynamic_info(p_out, p_timestamp_delta); + if (m_postproc.get_dynamic_info(p_out)) rv = true; + return rv; + } + void decode_seek(double p_seconds,abort_callback & p_abort) { + m_chunks.remove_all(); + m_haveEOF = false; + m_postproc.flush(); + double target = pfc::max_t(0, p_seconds - m_postproc.get_buffer_ahead()); + m_toSkip = p_seconds - target; + baseclass::decode_seek(target, p_abort); + } +private: + dsp_chunk_list_impl m_chunks; + bool m_haveEOF; + double m_toSkip; + decode_postprocessor m_postproc; +}; diff --git a/SDK/foobar2000/SDK/dsp.cpp b/SDK/foobar2000/SDK/dsp.cpp new file mode 100644 index 0000000..e0424e5 --- /dev/null +++ b/SDK/foobar2000/SDK/dsp.cpp @@ -0,0 +1,406 @@ +#include "foobar2000.h" +#include + +t_size dsp_chunk_list_impl::get_count() const {return m_data.get_count();} + +audio_chunk * dsp_chunk_list_impl::get_item(t_size n) const {return nmax) idx = max; + pfc::rcptr_t ret; + if (m_recycled.get_count()>0) + { + t_size best; + if (hint_size>0) + { + best = 0; + t_size best_found = m_recycled[0]->get_data_size(), n, total = m_recycled.get_count(); + for(n=1;nget_data_size(); + int delta_old = abs((int)best_found - (int)hint_size), delta_new = abs((int)size - (int)hint_size); + if (delta_new < delta_old) + { + best_found = size; + best = n; + } + } + } + else best = m_recycled.get_count()-1; + + ret = m_recycled.remove_by_idx(best); + ret->set_sample_count(0); + ret->set_channels(0); + ret->set_srate(0); + } + else ret = pfc::rcnew_t(); + if (idx==max) m_data.add_item(ret); + else m_data.insert_item(ret,idx); + return &*ret; +} + +void dsp_chunk_list::remove_bad_chunks() +{ + bool blah = false; + t_size idx; + for(idx=0;idxis_valid()) + { + chunk->reset(); + remove_by_idx(idx); + blah = true; + } + else idx++; + } + if (blah) console::info("one or more bad chunks removed from dsp chunk list"); +} + + +bool dsp_entry::g_instantiate(service_ptr_t & p_out,const dsp_preset & p_preset) +{ + service_ptr_t ptr; + if (!g_get_interface(ptr,p_preset.get_owner())) return false; + return ptr->instantiate(p_out,p_preset); +} + +bool dsp_entry::g_instantiate_default(service_ptr_t & p_out,const GUID & p_guid) +{ + service_ptr_t ptr; + if (!g_get_interface(ptr,p_guid)) return false; + dsp_preset_impl preset; + if (!ptr->get_default_preset(preset)) return false; + return ptr->instantiate(p_out,preset); +} + +bool dsp_entry::g_name_from_guid(pfc::string_base & p_out,const GUID & p_guid) +{ + service_ptr_t ptr; + if (!g_get_interface(ptr,p_guid)) return false; + ptr->get_name(p_out); + return true; +} + +bool dsp_entry::g_dsp_exists(const GUID & p_guid) +{ + service_ptr_t blah; + return g_get_interface(blah,p_guid); +} + +bool dsp_entry::g_get_default_preset(dsp_preset & p_out,const GUID & p_guid) +{ + service_ptr_t ptr; + if (!g_get_interface(ptr,p_guid)) return false; + return ptr->get_default_preset(p_out); +} + +void dsp_chain_config::contents_to_stream(stream_writer * p_stream,abort_callback & p_abort) const { + t_size n, count = get_count(); + p_stream->write_lendian_t(count,p_abort); + for(n=0;nread_lendian_t(count,p_abort); + + dsp_preset_impl temp; + + for(n=0;n & p_out) +{ + p_out.remove_all(); + t_size n, m = get_count(); + for(n=0;n temp; + if (dsp_entry::g_instantiate(temp,get_item(n))) + p_out.add_item(temp); + } +} + +t_size dsp_chain_config_impl::get_count() const +{ + return m_data.get_count(); +} + +const dsp_preset & dsp_chain_config_impl::get_item(t_size p_index) const +{ + return *m_data[p_index]; +} + +void dsp_chain_config_impl::replace_item(const dsp_preset & p_data,t_size p_index) +{ + *m_data[p_index] = p_data; +} + +void dsp_chain_config_impl::insert_item(const dsp_preset & p_data,t_size p_index) +{ + m_data.insert_item(new dsp_preset_impl(p_data),p_index); +} + +void dsp_chain_config_impl::remove_mask(const bit_array & p_mask) +{ + m_data.delete_mask(p_mask); +} + +dsp_chain_config_impl::~dsp_chain_config_impl() +{ + m_data.delete_all(); +} + +void dsp_preset::contents_to_stream(stream_writer * p_stream,abort_callback & p_abort) const { + t_size size = get_data_size(); + p_stream->write_lendian_t(get_owner(),p_abort); + p_stream->write_lendian_t(size,p_abort); + if (size > 0) { + p_stream->write_object(get_data(),size,p_abort); + } +} + +void dsp_preset::contents_from_stream(stream_reader * p_stream,abort_callback & p_abort) { + t_uint32 size; + GUID guid; + p_stream->read_lendian_t(guid,p_abort); + set_owner(guid); + p_stream->read_lendian_t(size,p_abort); + if (size > 1024*1024*32) throw exception_io_data(); + set_data_from_stream(p_stream,size,p_abort); +} + +void dsp_preset::g_contents_from_stream_skip(stream_reader * p_stream,abort_callback & p_abort) { + t_uint32 size; + GUID guid; + p_stream->read_lendian_t(guid,p_abort); + p_stream->read_lendian_t(size,p_abort); + if (size > 1024*1024*32) throw exception_io_data(); + p_stream->skip_object(size,p_abort); +} + +void dsp_preset_impl::set_data_from_stream(stream_reader * p_stream,t_size p_bytes,abort_callback & p_abort) { + m_data.set_size(p_bytes); + if (p_bytes > 0) p_stream->read_object(m_data.get_ptr(),p_bytes,p_abort); +} + +void dsp_chain_config::copy(const dsp_chain_config & p_source) { + remove_all(); + t_size n, m = p_source.get_count(); + for(n=0;n entry; + if (!g_get_interface(entry,p_guid)) return false; + return entry->have_config_popup(); +} + +bool dsp_entry::g_have_config_popup(const dsp_preset & p_preset) +{ + return g_have_config_popup(p_preset.get_owner()); +} + +bool dsp_entry::g_show_config_popup(dsp_preset & p_preset,HWND p_parent) +{ + service_ptr_t entry; + if (!g_get_interface(entry,p_preset.get_owner())) return false; + return entry->show_config_popup(p_preset,p_parent); +} + +void dsp_entry::g_show_config_popup_v2(const dsp_preset & p_preset,HWND p_parent,dsp_preset_edit_callback & p_callback) { + service_ptr_t entry; + if (g_get_interface(entry,p_preset.get_owner())) { + service_ptr_t entry_v2; + if (entry->service_query_t(entry_v2)) { + entry_v2->show_config_popup_v2(p_preset,p_parent,p_callback); + } else { + dsp_preset_impl temp(p_preset); + if (entry->show_config_popup(temp,p_parent)) p_callback.on_preset_changed(temp); + } + } +} + +bool dsp_entry::g_get_interface(service_ptr_t & p_out,const GUID & p_guid) +{ + service_ptr_t ptr; + service_enum_t e; + e.reset(); + while(e.next(ptr)) + { + if (ptr->get_guid() == p_guid) + { + p_out = ptr; + return true; + } + } + return false; +} + +bool resampler_entry::g_get_interface(service_ptr_t & p_out,unsigned p_srate_from,unsigned p_srate_to) +{ + service_ptr_t ptr_dsp; + service_ptr_t ptr_resampler; + service_enum_t e; + e.reset(); + float found_priority = 0; + service_ptr_t found; + while(e.next(ptr_dsp)) + { + if (ptr_dsp->service_query_t(ptr_resampler)) + { + if (p_srate_from == 0 || ptr_resampler->is_conversion_supported(p_srate_from,p_srate_to)) + { + float priority = ptr_resampler->get_priority(); + if (found.is_empty() || priority > found_priority) + { + found = ptr_resampler; + found_priority = priority; + } + } + } + } + if (found.is_empty()) return false; + p_out = found; + return true; +} + +bool resampler_entry::g_create_preset(dsp_preset & p_out,unsigned p_srate_from,unsigned p_srate_to,float p_qualityscale) +{ + service_ptr_t entry; + if (!g_get_interface(entry,p_srate_from,p_srate_to)) return false; + return entry->create_preset(p_out,p_srate_to,p_qualityscale); +} + +bool resampler_entry::g_create(service_ptr_t & p_out,unsigned p_srate_from,unsigned p_srate_to,float p_qualityscale) +{ + service_ptr_t entry; + if (!g_get_interface(entry,p_srate_from,p_srate_to)) return false; + dsp_preset_impl preset; + if (!entry->create_preset(preset,p_srate_to,p_qualityscale)) return false; + return entry->instantiate(p_out,preset); +} + + +bool dsp_chain_config::equals(dsp_chain_config const & v1, dsp_chain_config const & v2) { + const t_size count = v1.get_count(); + if (count != v2.get_count()) return false; + for(t_size walk = 0; walk < count; ++walk) { + if (v1.get_item(walk) != v2.get_item(walk)) return false; + } + return true; +} +void dsp_chain_config::get_name_list(pfc::string_base & p_out) const +{ + const t_size count = get_count(); + bool added = false; + for(unsigned n=0;n ptr; + if (dsp_entry::g_get_interface(ptr,get_item(n).get_owner())) + { + if (added) p_out += ", "; + added = true; + + pfc::string8 temp; + ptr->get_name(temp); + p_out += temp; + } + } +} + +void dsp::run_abortable(dsp_chunk_list * p_chunk_list,const metadb_handle_ptr & p_cur_file,int p_flags,abort_callback & p_abort) { + service_ptr_t this_v2; + if (this->service_query_t(this_v2)) this_v2->run_v2(p_chunk_list,p_cur_file,p_flags,p_abort); + else run(p_chunk_list,p_cur_file,p_flags); +} + +namespace { + class dsp_preset_edit_callback_impl : public dsp_preset_edit_callback { + public: + dsp_preset_edit_callback_impl(dsp_preset & p_data) : m_data(p_data) {} + void on_preset_changed(const dsp_preset & p_data) {m_data = p_data;} + private: + dsp_preset & m_data; + }; +}; + +bool dsp_entry_v2::show_config_popup(dsp_preset & p_data,HWND p_parent) { + PFC_ASSERT(p_data.get_owner() == get_guid()); + dsp_preset_impl temp(p_data); + + { + dsp_preset_edit_callback_impl cb(temp); + show_config_popup_v2(p_data,p_parent,cb); + } + PFC_ASSERT(temp.get_owner() == get_guid()); + if (temp == p_data) return false; + p_data = temp; + return true; +} \ No newline at end of file diff --git a/SDK/foobar2000/SDK/dsp.h b/SDK/foobar2000/SDK/dsp.h new file mode 100644 index 0000000..240dfc2 --- /dev/null +++ b/SDK/foobar2000/SDK/dsp.h @@ -0,0 +1,498 @@ +//! Interface to a DSP chunk list. A DSP chunk list object is passed to the DSP chain each time, since DSPs are allowed to remove processed chunks or insert new ones. +class NOVTABLE dsp_chunk_list { +public: + virtual t_size get_count() const = 0; + virtual audio_chunk * get_item(t_size n) const = 0; + virtual void remove_by_idx(t_size idx) = 0; + virtual void remove_mask(const bit_array & mask) = 0; + virtual audio_chunk * insert_item(t_size idx,t_size hint_size=0) = 0; + + audio_chunk * add_item(t_size hint_size=0) {return insert_item(get_count(),hint_size);} + + void remove_all() {remove_mask(bit_array_true());} + + double get_duration() { + double rv = 0; + t_size n,m = get_count(); + for(n=0;nget_duration(); + return rv; + } + + void add_chunk(const audio_chunk * chunk) { + audio_chunk * dst = insert_item(get_count(),chunk->get_used_size()); + if (dst) dst->copy(*chunk); + } + + void remove_bad_chunks(); +protected: + dsp_chunk_list() {} + ~dsp_chunk_list() {} +}; + +class dsp_chunk_list_impl : public dsp_chunk_list//implementation +{ + pfc::list_t > m_data, m_recycled; +public: + t_size get_count() const; + audio_chunk * get_item(t_size n) const; + void remove_by_idx(t_size idx); + void remove_mask(const bit_array & mask); + audio_chunk * insert_item(t_size idx,t_size hint_size=0); +}; + +//! Instance of a DSP.\n +//! Implementation: Derive from dsp_impl_base instead of deriving from dsp directly.\n +//! Instantiation: Use dsp_entry static helper methods to instantiate DSPs, or dsp_chain_config / dsp_manager to deal with entire DSP chains. +class NOVTABLE dsp : public service_base { +public: + enum { + //! Flush whatever you need to when tracks change. + END_OF_TRACK = 1, + //! Flush everything. + FLUSH = 2 + }; + + //! @param p_chunk_list List of chunks to process. The implementation may alter the list in any way, inserting chunks of different sample rate / channel configuration etc. + //! @param p_cur_file Optional, location of currently decoded file. May be null. + //! @param p_flags Flags. Can be null, or a combination of END_OF_TRACK and FLUSH constants. + virtual void run(dsp_chunk_list * p_chunk_list,const metadb_handle_ptr & p_cur_file,int p_flags)=0; + + //! Flushes the DSP (reinitializes / drops any buffered data). Called after seeking, etc. + virtual void flush() = 0; + + //! Retrieves amount of data buffered by the DSP, for syncing visualisation. + //! @returns Amount of buffered audio data, in seconds. + virtual double get_latency() = 0; + //! Returns true if DSP needs to know exact track change point (eg. for crossfading, removing silence).\n + //! Signaling this will force-flush any DSPs placed before this DSP so when it gets END_OF_TRACK, relevant chunks contain last samples of the track.\n + //! Signaling this will often break regular gapless playback so don't use it unless you have reasons to. + virtual bool need_track_change_mark() = 0; + + void run_abortable(dsp_chunk_list * p_chunk_list,const metadb_handle_ptr & p_cur_file,int p_flags,abort_callback & p_abort); + + FB2K_MAKE_SERVICE_INTERFACE(dsp,service_base); +}; + +//! Backwards-compatible extension to dsp interface, allows abortable operation. Introduced in 0.9.2. +class NOVTABLE dsp_v2 : public dsp { +public: + //! Abortable version of dsp::run(). See dsp::run() for descriptions of parameters. + virtual void run_v2(dsp_chunk_list * p_chunk_list,const metadb_handle_ptr & p_cur_file,int p_flags,abort_callback & p_abort) = 0; +private: + void run(dsp_chunk_list * p_chunk_list,const metadb_handle_ptr & p_cur_file,int p_flags) { + run_v2(p_chunk_list,p_cur_file,p_flags,abort_callback_dummy()); + } + + FB2K_MAKE_SERVICE_INTERFACE(dsp_v2,dsp); +}; + +//! Helper class for implementing dsps. You should derive from dsp_impl_base instead of from dsp directly.\n +//! The dsp_impl_base_t template allows you to use a custom interface class as a base class for your implementation, in case you provide extended functionality.\n +//! Use dsp_factory_t<> template to register your dsp implementation. +//! The implementation - as required by dsp_factory_t<> template - must also provide following methods:\n +//! A constructor taking const dsp_preset&, initializing the DSP with specified preset data.\n +//! static void g_get_name(pfc::string_base &); - retrieving human-readable name of the DSP to display.\n +//! static bool g_get_default_preset(dsp_preset &); - retrieving default preset for this DSP. Return value is reserved for future use and should always be true.\n +//! static GUID g_get_guid(); - retrieving GUID of your DSP implementation, to be used to identify it when storing DSP chain configuration.\n +//! static bool g_have_config_popup(); - retrieving whether your DSP implementation supplies a popup dialog for configuring it.\n +//! static void g_show_config_popup(const dsp_preset & p_data,HWND p_parent, dsp_preset_edit_callback & p_callback); - displaying your DSP's settings dialog; called only when g_have_config_popup() returns true; call p_callback.on_preset_changed() whenever user has made adjustments to the preset data.\n +template +class dsp_impl_base_t : public t_baseclass { +private: + typedef dsp_impl_base_t t_self; + dsp_chunk_list * m_list; + t_size m_chunk_ptr; + metadb_handle* m_cur_file; + void run_v2(dsp_chunk_list * p_list,const metadb_handle_ptr & p_cur_file,int p_flags,abort_callback & p_abort); +protected: + //! Call only from on_chunk / on_endoftrack (on_endoftrack will give info on track being finished).\n + //! May return false when there's no known track and the metadb_handle ptr will be empty/null. + bool get_cur_file(metadb_handle_ptr & p_out) {p_out = m_cur_file; return p_out.is_valid();} + + dsp_impl_base_t() : m_list(NULL), m_cur_file(NULL), m_chunk_ptr(0) {} + + //! Inserts a new chunk of audio data. \n + //! You can call this only from on_chunk(), on_endofplayback() and on_endoftrack(). You're NOT allowed to call this from flush() which should just drop any queued data. + //! @param hint_size Optional, amount of buffer space that you require (in audio_samples). This is just a hint for memory allocation logic and will not cause the framework to allocate the chunk for you. + //! @returns A pointer to the newly allocated chunk. Pass the audio data you want to insert to this chunk object. The chunk is owned by the framework, you can't delete it etc. + audio_chunk * insert_chunk(t_size p_hint_size = 0) { + PFC_ASSERT(m_list != NULL); + return m_list->insert_item(m_chunk_ptr++,p_hint_size); + } + audio_chunk * insert_chunk( const audio_chunk & sourceCopy ) { + audio_chunk * c = insert_chunk( sourceCopy.get_used_size() ); + c->copy( sourceCopy ); + return c; + } + + + //! To be overridden by a DSP implementation.\n + //! Called on track change. You can use insert_chunk() to dump any data you have to flush. \n + //! Note that you must implement need_track_change_mark() to return true if you need this method called. + virtual void on_endoftrack(abort_callback & p_abort) = 0; + //! To be overridden by a DSP implementation.\n + //! Called at the end of played stream, typically at the end of last played track, to allow the DSP to return all data it has buffered-ahead.\n + //! Use insert_chunk() to return any data you have buffered.\n + //! Note that this call does not imply that the DSP will be destroyed next. \n + //! This is also called on track changes if some DSP placed after your DSP requests track change marks. + virtual void on_endofplayback(abort_callback & p_abort) = 0; + //! To be overridden by a DSP implementation.\n + //! Processes a chunk of audio data.\n + //! You can call insert_chunk() from inside on_chunk() to insert any audio data before currently processed chunk.\n + //! @param p_chunk Current chunk being processed. You can alter it in any way you like. + //! @returns True to keep p_chunk (with alterations made inside on_chunk()) in the stream, false to remove it. + virtual bool on_chunk(audio_chunk * p_chunk,abort_callback & p_abort) = 0; + +public: + //! To be overridden by a DSP implementation.\n + //! Flushes the DSP (drops any buffered data). The implementation should reset the DSP to the same state it was in before receiving any audio data. \n + //! Called after seeking, etc. + virtual void flush() = 0; + //! To be overridden by a DSP implementation.\n + //! Retrieves amount of data buffered by the DSP, for syncing visualisation. + //! @returns Amount of buffered audio data, in seconds. + virtual double get_latency() = 0; + //! To be overridden by a DSP implementation.\n + //! Returns true if DSP needs to know exact track change point (eg. for crossfading, removing silence).\n + //! Signaling this will force-flush any DSPs placed before this DSP so when it gets on_endoftrack(), relevant chunks contain last samples of the track.\n + //! Signaling this may interfere with gapless playback in certain scenarios (forces flush of DSPs placed before you) so don't use it unless you have reasons to. + virtual bool need_track_change_mark() = 0; +private: + dsp_impl_base_t(const t_self&); + const t_self & operator=(const t_self &); +}; + +template +void dsp_impl_base_t::run_v2(dsp_chunk_list * p_list,const metadb_handle_ptr & p_cur_file,int p_flags,abort_callback & p_abort) { + pfc::vartoggle_t l_list_toggle(m_list,p_list); + pfc::vartoggle_t l_cur_file_toggle(m_cur_file,p_cur_file.get_ptr()); + + for(m_chunk_ptr = 0;m_chunk_ptrget_count();m_chunk_ptr++) { + audio_chunk * c = m_list->get_item(m_chunk_ptr); + if (c->is_empty() || !on_chunk(c,p_abort)) + m_list->remove_by_idx(m_chunk_ptr--); + } + + if (p_flags & dsp::FLUSH) { + on_endofplayback(p_abort); + } else if (p_flags & dsp::END_OF_TRACK) { + if (need_track_change_mark()) on_endoftrack(p_abort); + } +} + + +typedef dsp_impl_base_t dsp_impl_base; + +class NOVTABLE dsp_preset { +public: + virtual GUID get_owner() const = 0; + virtual void set_owner(const GUID & p_owner) = 0; + virtual const void * get_data() const = 0; + virtual t_size get_data_size() const = 0; + virtual void set_data(const void * p_data,t_size p_data_size) = 0; + virtual void set_data_from_stream(stream_reader * p_stream,t_size p_bytes,abort_callback & p_abort) = 0; + + const dsp_preset & operator=(const dsp_preset & p_source) {copy(p_source); return *this;} + + void copy(const dsp_preset & p_source) {set_owner(p_source.get_owner());set_data(p_source.get_data(),p_source.get_data_size());} + + void contents_to_stream(stream_writer * p_stream,abort_callback & p_abort) const; + void contents_from_stream(stream_reader * p_stream,abort_callback & p_abort); + static void g_contents_from_stream_skip(stream_reader * p_stream,abort_callback & p_abort); + + bool operator==(const dsp_preset & p_other) const { + if (get_owner() != p_other.get_owner()) return false; + if (get_data_size() != p_other.get_data_size()) return false; + if (memcmp(get_data(),p_other.get_data(),get_data_size()) != 0) return false; + return true; + } + bool operator!=(const dsp_preset & p_other) const { + return !(*this == p_other); + } +protected: + dsp_preset() {} + ~dsp_preset() {} +}; + +class dsp_preset_writer : public stream_writer { +public: + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + p_abort.check(); + m_data.append_fromptr((const t_uint8 *) p_buffer,p_bytes); + } + void flush(dsp_preset & p_preset) { + p_preset.set_data(m_data.get_ptr(),m_data.get_size()); + m_data.set_size(0); + } +private: + pfc::array_t m_data; +}; + +class dsp_preset_reader : public stream_reader { +public: + dsp_preset_reader() : m_walk(0) {} + dsp_preset_reader(const dsp_preset_reader & p_source) : m_walk(0) {*this = p_source;} + void init(const dsp_preset & p_preset) { + m_data.set_data_fromptr( (const t_uint8*) p_preset.get_data(), p_preset.get_data_size() ); + m_walk = 0; + } + t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + p_abort.check(); + t_size todo = pfc::min_t(p_bytes,m_data.get_size()-m_walk); + memcpy(p_buffer,m_data.get_ptr()+m_walk,todo); + m_walk += todo; + return todo; + } + bool is_finished() {return m_walk == m_data.get_size();} +private: + t_size m_walk; + pfc::array_t m_data; +}; + +class dsp_preset_impl : public dsp_preset +{ +public: + dsp_preset_impl() {} + dsp_preset_impl(const dsp_preset_impl & p_source) {copy(p_source);} + dsp_preset_impl(const dsp_preset & p_source) {copy(p_source);} + + const dsp_preset_impl& operator=(const dsp_preset_impl & p_source) {copy(p_source); return *this;} + const dsp_preset_impl& operator=(const dsp_preset & p_source) {copy(p_source); return *this;} + + GUID get_owner() const {return m_owner;} + void set_owner(const GUID & p_owner) {m_owner = p_owner;} + const void * get_data() const {return m_data.get_ptr();} + t_size get_data_size() const {return m_data.get_size();} + void set_data(const void * p_data,t_size p_data_size) {m_data.set_data_fromptr((const t_uint8*)p_data,p_data_size);} + void set_data_from_stream(stream_reader * p_stream,t_size p_bytes,abort_callback & p_abort); +private: + GUID m_owner; + pfc::array_t m_data; +}; + +class NOVTABLE dsp_preset_edit_callback { +public: + virtual void on_preset_changed(const dsp_preset &) = 0; +private: + dsp_preset_edit_callback(const dsp_preset_edit_callback&) {throw pfc::exception_not_implemented();} + const dsp_preset_edit_callback & operator=(const dsp_preset_edit_callback &) {throw pfc::exception_not_implemented();} +protected: + dsp_preset_edit_callback() {} + ~dsp_preset_edit_callback() {} +}; + +class NOVTABLE dsp_entry : public service_base { +public: + virtual void get_name(pfc::string_base & p_out) = 0; + virtual bool get_default_preset(dsp_preset & p_out) = 0; + virtual bool instantiate(service_ptr_t & p_out,const dsp_preset & p_preset) = 0; + virtual GUID get_guid() = 0; + virtual bool have_config_popup() = 0; + virtual bool show_config_popup(dsp_preset & p_data,HWND p_parent) = 0; + + + static bool g_get_interface(service_ptr_t & p_out,const GUID & p_guid); + static bool g_instantiate(service_ptr_t & p_out,const dsp_preset & p_preset); + static bool g_instantiate_default(service_ptr_t & p_out,const GUID & p_guid); + static bool g_name_from_guid(pfc::string_base & p_out,const GUID & p_guid); + static bool g_dsp_exists(const GUID & p_guid); + static bool g_get_default_preset(dsp_preset & p_out,const GUID & p_guid); + static bool g_have_config_popup(const GUID & p_guid); + static bool g_have_config_popup(const dsp_preset & p_preset); + static bool g_show_config_popup(dsp_preset & p_preset,HWND p_parent); + + static void g_show_config_popup_v2(const dsp_preset & p_preset,HWND p_parent,dsp_preset_edit_callback & p_callback); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(dsp_entry); +}; + +class NOVTABLE dsp_entry_v2 : public dsp_entry { +public: + virtual void show_config_popup_v2(const dsp_preset & p_data,HWND p_parent,dsp_preset_edit_callback & p_callback) = 0; + +private: + bool show_config_popup(dsp_preset & p_data,HWND p_parent); + + FB2K_MAKE_SERVICE_INTERFACE(dsp_entry_v2,dsp_entry); +}; + +template +class dsp_entry_impl_nopreset_t : public t_entry { +public: + void get_name(pfc::string_base & p_out) {T::g_get_name(p_out);} + bool get_default_preset(dsp_preset & p_out) + { + p_out.set_owner(T::g_get_guid()); + p_out.set_data(0,0); + return true; + } + bool instantiate(service_ptr_t & p_out,const dsp_preset & p_preset) + { + if (p_preset.get_owner() == T::g_get_guid() && p_preset.get_data_size() == 0) + { + p_out = new service_impl_t(); + return p_out.is_valid(); + } + else return false; + } + GUID get_guid() {return T::g_get_guid();} + + bool have_config_popup() {return false;} + bool show_config_popup(dsp_preset & p_data,HWND p_parent) {return false;} +}; + +template +class dsp_entry_impl_t : public t_entry { +public: + void get_name(pfc::string_base & p_out) {T::g_get_name(p_out);} + bool get_default_preset(dsp_preset & p_out) {return T::g_get_default_preset(p_out);} + bool instantiate(service_ptr_t & p_out,const dsp_preset & p_preset) { + if (p_preset.get_owner() == T::g_get_guid()) { + p_out = new service_impl_t(p_preset); + return true; + } + else return false; + } + GUID get_guid() {return T::g_get_guid();} + + bool have_config_popup() {return T::g_have_config_popup();} + bool show_config_popup(dsp_preset & p_data,HWND p_parent) {return T::g_show_config_popup(p_data,p_parent);} + //void show_config_popup_v2(const dsp_preset & p_data,HWND p_parent,dsp_preset_edit_callback & p_callback) {T::g_show_config_popup(p_data,p_parent,p_callback);} +}; + +template +class dsp_entry_v2_impl_t : public t_entry { +public: + void get_name(pfc::string_base & p_out) {T::g_get_name(p_out);} + bool get_default_preset(dsp_preset & p_out) {return T::g_get_default_preset(p_out);} + bool instantiate(service_ptr_t & p_out,const dsp_preset & p_preset) { + if (p_preset.get_owner() == T::g_get_guid()) { + p_out = new service_impl_t(p_preset); + return true; + } + else return false; + } + GUID get_guid() {return T::g_get_guid();} + + bool have_config_popup() {return T::g_have_config_popup();} + //bool show_config_popup(dsp_preset & p_data,HWND p_parent) {return T::g_show_config_popup(p_data,p_parent);} + void show_config_popup_v2(const dsp_preset & p_data,HWND p_parent,dsp_preset_edit_callback & p_callback) {T::g_show_config_popup(p_data,p_parent,p_callback);} +}; + + +template +class dsp_factory_nopreset_t : public service_factory_single_t > {}; + +template +class dsp_factory_t : public service_factory_single_t > {}; + +class NOVTABLE dsp_chain_config +{ +public: + virtual t_size get_count() const = 0; + virtual const dsp_preset & get_item(t_size p_index) const = 0; + virtual void replace_item(const dsp_preset & p_data,t_size p_index) = 0; + virtual void insert_item(const dsp_preset & p_data,t_size p_index) = 0; + virtual void remove_mask(const bit_array & p_mask) = 0; + + void remove_item(t_size p_index); + void remove_all(); + void add_item(const dsp_preset & p_data); + void copy(const dsp_chain_config & p_source); + + const dsp_chain_config & operator=(const dsp_chain_config & p_source) {copy(p_source); return *this;} + + void contents_to_stream(stream_writer * p_stream,abort_callback & p_abort) const; + void contents_from_stream(stream_reader * p_stream,abort_callback & p_abort); + + void instantiate(service_list_t & p_out); + + void get_name_list(pfc::string_base & p_out) const; + + static bool equals(dsp_chain_config const & v1, dsp_chain_config const & v2); + + bool operator==(const dsp_chain_config & other) const {return equals(*this, other);} + bool operator!=(const dsp_chain_config & other) const {return !equals(*this, other);} +}; + +FB2K_STREAM_READER_OVERLOAD(dsp_chain_config) { + value.contents_from_stream(&stream.m_stream, stream.m_abort); return stream; +} + +FB2K_STREAM_WRITER_OVERLOAD(dsp_chain_config) { + value.contents_to_stream(&stream.m_stream, stream.m_abort); return stream; +} + +class dsp_chain_config_impl : public dsp_chain_config +{ +public: + dsp_chain_config_impl() {} + dsp_chain_config_impl(const dsp_chain_config & p_source) {copy(p_source);} + dsp_chain_config_impl(const dsp_chain_config_impl & p_source) {copy(p_source);} + t_size get_count() const; + const dsp_preset & get_item(t_size p_index) const; + void replace_item(const dsp_preset & p_data,t_size p_index); + void insert_item(const dsp_preset & p_data,t_size p_index); + void remove_mask(const bit_array & p_mask); + + const dsp_chain_config_impl & operator=(const dsp_chain_config & p_source) {copy(p_source); return *this;} + const dsp_chain_config_impl & operator=(const dsp_chain_config_impl & p_source) {copy(p_source); return *this;} + + ~dsp_chain_config_impl(); +private: + pfc::ptr_list_t m_data; +}; + +class cfg_dsp_chain_config : public cfg_var { +protected: + void get_data_raw(stream_writer * p_stream,abort_callback & p_abort); + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort); +public: + void reset(); + inline cfg_dsp_chain_config(const GUID & p_guid) : cfg_var(p_guid) {} + t_size get_count() const {return m_data.get_count();} + const dsp_preset & get_item(t_size p_index) const {return m_data.get_item(p_index);} + bool get_data(dsp_chain_config & p_data) const; + void set_data(const dsp_chain_config & p_data); +private: + dsp_chain_config_impl m_data; + +}; + + + + +//! Helper. +class dsp_preset_parser : public stream_reader_formatter<> { +public: + dsp_preset_parser(const dsp_preset & in) : m_data(in), _m_stream(in.get_data(),in.get_data_size()), stream_reader_formatter(_m_stream,_m_abort) {} + + void reset() {_m_stream.reset();} + t_size get_remaining() const {return _m_stream.get_remaining();} + + void assume_empty() const { + if (get_remaining() != 0) throw exception_io_data(); + } + + GUID get_owner() const {return m_data.get_owner();} +private: + const dsp_preset & m_data; + abort_callback_dummy _m_abort; + stream_reader_memblock_ref _m_stream; +}; + +//! Helper. +class dsp_preset_builder : public stream_writer_formatter<> { +public: + dsp_preset_builder() : stream_writer_formatter(_m_stream,_m_abort) {} + void finish(const GUID & id, dsp_preset & out) { + out.set_owner(id); + out.set_data(_m_stream.m_buffer.get_ptr(), _m_stream.m_buffer.get_size()); + } + void reset() { + _m_stream.m_buffer.set_size(0); + } +private: + abort_callback_dummy _m_abort; + stream_writer_buffer_simple _m_stream; +}; diff --git a/SDK/foobar2000/SDK/dsp_manager.cpp b/SDK/foobar2000/SDK/dsp_manager.cpp new file mode 100644 index 0000000..dc43edf --- /dev/null +++ b/SDK/foobar2000/SDK/dsp_manager.cpp @@ -0,0 +1,189 @@ +#include "foobar2000.h" + +void dsp_manager::close() { + m_chain.remove_all(); + m_config_changed = true; +} + +void dsp_manager::set_config( const dsp_chain_config & p_data ) +{ + //dsp_chain_config::g_instantiate(m_dsp_list,p_data); + m_config.copy(p_data); + m_config_changed = true; +} + +void dsp_manager::dsp_run(t_dsp_chain::const_iterator p_iter,dsp_chunk_list * p_list,const metadb_handle_ptr & cur_file,unsigned flags,double & latency,abort_callback & p_abort) +{ + p_list->remove_bad_chunks(); + + TRACK_CODE("dsp::run",p_iter->m_dsp->run_abortable(p_list,cur_file,flags,p_abort)); + TRACK_CODE("dsp::get_latency",latency += p_iter->m_dsp->get_latency()); +} + +double dsp_manager::run(dsp_chunk_list * p_list,const metadb_handle_ptr & p_cur_file,unsigned p_flags,abort_callback & p_abort) { + TRACK_CALL_TEXT("dsp_manager::run"); + + try { +#if defined(_MSC_VER) && defined(_M_IX86) + fpu_control_default l_fpu_control; +#endif + double latency=0; + bool done = false; + + t_dsp_chain::const_iterator flush_mark; + if ((p_flags & dsp::END_OF_TRACK) && ! (p_flags & dsp::FLUSH)) { + for(t_dsp_chain::const_iterator iter = m_chain.first(); iter.is_valid(); ++iter) { + if (iter->m_dsp->need_track_change_mark()) flush_mark = iter; + } + } + + if (m_config_changed) + { + t_dsp_chain newchain; + bool recycle_available = true; + + for(t_size n=0;n temp; + + const dsp_preset & preset = m_config.get_item(n); + if (dsp_entry::g_dsp_exists(preset.get_owner())) { + t_dsp_chain::iterator iter = newchain.insert_last(); + iter->m_preset = m_config.get_item(n); + iter->m_recycle_flag = false; + } + } + + + //HACK: recycle existing DSPs in a special case when user has apparently only altered settings of one of DSPs. + if (newchain.get_count() == m_chain.get_count()) { + t_size data_mismatch_count = 0; + t_size owner_mismatch_count = 0; + t_dsp_chain::iterator iter_src, iter_dst; + iter_src = m_chain.first(); iter_dst = newchain.first(); + while(iter_src.is_valid() && iter_dst.is_valid()) { + if (iter_src->m_preset.get_owner() != iter_dst->m_preset.get_owner()) { + owner_mismatch_count++; + } else if (iter_src->m_preset != iter_dst->m_preset) { + data_mismatch_count++; + } + ++iter_src; ++iter_dst; + } + recycle_available = (owner_mismatch_count == 0 && data_mismatch_count <= 1); + } else { + recycle_available = false; + } + + if (recycle_available) { + t_dsp_chain::iterator iter_src, iter_dst; + iter_src = m_chain.first(); iter_dst = newchain.first(); + while(iter_src.is_valid() && iter_dst.is_valid()) { + if (iter_src->m_preset == iter_dst->m_preset) { + iter_src->m_recycle_flag = true; + iter_dst->m_dsp = iter_src->m_dsp; + } + ++iter_src; ++iter_dst; + } + } + + for(t_dsp_chain::iterator iter = newchain.first(); iter.is_valid(); ++iter) { + if (iter->m_dsp.is_empty()) { + if (!dsp_entry::g_instantiate(iter->m_dsp,iter->m_preset)) uBugCheck(); + } + } + + if (m_chain.get_count()>0) { + bool flushflag = flush_mark.is_valid(); + for(t_dsp_chain::const_iterator iter = m_chain.first(); iter.is_valid(); ++iter) { + unsigned flags2 = p_flags; + if (iter == flush_mark) flushflag = false; + if (flushflag || !iter->m_recycle_flag) flags2|=dsp::FLUSH; + dsp_run(iter,p_list,p_cur_file,flags2,latency,p_abort); + } + done = true; + } + + m_chain = newchain; + m_config_changed = false; + } + + if (!done) + { + bool flushflag = flush_mark.is_valid(); + for(t_dsp_chain::const_iterator iter = m_chain.first(); iter.is_valid(); ++iter) { + unsigned flags2 = p_flags; + if (iter == flush_mark) flushflag = false; + if (flushflag) flags2|=dsp::FLUSH; + dsp_run(iter,p_list,p_cur_file,flags2,latency,p_abort); + } + done = true; + } + + p_list->remove_bad_chunks(); + + return latency; + } catch(...) { + p_list->remove_all(); + throw; + } +} + +void dsp_manager::flush() +{ + for(t_dsp_chain::const_iterator iter = m_chain.first(); iter.is_valid(); ++iter) { + TRACK_CODE("dsp::flush",iter->m_dsp->flush()); + } +} + + +bool dsp_manager::is_active() const {return m_config.get_count()>0;} + +void dsp_config_manager::core_enable_dsp(const dsp_preset & preset) { + dsp_chain_config_impl cfg; + get_core_settings(cfg); + + bool found = false; + bool changed = false; + t_size n,m = cfg.get_count(); + for(n=0;n m_dsp; + dsp_preset_impl m_preset; + bool m_recycle_flag; + }; + typedef pfc::chain_list_v2_t t_dsp_chain; + + t_dsp_chain m_chain; + dsp_chain_config_impl m_config; + bool m_config_changed; + + void dsp_run(t_dsp_chain::const_iterator p_iter,dsp_chunk_list * list,const metadb_handle_ptr & cur_file,unsigned flags,double & latency,abort_callback&); + + dsp_manager(const dsp_manager &) {throw pfc::exception_not_implemented();} + const dsp_manager & operator=(const dsp_manager&) {throw pfc::exception_not_implemented();} +}; + +//! Core API for accessing core playback DSP settings as well as spawning DSP configuration dialogs. \n +//! Use static_api_ptr_t() to instantiate. +class dsp_config_manager : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(dsp_config_manager); +public: + //! Retrieves current core playback DSP settings. + virtual void get_core_settings(dsp_chain_config & p_out) = 0; + //! Changes current core playback DSP settings. + virtual void set_core_settings(const dsp_chain_config & p_data) = 0; + + //! Runs a modal DSP settings dialog. + //! @param p_data DSP chain configuration to edit - contains initial configuration to put in the dialog when called, receives the new configuration on successful edit. + //! @returns True when user approved DSP configuration changes (pressed the "OK" button), false when the user cancelled them ("Cancel" button). + virtual bool configure_popup(dsp_chain_config & p_data,HWND p_parent,const char * p_title) = 0; + + //! Spawns an embedded DSP settings dialog. + //! @param p_initdata Initial DSP chain configuration to put in the dialog. + //! @param p_parent Parent window to contain the embedded dialog. + //! @param p_id Control ID of the embedded dialog. The parent window will receive a WM_COMMAND with BN_CLICKED and this identifier when user changes settings in the embedded dialog. + //! @param p_from_modal Must be set to true when the parent window is a modal dialog, false otherwise. + virtual HWND configure_embedded(const dsp_chain_config & p_initdata,HWND p_parent,unsigned p_id,bool p_from_modal) = 0; + //! Retrieves current settings from an embedded DSP settings dialog. See also: configure_embedded(). + virtual void configure_embedded_retrieve(HWND wnd,dsp_chain_config & p_data) = 0; + //! Changes current settings in an embedded DSP settings dialog. See also: configure_embedded(). + virtual void configure_embedded_change(HWND wnd,const dsp_chain_config & p_data) = 0; + + + //! Helper - enables a DSP in core playback settings. + void core_enable_dsp(const dsp_preset & preset); + //! Helper - disables a DSP in core playback settings. + void core_disable_dsp(const GUID & id); + //! Helper - if a DSP with the specified identifier is present in playback settings, retrieves its configuration and returns true, otherwise returns false. + bool core_query_dsp(const GUID & id, dsp_preset & out); +}; + +//! Callback class for getting notified about core playback DSP settings getting altered. \n +//! Register your implementations with static service_factory_single_t g_myclass_factory; +class NOVTABLE dsp_config_callback : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(dsp_config_callback); +public: + //! Called when core playback DSP settings change. \n + //! Note: you must not try to alter core playback DSP settings inside this callback, or call anything else that possibly alters core playback DSP settings. + virtual void on_core_settings_change(const dsp_chain_config & p_newdata) = 0; +}; diff --git a/SDK/foobar2000/SDK/event_logger.h b/SDK/foobar2000/SDK/event_logger.h new file mode 100644 index 0000000..d396f36 --- /dev/null +++ b/SDK/foobar2000/SDK/event_logger.h @@ -0,0 +1,47 @@ +class NOVTABLE event_logger : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(event_logger, service_base); +public: + enum { + severity_status, + severity_warning, + severity_error + }; + void log_status(const char * line) {log_entry(line, severity_status);} + void log_warning(const char * line) {log_entry(line, severity_warning);} + void log_error(const char * line) {log_entry(line, severity_error);} + + virtual void log_entry(const char * line, unsigned severity) = 0; +}; + +class event_logger_fallback : public event_logger { +public: + void log_entry(const char * line, unsigned) {console::print(line);} +}; + +class NOVTABLE event_logger_recorder : public event_logger { + FB2K_MAKE_SERVICE_INTERFACE( event_logger_recorder , event_logger ); +public: + virtual void playback( event_logger::ptr playTo ) = 0; +}; + +class event_logger_recorder_impl : public event_logger_recorder { +public: + void playback( event_logger::ptr playTo ) { + for(auto i = m_entries.first(); i.is_valid(); ++i ) { + playTo->log_entry( i->line.get_ptr(), i->severity ); + } + } + + void log_entry( const char * line, unsigned severity ) { + auto rec = m_entries.insert_last(); + rec->line = line; + rec->severity = severity; + } +private: + + struct entry_t { + pfc::string_simple line; + unsigned severity; + }; + pfc::chain_list_v2_t< entry_t > m_entries; +}; \ No newline at end of file diff --git a/SDK/foobar2000/SDK/exceptions.h b/SDK/foobar2000/SDK/exceptions.h new file mode 100644 index 0000000..95f4b34 --- /dev/null +++ b/SDK/foobar2000/SDK/exceptions.h @@ -0,0 +1,15 @@ + +//! Base class for exceptions that should show a human readable message when caught in app entrypoint function rather than crash and send a crash report. +PFC_DECLARE_EXCEPTION(exception_messagebox,pfc::exception,"Internal Error"); + +//! Base class for exceptions that should result in a quiet app shutdown. +PFC_DECLARE_EXCEPTION(exception_shutdownrequest,pfc::exception,"Shutdown Request"); + + +PFC_DECLARE_EXCEPTION(exception_installdamaged, exception_messagebox, "Internal error - one or more of the installed components have been damaged."); +PFC_DECLARE_EXCEPTION(exception_osfailure, exception_messagebox, "Internal error - broken Windows installation?"); +PFC_DECLARE_EXCEPTION(exception_out_of_resources, exception_messagebox, "Not enough system resources available."); + +PFC_DECLARE_EXCEPTION(exception_configdamaged, exception_messagebox, "Internal error - configuration files are unreadable."); + +PFC_DECLARE_EXCEPTION(exception_profileaccess, exception_messagebox, "Internal error - cannot access configuration folder."); diff --git a/SDK/foobar2000/SDK/file_cached_impl.cpp b/SDK/foobar2000/SDK/file_cached_impl.cpp new file mode 100644 index 0000000..6fa22de --- /dev/null +++ b/SDK/foobar2000/SDK/file_cached_impl.cpp @@ -0,0 +1,370 @@ +#include "foobar2000.h" +namespace { + +#define FILE_CACHED_DEBUG_LOG 0 + +class file_cached_impl_v2 : public file_cached { +public: + enum {minBlockSize = 4096}; + enum {maxSkipSize = 128*1024}; + file_cached_impl_v2(size_t maxBlockSize) : m_maxBlockSize(maxBlockSize) { + //m_buffer.set_size(blocksize); + } + size_t get_cache_block_size() {return m_maxBlockSize;} + void suggest_grow_cache(size_t suggestSize) { + if (m_maxBlockSize < suggestSize) m_maxBlockSize = suggestSize; + } + + void initialize(service_ptr_t p_base,abort_callback & p_abort) { + m_base = p_base; + m_can_seek = m_base->can_seek(); + _reinit(p_abort); + } +private: + void _reinit(abort_callback & p_abort) { + m_position = 0; + + if (m_can_seek) { + m_position_base = m_base->get_position(p_abort); + } else { + m_position_base = 0; + } + + m_size = m_base->get_size(p_abort); + + flush_buffer(); + } +public: + + t_filesize skip(t_filesize p_bytes,abort_callback & p_abort) { + if (p_bytes > maxSkipSize) { + const t_filesize size = get_size(p_abort); + if (size != filesize_invalid) { + const t_filesize position = get_position(p_abort); + const t_filesize toskip = pfc::min_t( p_bytes, size - position ); + seek(position + toskip,p_abort); + return toskip; + } + } + return skip_( p_bytes, p_abort ); + } + t_filesize skip_(t_filesize p_bytes,abort_callback & p_abort) { +#if FILE_CACHED_DEBUG_LOG + FB2K_DebugLog() << "Skipping bytes: " << p_bytes; +#endif + t_filesize todo = p_bytes; + for(;;) { + size_t inBuffer = this->bufferRemaining(); + size_t delta = (size_t) pfc::min_t(inBuffer, todo); + m_bufferReadPtr += delta; + m_position += delta; + todo -= delta; + if (todo == 0) break; + p_abort.check(); + this->m_bufferState = 0; // null it early to leave in a consistent state if base read fails + this->m_bufferReadPtr = 0; + baseSeek(m_position,p_abort); + m_readSize = pfc::min_t(m_readSize << 1, this->m_maxBlockSize); + if (m_readSize < minBlockSize) m_readSize = minBlockSize; +#if FILE_CACHED_DEBUG_LOG + FB2K_DebugLog() << "Growing read size: " << m_readSize; +#endif + m_buffer.grow_size(m_readSize); + m_bufferState = m_base->read(m_buffer.get_ptr(), m_readSize, p_abort); + if (m_bufferState == 0) break; + m_position_base += m_bufferState; + } + + return p_bytes - todo; + } + + t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { +#if FILE_CACHED_DEBUG_LOG + FB2K_DebugLog() << "Reading bytes: " << p_bytes; +#endif + t_uint8 * outptr = (t_uint8*)p_buffer; + size_t todo = p_bytes; + for(;;) { + size_t inBuffer = this->bufferRemaining(); + size_t delta = pfc::min_t(inBuffer, todo); + memcpy(outptr, this->m_buffer.get_ptr() + m_bufferReadPtr, delta); + m_bufferReadPtr += delta; + m_position += delta; + todo -= delta; + if (todo == 0) break; + p_abort.check(); + outptr += delta; + this->m_bufferState = 0; // null it early to leave in a consistent state if base read fails + this->m_bufferReadPtr = 0; + baseSeek(m_position,p_abort); + m_readSize = pfc::min_t(m_readSize << 1, this->m_maxBlockSize); + if (m_readSize < minBlockSize) m_readSize = minBlockSize; +#if FILE_CACHED_DEBUG_LOG + FB2K_DebugLog() << "Growing read size: " << m_readSize; +#endif + m_buffer.grow_size(m_readSize); + m_bufferState = m_base->read(m_buffer.get_ptr(), m_readSize, p_abort); + if (m_bufferState == 0) break; + m_position_base += m_bufferState; + } + + return p_bytes - todo; + } + + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { +#if FILE_CACHED_DEBUG_LOG + FB2K_DebugLog() << "Writing bytes: " << p_bytes; +#endif + p_abort.check(); + baseSeek(m_position,p_abort); + m_base->write(p_buffer,p_bytes,p_abort); + m_position_base = m_position = m_position + p_bytes; + if (m_size < m_position) m_size = m_position; + flush_buffer(); + } + + t_filesize get_size(abort_callback & p_abort) { + p_abort.check(); + return m_size; + } + t_filesize get_position(abort_callback & p_abort) { + p_abort.check(); + return m_position; + } + void set_eof(abort_callback & p_abort) { + p_abort.check(); + baseSeek(m_position,p_abort); + m_base->set_eof(p_abort); + flush_buffer(); + } + void seek(t_filesize p_position,abort_callback & p_abort) { +#if FILE_CACHED_DEBUG_LOG + FB2K_DebugLog() << "Seeking: " << p_position; +#endif + p_abort.check(); + if (!m_can_seek) throw exception_io_object_not_seekable(); + if (p_position > m_size) throw exception_io_seek_out_of_range(); + int64_t delta = p_position - m_position; + + // special case + if (delta >= 0 && delta <= this->minBlockSize) { +#if FILE_CACHED_DEBUG_LOG + FB2K_DebugLog() << "Skip-seeking: " << p_position; +#endif + t_filesize skipped = this->skip_( delta, p_abort ); + PFC_ASSERT( skipped == delta ); (void) skipped; + return; + } + + m_position = p_position; + // within currently buffered data? + if ((delta >= 0 && (uint64_t) delta <= bufferRemaining()) || (delta < 0 && (uint64_t)(-delta) <= m_bufferReadPtr)) { +#if FILE_CACHED_DEBUG_LOG + FB2K_DebugLog() << "Quick-seeking: " << p_position; +#endif + m_bufferReadPtr += (ptrdiff_t)delta; + } else { +#if FILE_CACHED_DEBUG_LOG + FB2K_DebugLog() << "Slow-seeking: " << p_position; +#endif + this->flush_buffer(); + } + } + void reopen(abort_callback & p_abort) { + if (this->m_can_seek) { + seek(0,p_abort); + } else { + this->m_base->reopen( p_abort ); + this->_reinit( p_abort ); + } + } + bool can_seek() {return m_can_seek;} + bool get_content_type(pfc::string_base & out) {return m_base->get_content_type(out);} + void on_idle(abort_callback & p_abort) {p_abort.check();m_base->on_idle(p_abort);} + t_filetimestamp get_timestamp(abort_callback & p_abort) {p_abort.check(); return m_base->get_timestamp(p_abort);} + bool is_remote() {return m_base->is_remote();} + void resize(t_filesize p_size,abort_callback & p_abort) { + flush_buffer(); + m_base->resize(p_size,p_abort); + m_size = p_size; + if (m_position > m_size) m_position = m_size; + if (m_position_base > m_size) m_position_base = m_size; + } +private: + size_t bufferRemaining() const {return m_bufferState - m_bufferReadPtr;} + void baseSeek(t_filesize p_target,abort_callback & p_abort) { + if (p_target != m_position_base) { + m_base->seek(p_target,p_abort); + m_position_base = p_target; + } + } + + void flush_buffer() { + m_bufferState = m_bufferReadPtr = 0; + m_readSize = 0; + } + + service_ptr_t m_base; + t_filesize m_position,m_position_base,m_size; + bool m_can_seek; + size_t m_bufferState, m_bufferReadPtr; + pfc::array_t m_buffer; + size_t m_maxBlockSize; + size_t m_readSize; +}; + +class file_cached_impl : public file_cached { +public: + file_cached_impl(t_size blocksize) { + m_buffer.set_size(blocksize); + } + size_t get_cache_block_size() {return m_buffer.get_size();} + void suggest_grow_cache(size_t suggestSize) {} + void initialize(service_ptr_t p_base,abort_callback & p_abort) { + m_base = p_base; + m_can_seek = m_base->can_seek(); + _reinit(p_abort); + } +private: + void _reinit(abort_callback & p_abort) { + m_position = 0; + + if (m_can_seek) { + m_position_base = m_base->get_position(p_abort); + } else { + m_position_base = 0; + } + + m_size = m_base->get_size(p_abort); + + flush_buffer(); + } +public: + + t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + t_uint8 * outptr = (t_uint8*)p_buffer; + t_size done = 0; + while(done < p_bytes && m_position < m_size) { + p_abort.check(); + + if (m_position >= m_buffer_position && m_position < m_buffer_position + m_buffer_status) { + t_size delta = pfc::min_t((t_size)(m_buffer_position + m_buffer_status - m_position),p_bytes - done); + t_size bufptr = (t_size)(m_position - m_buffer_position); + memcpy(outptr+done,m_buffer.get_ptr()+bufptr,delta); + done += delta; + m_position += delta; + if (m_buffer_status != m_buffer.get_size() && done < p_bytes) break;//EOF before m_size is hit + } else { + m_buffer_position = m_position - m_position % m_buffer.get_size(); + baseSeek(m_buffer_position,p_abort); + + m_buffer_status = m_base->read(m_buffer.get_ptr(),m_buffer.get_size(),p_abort); + m_position_base += m_buffer_status; + + if (m_buffer_status <= (t_size)(m_position - m_buffer_position)) break; + } + } + + return done; + } + + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + p_abort.check(); + baseSeek(m_position,p_abort); + m_base->write(p_buffer,p_bytes,p_abort); + m_position_base = m_position = m_position + p_bytes; + if (m_size < m_position) m_size = m_position; + flush_buffer(); + } + + t_filesize get_size(abort_callback & p_abort) { + p_abort.check(); + return m_size; + } + t_filesize get_position(abort_callback & p_abort) { + p_abort.check(); + return m_position; + } + void set_eof(abort_callback & p_abort) { + p_abort.check(); + baseSeek(m_position,p_abort); + m_base->set_eof(p_abort); + flush_buffer(); + } + void seek(t_filesize p_position,abort_callback & p_abort) { + p_abort.check(); + if (!m_can_seek) throw exception_io_object_not_seekable(); + if (p_position > m_size) throw exception_io_seek_out_of_range(); + m_position = p_position; + } + void reopen(abort_callback & p_abort) { + if (this->m_can_seek) { + seek(0,p_abort); + } else { + this->m_base->reopen( p_abort ); + this->_reinit( p_abort ); + } + } + bool can_seek() {return m_can_seek;} + bool get_content_type(pfc::string_base & out) {return m_base->get_content_type(out);} + void on_idle(abort_callback & p_abort) {p_abort.check();m_base->on_idle(p_abort);} + t_filetimestamp get_timestamp(abort_callback & p_abort) {p_abort.check(); return m_base->get_timestamp(p_abort);} + bool is_remote() {return m_base->is_remote();} + void resize(t_filesize p_size,abort_callback & p_abort) { + flush_buffer(); + m_base->resize(p_size,p_abort); + m_size = p_size; + if (m_position > m_size) m_position = m_size; + if (m_position_base > m_size) m_position_base = m_size; + } +private: + void baseSeek(t_filesize p_target,abort_callback & p_abort) { + if (p_target != m_position_base) { + m_base->seek(p_target,p_abort); + m_position_base = p_target; + } + } + + void flush_buffer() { + m_buffer_status = 0; + m_buffer_position = 0; + } + + service_ptr_t m_base; + t_filesize m_position,m_position_base,m_size; + bool m_can_seek; + t_filesize m_buffer_position; + t_size m_buffer_status; + pfc::array_t m_buffer; +}; + +} + +file::ptr file_cached::g_create(service_ptr_t p_base,abort_callback & p_abort, t_size blockSize) { + + if (p_base->is_in_memory()) { + return p_base; // do not want + } + + { // do not duplicate cache layers, check if the file we're being handed isn't already cached + file_cached::ptr c; + if (p_base->service_query_t(c)) { + c->suggest_grow_cache(blockSize); + return p_base; + } + } + + service_ptr_t temp = new service_impl_t(blockSize); + temp->initialize(p_base,p_abort); + return temp; +} + +void file_cached::g_create(service_ptr_t & p_out,service_ptr_t p_base,abort_callback & p_abort, t_size blockSize) { + p_out = g_create(p_base, p_abort, blockSize); +} + +void file_cached::g_decodeInitCache(file::ptr & theFile, abort_callback & abort, size_t blockSize) { + if (theFile->is_remote() || !theFile->can_seek()) return; + + g_create(theFile, theFile, abort, blockSize); +} diff --git a/SDK/foobar2000/SDK/file_info.cpp b/SDK/foobar2000/SDK/file_info.cpp new file mode 100644 index 0000000..f607ba2 --- /dev/null +++ b/SDK/foobar2000/SDK/file_info.cpp @@ -0,0 +1,725 @@ +#include "foobar2000.h" + +#ifndef _MSC_VER +#define strcat_s strcat +#define _atoi64 atoll +#endif + +t_size file_info::meta_find_ex(const char * p_name,t_size p_name_length) const +{ + t_size n, m = meta_get_count(); + for(n=0;n= max) return 0; + return meta_enum_value(index,p_index); +} + +const char * file_info::info_get_ex(const char * p_name,t_size p_name_length) const +{ + t_size index = info_find_ex(p_name,p_name_length); + if (index == pfc_infinite) return 0; + return info_enum_value(index); +} + +t_int64 file_info::info_get_int(const char * name) const +{ + PFC_ASSERT(pfc::is_valid_utf8(name)); + const char * val = info_get(name); + if (val==0) return 0; + return _atoi64(val); +} + +t_int64 file_info::info_get_length_samples() const +{ + t_int64 ret = 0; + double len = get_length(); + t_int64 srate = info_get_int("samplerate"); + + if (srate>0 && len>0) + { + ret = audio_math::time_to_samples(len,(unsigned)srate); + } + return ret; +} + +double file_info::info_get_float(const char * name) const +{ + const char * ptr = info_get(name); + if (ptr) return pfc::string_to_float(ptr); + else return 0; +} + +void file_info::info_set_int(const char * name,t_int64 value) +{ + PFC_ASSERT(pfc::is_valid_utf8(name)); + info_set(name,pfc::format_int(value)); +} + +void file_info::info_set_float(const char * name,double value,unsigned precision,bool force_sign,const char * unit) +{ + PFC_ASSERT(pfc::is_valid_utf8(name)); + PFC_ASSERT(unit==0 || strlen(unit) <= 64); + char temp[128]; + pfc::float_to_string(temp,64,value,precision,force_sign); + temp[63] = 0; + if (unit) + { + strcat_s(temp," "); + strcat_s(temp,unit); + } + info_set(name,temp); +} + + +void file_info::info_set_replaygain_album_gain(float value) +{ + replaygain_info temp = get_replaygain(); + temp.m_album_gain = value; + set_replaygain(temp); +} + +void file_info::info_set_replaygain_album_peak(float value) +{ + replaygain_info temp = get_replaygain(); + temp.m_album_peak = value; + set_replaygain(temp); +} + +void file_info::info_set_replaygain_track_gain(float value) +{ + replaygain_info temp = get_replaygain(); + temp.m_track_gain = value; + set_replaygain(temp); +} + +void file_info::info_set_replaygain_track_peak(float value) +{ + replaygain_info temp = get_replaygain(); + temp.m_track_peak = value; + set_replaygain(temp); +} + + +static bool is_valid_bps(t_int64 val) +{ + return val>0 && val<=256; +} + +unsigned file_info::info_get_decoded_bps() const +{ + t_int64 val = info_get_int("decoded_bitspersample"); + if (is_valid_bps(val)) return (unsigned)val; + val = info_get_int("bitspersample"); + if (is_valid_bps(val)) return (unsigned)val; + return 0; + +} + +void file_info::reset() +{ + info_remove_all(); + meta_remove_all(); + set_length(0); + reset_replaygain(); +} + +void file_info::reset_replaygain() +{ + replaygain_info temp; + temp.reset(); + set_replaygain(temp); +} + +void file_info::copy_meta_single_rename_ex(const file_info & p_source,t_size p_index,const char * p_new_name,t_size p_new_name_length) +{ + t_size n, m = p_source.meta_enum_value_count(p_index); + t_size new_index = pfc_infinite; + for(n=0;n 0); + for(val=0;val 0) out += separator; + out += meta_enum_value(index,val); + } +} + +bool file_info::meta_format(const char * p_name,pfc::string_base & p_out, const char * separator) const { + p_out.reset(); + t_size index = meta_find(p_name); + if (index == pfc_infinite) return false; + meta_format_entry(index, p_out, separator); + return true; +} + +void file_info::info_calculate_bitrate(t_filesize p_filesize,double p_length) +{ + if (p_filesize > 0 && p_length > 0) info_set_bitrate((unsigned)floor((double)p_filesize * 8 / (p_length * 1000) + 0.5)); +} + +bool file_info::is_encoding_lossy() const { + const char * encoding = info_get("encoding"); + if (encoding != NULL) { + if (pfc::stricmp_ascii(encoding,"lossy") == 0 /*|| pfc::stricmp_ascii(encoding,"hybrid") == 0*/) return true; + } else { + //the old way + //disabled: don't whine if we're not sure what we're dealing with - might be a file with info not-yet-loaded in oddball cases or a mod file + //if (info_get("bitspersample") == NULL) return true; + } + return false; +} + +bool file_info::g_is_meta_equal(const file_info & p_item1,const file_info & p_item2) { + const t_size count = p_item1.meta_get_count(); + if (count != p_item2.meta_get_count()) { + //uDebugLog() << "meta count mismatch"; + return false; + } + pfc::map_t item2_meta_map; + for(t_size n=0; n item2_meta_map; + for(t_size n=0; n= 32 && p_char < 127 && p_char != '=' && p_char != '%' && p_char != '<' && p_char != '>'; +} + +bool file_info::g_is_valid_field_name(const char * p_name,t_size p_length) { + t_size walk; + for(walk = 0; walk < p_length && p_name[walk] != 0; walk++) { + if (!is_valid_field_name_char(p_name[walk])) return false; + } + return walk > 0; +} + +void file_info::to_formatter(pfc::string_formatter& out) const { + out << "File info dump:\n"; + if (get_length() > 0) out<< "Duration: " << pfc::format_time_ex(get_length(), 6) << "\n"; + pfc::string_formatter temp; + for(t_size metaWalk = 0; metaWalk < meta_get_count(); ++metaWalk) { + meta_format_entry(metaWalk, temp); + out << "Meta: " << meta_enum_name(metaWalk) << " = " << temp << "\n"; + } + for(t_size infoWalk = 0; infoWalk < info_get_count(); ++infoWalk) { + out << "Info: " << info_enum_name(infoWalk) << " = " << info_enum_value(infoWalk) << "\n"; + } +} + +void file_info::to_console() const { + FB2K_console_formatter() << "File info dump:"; + if (get_length() > 0) FB2K_console_formatter() << "Duration: " << pfc::format_time_ex(get_length(), 6); + pfc::string_formatter temp; + for(t_size metaWalk = 0; metaWalk < meta_get_count(); ++metaWalk) { + meta_format_entry(metaWalk, temp); + FB2K_console_formatter() << "Meta: " << meta_enum_name(metaWalk) << " = " << temp; + } + for(t_size infoWalk = 0; infoWalk < info_get_count(); ++infoWalk) { + FB2K_console_formatter() << "Info: " << info_enum_name(infoWalk) << " = " << info_enum_value(infoWalk); + } +} + +void file_info::info_set_wfx_chanMask(uint32_t val) { + switch(val) { + case 0: + case 4: + case 3: + break; + default: + info_set ("WAVEFORMATEXTENSIBLE_CHANNEL_MASK", PFC_string_formatter() << "0x" << pfc::format_hex(val) ); + break; + } +} + +uint32_t file_info::info_get_wfx_chanMask() const { + const char * str = this->info_get("WAVEFORMATEXTENSIBLE_CHANNEL_MASK"); + if (str == NULL) return 0; + if (pfc::strcmp_partial( str, "0x") != 0) return 0; + try { + return pfc::atohex( str + 2, strlen(str+2) ); + } catch(...) { return 0;} +} + +bool file_info::field_is_person(const char * fieldName) { + return field_name_equals(fieldName, "artist") || + field_name_equals(fieldName, "album artist") || + field_name_equals(fieldName, "composer") || + field_name_equals(fieldName, "performer") || + field_name_equals(fieldName, "conductor") || + field_name_equals(fieldName, "orchestra") || + field_name_equals(fieldName, "ensemble") || + field_name_equals(fieldName, "engineer"); +} + +bool file_info::field_is_title(const char * fieldName) { + return field_name_equals(fieldName, "title") || field_name_equals(fieldName, "album"); +} + + +void file_info::to_stream( stream_writer * stream, abort_callback & abort ) const { + stream_writer_formatter<> out(* stream, abort ); + + out << this->get_length(); + + { + const auto rg = this->get_replaygain(); + out << rg.m_track_gain << rg.m_album_gain << rg.m_track_peak << rg.m_album_peak; + } + + + { + const uint32_t metaCount = pfc::downcast_guarded( this->meta_get_count() ); + for(uint32_t metaWalk = 0; metaWalk < metaCount; ++metaWalk) { + const char * name = this->meta_enum_name( metaWalk ); + if (*name) { + out.write_string_nullterm( this->meta_enum_name( metaWalk ) ); + const size_t valCount = this->meta_enum_value_count( metaWalk ); + for(size_t valWalk = 0; valWalk < valCount; ++valWalk) { + const char * value = this->meta_enum_value( metaWalk, valWalk ); + if (*value) { + out.write_string_nullterm( value ); + } + } + out.write_int(0); + } + } + out.write_int(0); + } + + { + const uint32_t infoCount = pfc::downcast_guarded( this->info_get_count() ); + for(uint32_t infoWalk = 0; infoWalk < infoCount; ++infoWalk) { + const char * name = this->info_enum_name( infoWalk ); + const char * value = this->info_enum_value( infoWalk ); + if (*name && *value) { + out.write_string_nullterm(name); out.write_string_nullterm(value); + } + } + out.write_int(0); + } +} + +void file_info::from_stream( stream_reader * stream, abort_callback & abort ) { + stream_reader_formatter<> in( *stream, abort ); + pfc::string_formatter tempName, tempValue; + { + double len; in >> len; this->set_length( len ); + } + { + replaygain_info rg; + in >> rg.m_track_gain >> rg.m_album_gain >> rg.m_track_peak >> rg.m_album_peak; + } + + { + this->meta_remove_all(); + for(;;) { + in.read_string_nullterm( tempName ); + if (tempName.length() == 0) break; + size_t metaIndex = pfc_infinite; + for(;;) { + in.read_string_nullterm( tempValue ); + if (tempValue.length() == 0) break; + if (metaIndex == pfc_infinite) metaIndex = this->meta_add( tempName, tempValue ); + else this->meta_add_value( metaIndex, tempValue ); + } + } + } + { + this->info_remove_all(); + for(;;) { + in.read_string_nullterm( tempName ); + if (tempName.length() == 0) break; + in.read_string_nullterm( tempValue ); + this->info_set( tempName, tempValue ); + } + } +} + +static const char * _readString( const uint8_t * & ptr, size_t & remaining ) { + const char * rv = (const char*)ptr; + for(;;) { + if (remaining == 0) throw exception_io_data(); + uint8_t byte = *ptr++; --remaining; + if (byte == 0) break; + } + return rv; +} + +template void _readInt( int_t & out, const uint8_t * &ptr, size_t & remaining) { + if (remaining < sizeof(out)) throw exception_io_data(); + pfc::decode_little_endian( out, ptr ); ptr += sizeof(out); remaining -= sizeof(out); +} + +template static void _readFloat(float_t & out, const uint8_t * &ptr, size_t & remaining) { + union { + typename pfc::sized_int_t::t_unsigned i; + float_t f; + } u; + _readInt(u.i, ptr, remaining); + out = u.f; +} + +void file_info::from_mem( const void * memPtr, size_t memSize ) { + size_t remaining = memSize; + const uint8_t * walk = (const uint8_t*) memPtr; + + { + double len; _readFloat(len, walk, remaining); + this->set_length( len ); + } + + { + replaygain_info rg; + _readFloat(rg.m_track_gain, walk, remaining ); + _readFloat(rg.m_album_gain, walk, remaining ); + _readFloat(rg.m_track_peak, walk, remaining ); + _readFloat(rg.m_album_peak, walk, remaining ); + this->set_replaygain( rg ); + } + + { + this->meta_remove_all(); + for(;;) { + const char * metaName = _readString( walk, remaining ); + if (*metaName == 0) break; + size_t metaIndex = pfc_infinite; + for(;;) { + const char * metaValue = _readString( walk, remaining ); + if (*metaValue == 0) break; + if (metaIndex == pfc_infinite) metaIndex = this->meta_add( metaName, metaValue ); + else this->meta_add_value( metaIndex, metaName ); + } + } + } + { + this->info_remove_all(); + for(;;) { + const char * infoName = _readString( walk, remaining ); + if (*infoName == 0) break; + const char * infoValue = _readString( walk, remaining ); + this->info_set( infoName, infoValue ); + } + } +} + +audio_chunk::spec_t file_info::audio_chunk_spec() const +{ + audio_chunk::spec_t rv = {}; + rv.sampleRate = (uint32_t)this->info_get_int("samplerate"); + rv.chanCount = (uint32_t)this->info_get_int("channels"); + rv.chanMask = (uint32_t)this->info_get_wfx_chanMask(); + if (audio_chunk::g_count_channels( rv.chanMask ) != rv.chanCount ) { + rv.chanMask = audio_chunk::g_guess_channel_config( rv.chanCount ); + } + return rv; +} \ No newline at end of file diff --git a/SDK/foobar2000/SDK/file_info.h b/SDK/foobar2000/SDK/file_info.h new file mode 100644 index 0000000..f5da9c9 --- /dev/null +++ b/SDK/foobar2000/SDK/file_info.h @@ -0,0 +1,279 @@ +//! Structure containing ReplayGain scan results from some playable object, also providing various helper methods to manipulate those results. +struct replaygain_info +{ + float m_album_gain,m_track_gain; + float m_album_peak,m_track_peak; + + enum {text_buffer_size = 16 }; + typedef char t_text_buffer[text_buffer_size]; + + enum { peak_invalid = -1, gain_invalid = -1000 }; + + static bool g_format_gain(float p_value,char p_buffer[text_buffer_size]); + static bool g_format_peak(float p_value,char p_buffer[text_buffer_size]); + + inline bool format_album_gain(char p_buffer[text_buffer_size]) const {return g_format_gain(m_album_gain,p_buffer);} + inline bool format_track_gain(char p_buffer[text_buffer_size]) const {return g_format_gain(m_track_gain,p_buffer);} + inline bool format_album_peak(char p_buffer[text_buffer_size]) const {return g_format_peak(m_album_peak,p_buffer);} + inline bool format_track_peak(char p_buffer[text_buffer_size]) const {return g_format_peak(m_track_peak,p_buffer);} + + void set_album_gain_text(const char * p_text,t_size p_text_len = pfc_infinite); + void set_track_gain_text(const char * p_text,t_size p_text_len = pfc_infinite); + void set_album_peak_text(const char * p_text,t_size p_text_len = pfc_infinite); + void set_track_peak_text(const char * p_text,t_size p_text_len = pfc_infinite); + + static bool g_is_meta_replaygain(const char * p_name,t_size p_name_len = pfc_infinite); + bool set_from_meta_ex(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len); + inline bool set_from_meta(const char * p_name,const char * p_value) {return set_from_meta_ex(p_name,pfc_infinite,p_value,pfc_infinite);} + + inline bool is_album_gain_present() const {return m_album_gain != gain_invalid;} + inline bool is_track_gain_present() const {return m_track_gain != gain_invalid;} + inline bool is_album_peak_present() const {return m_album_peak != peak_invalid;} + inline bool is_track_peak_present() const {return m_track_peak != peak_invalid;} + + inline void remove_album_gain() {m_album_gain = gain_invalid;} + inline void remove_track_gain() {m_track_gain = gain_invalid;} + inline void remove_album_peak() {m_album_peak = peak_invalid;} + inline void remove_track_peak() {m_track_peak = peak_invalid;} + + t_size get_value_count(); + + static replaygain_info g_merge(replaygain_info r1,replaygain_info r2); + + static bool g_equal(const replaygain_info & item1,const replaygain_info & item2); + + void reset(); +}; + +class format_rg_gain { +public: + format_rg_gain(float val) {replaygain_info::g_format_gain(val, m_buffer);} + + operator const char * () const {return m_buffer;} +private: + replaygain_info::t_text_buffer m_buffer; +}; + +class format_rg_peak { +public: + format_rg_peak(float val) {replaygain_info::g_format_peak(val, m_buffer);} + + operator const char * () const {return m_buffer;} +private: + replaygain_info::t_text_buffer m_buffer; +}; + +inline bool operator==(const replaygain_info & item1,const replaygain_info & item2) {return replaygain_info::g_equal(item1,item2);} +inline bool operator!=(const replaygain_info & item1,const replaygain_info & item2) {return !replaygain_info::g_equal(item1,item2);} + +static const replaygain_info replaygain_info_invalid = {replaygain_info::gain_invalid,replaygain_info::gain_invalid,replaygain_info::peak_invalid,replaygain_info::peak_invalid}; + + +//! Main interface class for information about some playable object. +class NOVTABLE file_info { +public: + //! Retrieves audio duration, in seconds. \n + //! Note that the reported duration should not be assumed to be the exact length of the track -\n + //! with many popular audio formats, exact duration is impossible to determine without performing a full decode pass;\n + //! with other formats, the decoded data may be shorter than reported due to truncation other damage. + virtual double get_length() const = 0; + //! Sets audio duration, in seconds. \n + //! Note that the reported duration should not be assumed to be the exact length of the track -\n + //! with many popular audio formats, exact duration is impossible to determine without performing a full decode pass;\n + //! with other formats, the decoded data may be shorter than reported due to truncation other damage. + virtual void set_length(double p_length) = 0; + + //! Sets ReplayGain information. + virtual void set_replaygain(const replaygain_info & p_info) = 0; + //! Retrieves ReplayGain information. + virtual replaygain_info get_replaygain() const = 0; + + //! Retrieves count of metadata entries. + virtual t_size meta_get_count() const = 0; + //! Retrieves the name of metadata entry of specified index. Return value is a null-terminated UTF-8 encoded string. + virtual const char* meta_enum_name(t_size p_index) const = 0; + //! Retrieves count of values in metadata entry of specified index. The value is always equal to or greater than 1. + virtual t_size meta_enum_value_count(t_size p_index) const = 0; + //! Retrieves specified value from specified metadata entry. Return value is a null-terminated UTF-8 encoded string. + virtual const char* meta_enum_value(t_size p_index,t_size p_value_number) const = 0; + //! Finds index of metadata entry of specified name. Returns infinite when not found. + virtual t_size meta_find_ex(const char * p_name,t_size p_name_length) const; + //! Creates a new metadata entry of specified name with specified value. If an entry of same name already exists, it is erased. Return value is the index of newly created metadata entry. + virtual t_size meta_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) = 0; + //! Inserts a new value into specified metadata entry. + virtual void meta_insert_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length) = 0; + //! Removes metadata entries according to specified bit mask. + virtual void meta_remove_mask(const bit_array & p_mask) = 0; + //! Reorders metadata entries according to specified permutation. + virtual void meta_reorder(const t_size * p_order) = 0; + //! Removes values according to specified bit mask from specified metadata entry. If all values are removed, entire metadata entry is removed as well. + virtual void meta_remove_values(t_size p_index,const bit_array & p_mask) = 0; + //! Alters specified value in specified metadata entry. + virtual void meta_modify_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length) = 0; + + //! Retrieves number of technical info entries. + virtual t_size info_get_count() const = 0; + //! Retrieves the name of specified technical info entry. Return value is a null-terminated UTF-8 encoded string. + virtual const char* info_enum_name(t_size p_index) const = 0; + //! Retrieves the value of specified technical info entry. Return value is a null-terminated UTF-8 encoded string. + virtual const char* info_enum_value(t_size p_index) const = 0; + //! Creates a new technical info entry with specified name and specified value. If an entry of the same name already exists, it is erased. Return value is the index of newly created entry. + virtual t_size info_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) = 0; + //! Removes technical info entries indicated by specified bit mask. + virtual void info_remove_mask(const bit_array & p_mask) = 0; + //! Finds technical info entry of specified name. Returns index of found entry on success, infinite on failure. + virtual t_size info_find_ex(const char * p_name,t_size p_name_length) const; + + //! Copies entire file_info contents from specified file_info object. + virtual void copy(const file_info & p_source);//virtualized for performance reasons, can be faster in two-pass + //! Copies metadata from specified file_info object. + virtual void copy_meta(const file_info & p_source);//virtualized for performance reasons, can be faster in two-pass + //! Copies technical info from specified file_info object. + virtual void copy_info(const file_info & p_source);//virtualized for performance reasons, can be faster in two-pass + + bool meta_exists_ex(const char * p_name,t_size p_name_length) const; + void meta_remove_field_ex(const char * p_name,t_size p_name_length); + void meta_remove_index(t_size p_index); + void meta_remove_all(); + void meta_remove_value(t_size p_index,t_size p_value); + const char * meta_get_ex(const char * p_name,t_size p_name_length,t_size p_index) const; + t_size meta_get_count_by_name_ex(const char * p_name,t_size p_name_length) const; + void meta_add_value_ex(t_size p_index,const char * p_value,t_size p_value_length); + t_size meta_add_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length); + t_size meta_calc_total_value_count() const; + bool meta_format(const char * p_name,pfc::string_base & p_out, const char * separator = ", ") const; + void meta_format_entry(t_size index, pfc::string_base & p_out, const char * separator = ", ") const;//same as meta_format but takes index instead of meta name. + + + bool info_exists_ex(const char * p_name,t_size p_name_length) const; + void info_remove_index(t_size p_index); + void info_remove_all(); + bool info_remove_ex(const char * p_name,t_size p_name_length); + const char * info_get_ex(const char * p_name,t_size p_name_length) const; + + inline t_size meta_find(const char * p_name) const {return meta_find_ex(p_name,pfc_infinite);} + inline bool meta_exists(const char * p_name) const {return meta_exists_ex(p_name,pfc_infinite);} + inline void meta_remove_field(const char * p_name) {meta_remove_field_ex(p_name,pfc_infinite);} + inline t_size meta_set(const char * p_name,const char * p_value) {return meta_set_ex(p_name,pfc_infinite,p_value,pfc_infinite);} + inline void meta_insert_value(t_size p_index,t_size p_value_index,const char * p_value) {meta_insert_value_ex(p_index,p_value_index,p_value,pfc_infinite);} + inline void meta_add_value(t_size p_index,const char * p_value) {meta_add_value_ex(p_index,p_value,pfc_infinite);} + inline const char* meta_get(const char * p_name,t_size p_index) const {return meta_get_ex(p_name,pfc_infinite,p_index);} + inline t_size meta_get_count_by_name(const char * p_name) const {return meta_get_count_by_name_ex(p_name,pfc_infinite);} + inline t_size meta_add(const char * p_name,const char * p_value) {return meta_add_ex(p_name,pfc_infinite,p_value,pfc_infinite);} + inline void meta_modify_value(t_size p_index,t_size p_value_index,const char * p_value) {meta_modify_value_ex(p_index,p_value_index,p_value,pfc_infinite);} + + + + inline t_size info_set(const char * p_name,const char * p_value) {return info_set_ex(p_name,pfc_infinite,p_value,pfc_infinite);} + inline t_size info_find(const char * p_name) const {return info_find_ex(p_name,pfc_infinite);} + inline bool info_exists(const char * p_name) const {return info_exists_ex(p_name,pfc_infinite);} + inline bool info_remove(const char * p_name) {return info_remove_ex(p_name,pfc_infinite);} + inline const char * info_get(const char * p_name) const {return info_get_ex(p_name,pfc_infinite);} + + bool info_set_replaygain_ex(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len); + inline bool info_set_replaygain(const char * p_name,const char * p_value) {return info_set_replaygain_ex(p_name,pfc_infinite,p_value,pfc_infinite);} + void info_set_replaygain_auto_ex(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len); + inline void info_set_replaygain_auto(const char * p_name,const char * p_value) {info_set_replaygain_auto_ex(p_name,pfc_infinite,p_value,pfc_infinite);} + + + + void copy_meta_single(const file_info & p_source,t_size p_index); + void copy_info_single(const file_info & p_source,t_size p_index); + void copy_meta_single_by_name_ex(const file_info & p_source,const char * p_name,t_size p_name_length); + void copy_info_single_by_name_ex(const file_info & p_source,const char * p_name,t_size p_name_length); + inline void copy_meta_single_by_name(const file_info & p_source,const char * p_name) {copy_meta_single_by_name_ex(p_source,p_name,pfc_infinite);} + inline void copy_info_single_by_name(const file_info & p_source,const char * p_name) {copy_info_single_by_name_ex(p_source,p_name,pfc_infinite);} + void reset(); + void reset_replaygain(); + void copy_meta_single_rename_ex(const file_info & p_source,t_size p_index,const char * p_new_name,t_size p_new_name_length); + inline void copy_meta_single_rename(const file_info & p_source,t_size p_index,const char * p_new_name) {copy_meta_single_rename_ex(p_source,p_index,p_new_name,pfc_infinite);} + void overwrite_info(const file_info & p_source); + void overwrite_meta(const file_info & p_source); + + t_int64 info_get_int(const char * name) const; + t_int64 info_get_length_samples() const; + double info_get_float(const char * name) const; + void info_set_int(const char * name,t_int64 value); + void info_set_float(const char * name,double value,unsigned precision,bool force_sign = false,const char * unit = 0); + void info_set_replaygain_track_gain(float value); + void info_set_replaygain_album_gain(float value); + void info_set_replaygain_track_peak(float value); + void info_set_replaygain_album_peak(float value); + + inline t_int64 info_get_bitrate_vbr() const {return info_get_int("bitrate_dynamic");} + inline void info_set_bitrate_vbr(t_int64 val) {info_set_int("bitrate_dynamic",val);} + inline t_int64 info_get_bitrate() const {return info_get_int("bitrate");} + inline void info_set_bitrate(t_int64 val) {info_set_int("bitrate",val);} + + void info_set_wfx_chanMask(uint32_t val); + uint32_t info_get_wfx_chanMask() const; + + bool is_encoding_lossy() const; + + + void info_calculate_bitrate(t_filesize p_filesize,double p_length); + + unsigned info_get_decoded_bps() const;//what bps the stream originally was (before converting to audio_sample), 0 if unknown + +private: + void merge(const pfc::list_base_const_t & p_sources); +public: + + void _set_tag(const file_info & tag); + void _add_tag(const file_info & otherTag); + + void merge_fallback(const file_info & fallback); + + bool are_meta_fields_identical(t_size p_index1,t_size p_index2) const; + + inline const file_info & operator=(const file_info & p_source) {copy(p_source);return *this;} + + static bool g_is_meta_equal(const file_info & p_item1,const file_info & p_item2); + static bool g_is_meta_equal_debug(const file_info & p_item1,const file_info & p_item2); + static bool g_is_info_equal(const file_info & p_item1,const file_info & p_item2); + + //! Unsafe - does not check whether the field already exists and will result in duplicates if it does - call only when appropriate checks have been applied externally. + t_size __meta_add_unsafe_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) {return meta_set_nocheck_ex(p_name,p_name_length,p_value,p_value_length);} + //! Unsafe - does not check whether the field already exists and will result in duplicates if it does - call only when appropriate checks have been applied externally. + t_size __meta_add_unsafe(const char * p_name,const char * p_value) {return meta_set_nocheck_ex(p_name,pfc_infinite,p_value,pfc_infinite);} + + //! Unsafe - does not check whether the field already exists and will result in duplicates if it does - call only when appropriate checks have been applied externally. + t_size __info_add_unsafe_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) {return info_set_nocheck_ex(p_name,p_name_length,p_value,p_value_length);} + //! Unsafe - does not check whether the field already exists and will result in duplicates if it does - call only when appropriate checks have been applied externally. + t_size __info_add_unsafe(const char * p_name,const char * p_value) {return info_set_nocheck_ex(p_name,pfc_infinite,p_value,pfc_infinite);} + + void _copy_meta_single_nocheck(const file_info & p_source,t_size p_index) {copy_meta_single_nocheck(p_source, p_index);} + + static bool g_is_valid_field_name(const char * p_name,t_size p_length = pfc_infinite); + //typedef pfc::comparator_stricmp_ascii field_name_comparator; + typedef pfc::string::comparatorCaseInsensitiveASCII field_name_comparator; + + static bool field_name_equals(const char * n1, const char * n2) {return field_name_comparator::compare(n1, n2) == 0;} + + void to_console() const; + void to_formatter(pfc::string_formatter&) const; + static bool field_is_person(const char * fieldName); + static bool field_is_title(const char * fieldName); + + void to_stream( stream_writer * stream, abort_callback & abort ) const; + void from_stream( stream_reader * stream, abort_callback & abort ); + void from_mem( const void * memPtr, size_t memSize); + + //! Returns ESTIMATED audio chunk spec from what has been put in the file_info. \n + //! Provided for convenience. Do not rely on it for processing decoded data. + audio_chunk::spec_t audio_chunk_spec() const; +protected: + file_info() {} + ~file_info() {} + void copy_meta_single_nocheck(const file_info & p_source,t_size p_index); + void copy_info_single_nocheck(const file_info & p_source,t_size p_index); + void copy_meta_single_by_name_nocheck_ex(const file_info & p_source,const char * p_name,t_size p_name_length); + void copy_info_single_by_name_nocheck_ex(const file_info & p_source,const char * p_name,t_size p_name_length); + inline void copy_meta_single_by_name_nocheck(const file_info & p_source,const char * p_name) {copy_meta_single_by_name_nocheck_ex(p_source,p_name,pfc_infinite);} + inline void copy_info_single_by_name_nocheck(const file_info & p_source,const char * p_name) {copy_info_single_by_name_nocheck_ex(p_source,p_name,pfc_infinite);} + + virtual t_size meta_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) = 0; + virtual t_size info_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) = 0; + inline t_size meta_set_nocheck(const char * p_name,const char * p_value) {return meta_set_nocheck_ex(p_name,pfc_infinite,p_value,pfc_infinite);} + inline t_size info_set_nocheck(const char * p_name,const char * p_value) {return info_set_nocheck_ex(p_name,pfc_infinite,p_value,pfc_infinite);} +}; diff --git a/SDK/foobar2000/SDK/file_info_impl.cpp b/SDK/foobar2000/SDK/file_info_impl.cpp new file mode 100644 index 0000000..a93a190 --- /dev/null +++ b/SDK/foobar2000/SDK/file_info_impl.cpp @@ -0,0 +1,243 @@ +#include "foobar2000.h" + + +t_size file_info_impl::meta_get_count() const +{ + return m_meta.get_count(); +} + +const char* file_info_impl::meta_enum_name(t_size p_index) const +{ + return m_meta.get_name(p_index); +} + +t_size file_info_impl::meta_enum_value_count(t_size p_index) const +{ + return m_meta.get_value_count(p_index); +} + +const char* file_info_impl::meta_enum_value(t_size p_index,t_size p_value_number) const +{ + return m_meta.get_value(p_index,p_value_number); +} + +t_size file_info_impl::meta_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) +{ + meta_remove_field_ex(p_name,p_name_length); + return meta_set_nocheck_ex(p_name,p_name_length,p_value,p_value_length); +} + +t_size file_info_impl::meta_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) +{ + return m_meta.add_entry(p_name,p_name_length,p_value,p_value_length); +} + +void file_info_impl::meta_insert_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length) +{ + m_meta.insert_value(p_index,p_value_index,p_value,p_value_length); +} + +void file_info_impl::meta_remove_mask(const bit_array & p_mask) +{ + m_meta.remove_mask(p_mask); +} + +void file_info_impl::meta_reorder(const t_size * p_order) +{ + m_meta.reorder(p_order); +} + +void file_info_impl::meta_remove_values(t_size p_index,const bit_array & p_mask) +{ + m_meta.remove_values(p_index,p_mask); + if (m_meta.get_value_count(p_index) == 0) + m_meta.remove_mask(bit_array_one(p_index)); +} + +t_size file_info_impl::info_get_count() const +{ + return m_info.get_count(); +} + +const char* file_info_impl::info_enum_name(t_size p_index) const +{ + return m_info.get_name(p_index); +} + +const char* file_info_impl::info_enum_value(t_size p_index) const +{ + return m_info.get_value(p_index); +} + +t_size file_info_impl::info_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) +{ + info_remove_ex(p_name,p_name_length); + return info_set_nocheck_ex(p_name,p_name_length,p_value,p_value_length); +} + +t_size file_info_impl::info_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) +{ + return m_info.add_item(p_name,p_name_length,p_value,p_value_length); +} + +void file_info_impl::info_remove_mask(const bit_array & p_mask) +{ + m_info.remove_mask(p_mask); +} + + +file_info_impl::file_info_impl(const file_info & p_source) : m_length(0) +{ + copy(p_source); +} + +file_info_impl::file_info_impl(const file_info_impl & p_source) : m_length(0) +{ + copy(p_source); +} + +const file_info_impl & file_info_impl::operator=(const file_info_impl & p_source) +{ + copy(p_source); + return *this; +} + +file_info_impl::file_info_impl() : m_length(0) +{ + m_replaygain.reset(); +} + +double file_info_impl::get_length() const +{ + return m_length; +} + +void file_info_impl::set_length(double p_length) +{ + m_length = p_length; +} + +void file_info_impl::meta_modify_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length) +{ + m_meta.modify_value(p_index,p_value_index,p_value,p_value_length); +} + +replaygain_info file_info_impl::get_replaygain() const +{ + return m_replaygain; +} + +void file_info_impl::set_replaygain(const replaygain_info & p_info) +{ + m_replaygain = p_info; +} + + + + +file_info_impl::~file_info_impl() +{ +} + +t_size file_info_impl_utils::info_storage::add_item(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) { + t_size index = m_info.get_size(); + m_info.set_size(index + 1); + m_info[index].init(p_name,p_name_length,p_value,p_value_length); + return index; +} + +void file_info_impl_utils::info_storage::remove_mask(const bit_array & p_mask) { + pfc::remove_mask_t(m_info,p_mask); +} + + + +t_size file_info_impl_utils::meta_storage::add_entry(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) +{ + meta_entry temp(p_name,p_name_length,p_value,p_value_length); + return pfc::append_swap_t(m_data,temp); +} + +void file_info_impl_utils::meta_storage::insert_value(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length) +{ + m_data[p_index].insert_value(p_value_index,p_value,p_value_length); +} + +void file_info_impl_utils::meta_storage::modify_value(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length) +{ + m_data[p_index].modify_value(p_value_index,p_value,p_value_length); +} + +void file_info_impl_utils::meta_storage::remove_values(t_size p_index,const bit_array & p_mask) +{ + m_data[p_index].remove_values(p_mask); +} + +void file_info_impl_utils::meta_storage::remove_mask(const bit_array & p_mask) +{ + pfc::remove_mask_t(m_data,p_mask); +} + + +file_info_impl_utils::meta_entry::meta_entry(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len) +{ + m_name.set_string(p_name,p_name_len); + m_values.set_size(1); + m_values[0].set_string(p_value,p_value_len); +} + + +void file_info_impl_utils::meta_entry::remove_values(const bit_array & p_mask) +{ + pfc::remove_mask_t(m_values,p_mask); +} + +void file_info_impl_utils::meta_entry::insert_value(t_size p_value_index,const char * p_value,t_size p_value_length) +{ + pfc::string_simple temp; + temp.set_string(p_value,p_value_length); + pfc::insert_t(m_values,temp,p_value_index); +} + +void file_info_impl_utils::meta_entry::modify_value(t_size p_value_index,const char * p_value,t_size p_value_length) +{ + m_values[p_value_index].set_string(p_value,p_value_length); +} + +void file_info_impl_utils::meta_storage::reorder(const t_size * p_order) +{ + pfc::reorder_t(m_data,p_order,m_data.get_size()); +} + +void file_info_impl::copy_meta(const file_info & p_source) +{ + m_meta.copy_from(p_source); +} + +void file_info_impl::copy_info(const file_info & p_source) +{ + m_info.copy_from(p_source); +} + +void file_info_impl_utils::meta_storage::copy_from(const file_info & p_info) +{ + t_size meta_index,meta_count = p_info.meta_get_count(); + m_data.set_size(meta_count); + for(meta_index=0;meta_index info_entry_array; + +} + +namespace pfc { + template<> class traits_t : public traits_t {}; +}; + + +namespace file_info_impl_utils { + class info_storage + { + public: + t_size add_item(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length); + void remove_mask(const bit_array & p_mask); + inline t_size get_count() const {return m_info.get_count();} + inline const char * get_name(t_size p_index) const {return m_info[p_index].get_name();} + inline const char * get_value(t_size p_index) const {return m_info[p_index].get_value();} + void copy_from(const file_info & p_info); + private: + info_entry_array m_info; + }; +} + + +namespace file_info_impl_utils { + typedef pfc::array_hybrid_t meta_value_array; + struct meta_entry { + meta_entry() {} + meta_entry(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len); + + void remove_values(const bit_array & p_mask); + void insert_value(t_size p_value_index,const char * p_value,t_size p_value_length); + void modify_value(t_size p_value_index,const char * p_value,t_size p_value_length); + + inline const char * get_name() const {return m_name;} + inline const char * get_value(t_size p_index) const {return m_values[p_index];} + inline t_size get_value_count() const {return m_values.get_size();} + + + pfc::string_simple m_name; + meta_value_array m_values; + }; + typedef pfc::array_hybrid_t meta_entry_array; +} +namespace pfc { + template<> class traits_t : public pfc::traits_combined {}; +} + + +namespace file_info_impl_utils { + class meta_storage + { + public: + t_size add_entry(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length); + void insert_value(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length); + void modify_value(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length); + void remove_values(t_size p_index,const bit_array & p_mask); + void remove_mask(const bit_array & p_mask); + void copy_from(const file_info & p_info); + + inline void reorder(const t_size * p_order); + + inline t_size get_count() const {return m_data.get_size();} + + inline const char * get_name(t_size p_index) const {PFC_ASSERT(p_index < m_data.get_size()); return m_data[p_index].get_name();} + inline const char * get_value(t_size p_index,t_size p_value_index) const {PFC_ASSERT(p_index < m_data.get_size()); return m_data[p_index].get_value(p_value_index);} + inline t_size get_value_count(t_size p_index) const {PFC_ASSERT(p_index < m_data.get_size()); return m_data[p_index].get_value_count();} + + private: + meta_entry_array m_data; + }; +} + +//! Implements file_info. +class file_info_impl : public file_info +{ +public: + file_info_impl(const file_info_impl & p_source); + file_info_impl(const file_info & p_source); + file_info_impl(); + ~file_info_impl(); + + double get_length() const; + void set_length(double p_length); + + void copy_meta(const file_info & p_source);//virtualized for performance reasons, can be faster in two-pass + void copy_info(const file_info & p_source);//virtualized for performance reasons, can be faster in two-pass + + t_size meta_get_count() const; + const char* meta_enum_name(t_size p_index) const; + t_size meta_enum_value_count(t_size p_index) const; + const char* meta_enum_value(t_size p_index,t_size p_value_number) const; + t_size meta_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length); + void meta_insert_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length); + void meta_remove_mask(const bit_array & p_mask); + void meta_reorder(const t_size * p_order); + void meta_remove_values(t_size p_index,const bit_array & p_mask); + void meta_modify_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length); + + t_size info_get_count() const; + const char* info_enum_name(t_size p_index) const; + const char* info_enum_value(t_size p_index) const; + t_size info_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length); + void info_remove_mask(const bit_array & p_mask); + + const file_info_impl & operator=(const file_info_impl & p_source); + + replaygain_info get_replaygain() const; + void set_replaygain(const replaygain_info & p_info); + +protected: + t_size meta_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length); + t_size info_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length); +private: + + + file_info_impl_utils::meta_storage m_meta; + file_info_impl_utils::info_storage m_info; + + + double m_length; + + replaygain_info m_replaygain; +}; + +#endif diff --git a/SDK/foobar2000/SDK/file_info_merge.cpp b/SDK/foobar2000/SDK/file_info_merge.cpp new file mode 100644 index 0000000..84b0f63 --- /dev/null +++ b/SDK/foobar2000/SDK/file_info_merge.cpp @@ -0,0 +1,171 @@ +#include "foobar2000.h" + +static t_size merge_tags_calc_rating_by_index(const file_info & p_info,t_size p_index) { + t_size n,m = p_info.meta_enum_value_count(p_index); + t_size ret = 0; + for(n=0;ninfo_get(field); + if (val) to->info_set(field,val); +} +#endif + +namespace { + struct meta_merge_entry { + meta_merge_entry() : m_rating(0) {} + t_size m_rating; + pfc::array_t m_data; + }; + + class meta_merge_map_enumerator { + public: + meta_merge_map_enumerator(file_info & p_out) : m_out(p_out) { + m_out.meta_remove_all(); + } + void operator() (const char * p_name, const meta_merge_entry & p_entry) { + if (p_entry.m_data.get_size() > 0) { + t_size index = m_out.__meta_add_unsafe(p_name,p_entry.m_data[0]); + for(t_size walk = 1; walk < p_entry.m_data.get_size(); ++walk) { + m_out.meta_add_value(index,p_entry.m_data[walk]); + } + } + } + private: + file_info & m_out; + }; +} + +static void merge_meta(file_info & p_out,const pfc::list_base_const_t & p_in) { + pfc::map_t map; + for(t_size in_walk = 0; in_walk < p_in.get_count(); in_walk++) { + const file_info & in = * p_in[in_walk]; + for(t_size meta_walk = 0, meta_count = in.meta_get_count(); meta_walk < meta_count; meta_walk++ ) { + meta_merge_entry & entry = map.find_or_add(in.meta_enum_name(meta_walk)); + t_size rating = merge_tags_calc_rating_by_index(in,meta_walk); + if (rating > entry.m_rating) { + entry.m_rating = rating; + const t_size value_count = in.meta_enum_value_count(meta_walk); + entry.m_data.set_size(value_count); + for(t_size value_walk = 0; value_walk < value_count; value_walk++ ) { + entry.m_data[value_walk] = in.meta_enum_value(meta_walk,value_walk); + } + } + } + } + + meta_merge_map_enumerator en(p_out); + map.enumerate(en); +} + +void file_info::merge(const pfc::list_base_const_t & p_in) +{ + t_size in_count = p_in.get_count(); + if (in_count == 0) + { + meta_remove_all(); + return; + } + else if (in_count == 1) + { + const file_info * info = p_in[0]; + + copy_meta(*info); + + set_replaygain(replaygain_info::g_merge(get_replaygain(),info->get_replaygain())); + + overwrite_info(*info); + + //copy_info_single_by_name(*info,"tagtype"); + + return; + } + + merge_meta(*this,p_in); + + { + pfc::string8_fastalloc tagtype; + replaygain_info rg = get_replaygain(); + t_size in_ptr; + for(in_ptr = 0; in_ptr < in_count; in_ptr++ ) + { + const file_info * info = p_in[in_ptr]; + rg = replaygain_info::g_merge(rg, info->get_replaygain()); + t_size field_ptr, field_max = info->info_get_count(); + for(field_ptr = 0; field_ptr < field_max; field_ptr++ ) + { + const char * field_name = info->info_enum_name(field_ptr), * field_value = info->info_enum_value(field_ptr); + if (*field_value) + { + if (!pfc::stricmp_ascii(field_name,"tagtype")) + { + if (!tagtype.is_empty()) tagtype += "|"; + tagtype += field_value; + } + } + } + } + if (!tagtype.is_empty()) info_set("tagtype",tagtype); + set_replaygain(rg); + } +} + +void file_info::overwrite_info(const file_info & p_source) { + t_size count = p_source.info_get_count(); + for(t_size n=0;ncopy_meta(tag); + this->set_replaygain( replaygain_info::g_merge( this->get_replaygain(), tag.get_replaygain() ) ); + const char * tt = tag.info_get(_tagtype); + if (tt) this->info_set(_tagtype, tt); +} + +void file_info::_add_tag(const file_info & otherTag) { + this->set_replaygain( replaygain_info::g_merge( this->get_replaygain(), otherTag.get_replaygain() ) ); + + const char * tt1 = this->info_get(_tagtype); + const char * tt2 = otherTag.info_get(_tagtype); + if (tt2) { + if (tt1) { + this->info_set(_tagtype, PFC_string_formatter() << tt1 << "|" << tt2); + } else { + this->info_set(_tagtype, tt2); + } + } + +} diff --git a/SDK/foobar2000/SDK/file_operation_callback.cpp b/SDK/foobar2000/SDK/file_operation_callback.cpp new file mode 100644 index 0000000..cc2a537 --- /dev/null +++ b/SDK/foobar2000/SDK/file_operation_callback.cpp @@ -0,0 +1,129 @@ +#include "foobar2000.h" + + +static void g_on_files_deleted_sorted(const pfc::list_base_const_t & p_items) +{ + //static_api_ptr_t()->on_files_deleted_sorted(p_items); + static_api_ptr_t()->on_files_deleted_sorted(p_items); + + FB2K_FOR_EACH_SERVICE(file_operation_callback, on_files_deleted_sorted(p_items)); +} + +static void g_on_files_moved_sorted(const pfc::list_base_const_t & p_from,const pfc::list_base_const_t & p_to) +{ + static_api_ptr_t()->on_files_moved_sorted(p_from,p_to); + static_api_ptr_t()->on_files_deleted_sorted(p_from); + + FB2K_FOR_EACH_SERVICE(file_operation_callback, on_files_moved_sorted(p_from,p_to)); +} + +static void g_on_files_copied_sorted(const pfc::list_base_const_t & p_from,const pfc::list_base_const_t & p_to) +{ + FB2K_FOR_EACH_SERVICE(file_operation_callback, on_files_copied_sorted(p_from,p_to)); +} + +void file_operation_callback::g_on_files_deleted(const pfc::list_base_const_t & p_items) +{ + core_api::ensure_main_thread(); + t_size count = p_items.get_count(); + if (count > 0) + { + if (count == 1) g_on_files_deleted_sorted(p_items); + else + { + pfc::array_t order; order.set_size(count); + order_helper::g_fill(order); + p_items.sort_get_permutation_t(metadb::path_compare,order.get_ptr()); + g_on_files_deleted_sorted(pfc::list_permutation_t(p_items,order.get_ptr(),count)); + } + } +} + +void file_operation_callback::g_on_files_moved(const pfc::list_base_const_t & p_from,const pfc::list_base_const_t & p_to) +{ + core_api::ensure_main_thread(); + pfc::dynamic_assert(p_from.get_count() == p_to.get_count()); + t_size count = p_from.get_count(); + if (count > 0) + { + if (count == 1) g_on_files_moved_sorted(p_from,p_to); + else + { + pfc::array_t order; order.set_size(count); + order_helper::g_fill(order); + p_from.sort_get_permutation_t(metadb::path_compare,order.get_ptr()); + g_on_files_moved_sorted(pfc::list_permutation_t(p_from,order.get_ptr(),count),pfc::list_permutation_t(p_to,order.get_ptr(),count)); + } + } +} + +void file_operation_callback::g_on_files_copied(const pfc::list_base_const_t & p_from,const pfc::list_base_const_t & p_to) +{ + if (core_api::assert_main_thread()) + { + assert(p_from.get_count() == p_to.get_count()); + t_size count = p_from.get_count(); + if (count > 0) + { + if (count == 1) g_on_files_copied_sorted(p_from,p_to); + else + { + pfc::array_t order; order.set_size(count); + order_helper::g_fill(order); + p_from.sort_get_permutation_t(metadb::path_compare,order.get_ptr()); + g_on_files_copied_sorted(pfc::list_permutation_t(p_from,order.get_ptr(),count),pfc::list_permutation_t(p_to,order.get_ptr(),count)); + } + } + } +} +bool file_operation_callback::g_search_sorted_list(const pfc::list_base_const_t & p_list,const char * p_string,t_size & p_index) { + return pfc::binarySearch::run(p_list,0,p_list.get_count(),p_string,p_index); +} + +bool file_operation_callback::g_update_list_on_moved_ex(metadb_handle_list_ref p_list,t_pathlist p_from,t_pathlist p_to, metadb_handle_list_ref itemsAdded, metadb_handle_list_ref itemsRemoved) { + static_api_ptr_t api; + bool changed = false; + itemsAdded.remove_all(); itemsRemoved.remove_all(); + for(t_size walk = 0; walk < p_list.get_count(); ++walk) { + metadb_handle_ptr item = p_list[walk]; + t_size index; + if (g_search_sorted_list(p_from,item->get_path(),index)) { + metadb_handle_ptr newItem; + api->handle_create_replace_path_canonical(newItem,item,p_to[index]); + p_list.replace_item(walk,newItem); + changed = true; + itemsAdded.add_item(newItem); itemsRemoved.add_item(item); + } + } + return changed; +} +bool file_operation_callback::g_update_list_on_moved(metadb_handle_list_ref p_list,const pfc::list_base_const_t & p_from,const pfc::list_base_const_t & p_to) { + static_api_ptr_t api; + bool changed = false; + for(t_size walk = 0; walk < p_list.get_count(); ++walk) { + metadb_handle_ptr item = p_list[walk]; + t_size index; + if (g_search_sorted_list(p_from,item->get_path(),index)) { + metadb_handle_ptr newItem; + api->handle_create_replace_path_canonical(newItem,item,p_to[index]); + p_list.replace_item(walk,newItem); + changed = true; + } + } + return changed; +} + + +bool file_operation_callback::g_mark_dead_entries(metadb_handle_list_cref items, bit_array_var & mask, t_pathlist deadPaths) { + bool found = false; + const t_size total = items.get_count(); + for(t_size walk = 0; walk < total; ++walk) { + t_size index; + if (g_search_sorted_list(deadPaths,items[walk]->get_path(),index)) { + mask.set(walk,true); found = true; + } else { + mask.set(walk,false); + } + } + return found; +} diff --git a/SDK/foobar2000/SDK/file_operation_callback.h b/SDK/foobar2000/SDK/file_operation_callback.h new file mode 100644 index 0000000..c3fccba --- /dev/null +++ b/SDK/foobar2000/SDK/file_operation_callback.h @@ -0,0 +1,66 @@ +#ifndef _FILE_OPERATION_CALLBACK_H_ +#define _FILE_OPERATION_CALLBACK_H_ + +//! Interface to notify component system about files being deleted or moved. Operates in app's main thread only. + +class NOVTABLE file_operation_callback : public service_base { +public: + typedef const pfc::list_base_const_t & t_pathlist; + //! p_items is a metadb::path_compare sorted list of files that have been deleted. + virtual void on_files_deleted_sorted(t_pathlist p_items) = 0; + //! p_from is a metadb::path_compare sorted list of files that have been moved, p_to is a list of corresponding target locations. + virtual void on_files_moved_sorted(t_pathlist p_from,t_pathlist p_to) = 0; + //! p_from is a metadb::path_compare sorted list of files that have been copied, p_to is a list of corresponding target locations. + virtual void on_files_copied_sorted(t_pathlist p_from,t_pathlist p_to) = 0; + + static void g_on_files_deleted(const pfc::list_base_const_t & p_items); + static void g_on_files_moved(const pfc::list_base_const_t & p_from,const pfc::list_base_const_t & p_to); + static void g_on_files_copied(const pfc::list_base_const_t & p_from,const pfc::list_base_const_t & p_to); + + static bool g_search_sorted_list(const pfc::list_base_const_t & p_list,const char * p_string,t_size & p_index); + static bool g_update_list_on_moved(metadb_handle_list_ref p_list,t_pathlist p_from,t_pathlist p_to); + + static bool g_update_list_on_moved_ex(metadb_handle_list_ref p_list,t_pathlist p_from,t_pathlist p_to, metadb_handle_list_ref itemsAdded, metadb_handle_list_ref itemsRemoved); + + static bool g_mark_dead_entries(metadb_handle_list_cref items, bit_array_var & mask, t_pathlist deadPaths); + + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(file_operation_callback); +}; + + + +//! New in 0.9.5. +class NOVTABLE file_operation_callback_dynamic { +public: + //! p_items is a metadb::path_compare sorted list of files that have been deleted. + virtual void on_files_deleted_sorted(const pfc::list_base_const_t & p_items) = 0; + //! p_from is a metadb::path_compare sorted list of files that have been moved, p_to is a list of corresponding target locations. + virtual void on_files_moved_sorted(const pfc::list_base_const_t & p_from,const pfc::list_base_const_t & p_to) = 0; + //! p_from is a metadb::path_compare sorted list of files that have been copied, p_to is a list of corresponding target locations. + virtual void on_files_copied_sorted(const pfc::list_base_const_t & p_from,const pfc::list_base_const_t & p_to) = 0; +}; + +//! New in 0.9.5. +class NOVTABLE file_operation_callback_dynamic_manager : public service_base { +public: + virtual void register_callback(file_operation_callback_dynamic * p_callback) = 0; + virtual void unregister_callback(file_operation_callback_dynamic * p_callback) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(file_operation_callback_dynamic_manager); +}; + +//! New in 0.9.5. +class file_operation_callback_dynamic_impl_base : public file_operation_callback_dynamic { +public: + file_operation_callback_dynamic_impl_base() {static_api_ptr_t()->register_callback(this);} + ~file_operation_callback_dynamic_impl_base() {static_api_ptr_t()->unregister_callback(this);} + + void on_files_deleted_sorted(const pfc::list_base_const_t & p_items) {} + void on_files_moved_sorted(const pfc::list_base_const_t & p_from,const pfc::list_base_const_t & p_to) {} + void on_files_copied_sorted(const pfc::list_base_const_t & p_from,const pfc::list_base_const_t & p_to) {} + + PFC_CLASS_NOT_COPYABLE_EX(file_operation_callback_dynamic_impl_base); +}; + +#endif //_FILE_OPERATION_CALLBACK_H_ diff --git a/SDK/foobar2000/SDK/filesystem.cpp b/SDK/foobar2000/SDK/filesystem.cpp new file mode 100644 index 0000000..ce7fa72 --- /dev/null +++ b/SDK/foobar2000/SDK/filesystem.cpp @@ -0,0 +1,1079 @@ +#include "foobar2000.h" + +static const char unpack_prefix[] = "unpack://"; +static const unsigned unpack_prefix_len = 9; + +void unpacker::g_open(service_ptr_t & p_out,const service_ptr_t & p,abort_callback & p_abort) +{ + service_enum_t e; + service_ptr_t ptr; + if (e.first(ptr)) do { + p->reopen(p_abort); + try { + ptr->open(p_out,p,p_abort); + return; + } catch(exception_io_data const &) {} + } while(e.next(ptr)); + throw exception_io_data(); +} + +void file::seek_probe(t_filesize p_position, abort_callback & p_abort) { + try { seek(p_position, p_abort); } catch(exception_io_seek_out_of_range) {throw exception_io_data();} +} + +void file::seek_ex(t_sfilesize p_position, file::t_seek_mode p_mode, abort_callback &p_abort) { + switch(p_mode) { + case seek_from_beginning: + seek(p_position,p_abort); + break; + case seek_from_current: + seek(p_position + get_position(p_abort),p_abort); + break; + case seek_from_eof: + seek(p_position + get_size_ex(p_abort),p_abort); + break; + default: + throw exception_io_data(); + } +} + +static void makeBuffer(pfc::array_t & buffer, size_t size) { + for(;;) {// Tolerant malloc - allocate a smaller buffer if we're unable to acquire the requested size. + try { + buffer.set_size_discard( size ); + return; + } catch(std::bad_alloc) { + if (size < 256) throw; + size >>= 1; + } + } +} + +t_filesize file::g_transfer(stream_reader * p_src,stream_writer * p_dst,t_filesize p_bytes,abort_callback & p_abort) { + pfc::array_t temp; + makeBuffer(temp, (t_size)pfc::min_t(1024*1024*8,p_bytes)); + void* ptr = temp.get_ptr(); + t_filesize done = 0; + while(done(temp.get_size(),p_bytes-done); + delta = p_src->read(ptr,delta,p_abort); + if (delta<=0) break; + p_dst->write(ptr,delta,p_abort); + done += delta; + } + return done; +} + +void file::g_transfer_object(stream_reader * p_src,stream_writer * p_dst,t_filesize p_bytes,abort_callback & p_abort) { + if (g_transfer(p_src,p_dst,p_bytes,p_abort) != p_bytes) + throw exception_io_data_truncation(); +} + + +void filesystem::g_get_canonical_path(const char * path,pfc::string_base & out) +{ + TRACK_CALL_TEXT("filesystem::g_get_canonical_path"); + + service_enum_t e; + service_ptr_t ptr; + if (e.first(ptr)) do { + if (ptr->get_canonical_path(path,out)) return; + } while(e.next(ptr)); + //no one wants to process this, let's copy over + out = path; +} + +void filesystem::g_get_display_path(const char * path,pfc::string_base & out) +{ + TRACK_CALL_TEXT("filesystem::g_get_display_path"); + service_ptr_t ptr; + if (!g_get_interface(ptr,path)) + { + //no one wants to process this, let's copy over + out = path; + } + else + { + if (!ptr->get_display_path(path,out)) + out = path; + } +} + +bool filesystem::g_get_native_path( const char * path, pfc::string_base & out) { + // Is proper file:// path? + if (foobar2000_io::extract_native_path( path, out ) ) return true; + + // Set anyway + out = path; + + // Maybe just a file:// less local path? Check for other protocol markers + // If no :// present, return true anyway + return strstr( path, "://" ) == NULL; +} + +filesystem::ptr filesystem::g_get_interface(const char * path) { + filesystem::ptr rv; + if (!g_get_interface(rv, path)) throw exception_io_no_handler_for_path(); + return rv; + +} +bool filesystem::g_get_interface(service_ptr_t & p_out,const char * path) +{ + service_enum_t e; + service_ptr_t ptr; + if (e.first(ptr)) do { + if (ptr->is_our_path(path)) + { + p_out = ptr; + return true; + } + } while(e.next(ptr)); + return false; +} + + +void filesystem::g_open(service_ptr_t & p_out,const char * path,t_open_mode mode,abort_callback & p_abort) +{ + TRACK_CALL_TEXT("filesystem::g_open"); + g_get_interface(path)->open(p_out,path,mode,p_abort); +} + + +void filesystem::g_open_timeout(service_ptr_t & p_out,const char * p_path,t_open_mode p_mode,double p_timeout,abort_callback & p_abort) { + FB2K_RETRY_ON_SHARING_VIOLATION( g_open(p_out, p_path, p_mode, p_abort), p_abort, p_timeout); +} + +bool filesystem::g_exists(const char * p_path,abort_callback & p_abort) +{ + t_filestats stats; + bool dummy; + try { + g_get_stats(p_path,stats,dummy,p_abort); + } catch(exception_io_not_found) {return false;} + return true; +} + +bool filesystem::g_exists_writeable(const char * p_path,abort_callback & p_abort) +{ + t_filestats stats; + bool writeable; + try { + g_get_stats(p_path,stats,writeable,p_abort); + } catch(exception_io_not_found) {return false;} + return writeable; +} + +void filesystem::g_remove(const char * p_path,abort_callback & p_abort) { + g_get_interface(p_path)->remove(p_path,p_abort); +} + +void filesystem::g_remove_timeout(const char * p_path,double p_timeout,abort_callback & p_abort) { + FB2K_RETRY_FILE_MOVE( g_remove(p_path, p_abort), p_abort, p_timeout ); +} + +void filesystem::g_move_timeout(const char * p_src,const char * p_dst,double p_timeout,abort_callback & p_abort) { + FB2K_RETRY_FILE_MOVE( g_move(p_src, p_dst, p_abort), p_abort, p_timeout ); +} + +void filesystem::g_copy_timeout(const char * p_src,const char * p_dst,double p_timeout,abort_callback & p_abort) { + FB2K_RETRY_FILE_MOVE( g_copy(p_src, p_dst, p_abort), p_abort, p_timeout ); +} + +void filesystem::g_create_directory(const char * p_path,abort_callback & p_abort) +{ + g_get_interface(p_path)->create_directory(p_path,p_abort); +} + +void filesystem::g_move(const char * src,const char * dst,abort_callback & p_abort) { + service_enum_t e; + service_ptr_t ptr; + if (e.first(ptr)) do { + if (ptr->is_our_path(src) && ptr->is_our_path(dst)) { + ptr->move(src,dst,p_abort); + return; + } + } while(e.next(ptr)); + throw exception_io_no_handler_for_path(); +} + +void filesystem::g_link(const char * p_src,const char * p_dst,abort_callback & p_abort) { + if (!foobar2000_io::_extract_native_path_ptr(p_src) || !foobar2000_io::_extract_native_path_ptr(p_dst)) throw exception_io_no_handler_for_path(); + WIN32_IO_OP( CreateHardLink( pfc::stringcvt::string_os_from_utf8( p_dst ), pfc::stringcvt::string_os_from_utf8( p_src ), NULL) ); +} + +void filesystem::g_link_timeout(const char * p_src,const char * p_dst,double p_timeout,abort_callback & p_abort) { + FB2K_RETRY_FILE_MOVE( g_link(p_src, p_dst, p_abort), p_abort, p_timeout ); +} + + +void filesystem::g_list_directory(const char * p_path,directory_callback & p_out,abort_callback & p_abort) +{ + TRACK_CALL_TEXT("filesystem::g_list_directory"); + g_get_interface(p_path)->list_directory(p_path,p_out,p_abort); +} + + +static void path_pack_string(pfc::string_base & out,const char * src) +{ + out.add_char('|'); + out << (unsigned) strlen(src); + out.add_char('|'); + out << src; + out.add_char('|'); +} + +static int path_unpack_string(pfc::string_base & out,const char * src) +{ + int ptr=0; + if (src[ptr++]!='|') return -1; + int len = atoi(src+ptr); + if (len<=0) return -1; + while(src[ptr]!=0 && src[ptr]!='|') ptr++; + if (src[ptr]!='|') return -1; + ptr++; + int start = ptr; + while(ptr-start & p_out,const char * p_path,abort_callback & p_abort) { + service_ptr_t fs = g_get_interface(p_path); + if (fs->is_remote(p_path)) throw exception_io_object_is_remote(); + fs->open(p_out,p_path,open_mode_read,p_abort); +} + +bool filesystem::g_is_remote(const char * p_path) { + return g_get_interface(p_path)->is_remote(p_path); +} + +bool filesystem::g_is_recognized_and_remote(const char * p_path) { + service_ptr_t fs; + if (g_get_interface(fs,p_path)) return fs->is_remote(p_path); + else return false; +} + +bool filesystem::g_is_remote_or_unrecognized(const char * p_path) { + service_ptr_t fs; + if (g_get_interface(fs,p_path)) return fs->is_remote(p_path); + else return true; +} + +bool filesystem::g_relative_path_create(const char * file_path,const char * playlist_path,pfc::string_base & out) +{ + + bool rv = false; + service_ptr_t fs; + + if (g_get_interface(fs,file_path)) + rv = fs->relative_path_create(file_path,playlist_path,out); + + return rv; +} + +bool filesystem::g_relative_path_parse(const char * relative_path,const char * playlist_path,pfc::string_base & out) +{ + service_enum_t e; + service_ptr_t ptr; + if (e.first(ptr)) do { + if (ptr->relative_path_parse(relative_path,playlist_path,out)) return true; + } while(e.next(ptr)); + return false; +} + + + +bool archive_impl::get_canonical_path(const char * path,pfc::string_base & out) +{ + if (is_our_path(path)) + { + pfc::string8 archive,file,archive_canonical; + if (g_parse_unpack_path(path,archive,file)) + { + g_get_canonical_path(archive,archive_canonical); + make_unpack_path(out,archive_canonical,file); + + return true; + } + else return false; + } + else return false; +} + +bool archive_impl::is_our_path(const char * path) +{ + if (!g_is_unpack_path(path)) return false; + const char * type = get_archive_type(); + path += 9; + while(*type) + { + if (*type!=*path) return false; + type++; + path++; + } + if (*path!='|') return false; + return true; +} + +bool archive_impl::get_display_path(const char * path,pfc::string_base & out) +{ + pfc::string8 archive,file; + if (g_parse_unpack_path(path,archive,file)) + { + g_get_display_path(archive,out); + out.add_string("|"); + out.add_string(file); + return true; + } + else return false; +} + +void archive_impl::open(service_ptr_t & p_out,const char * path,t_open_mode mode, abort_callback & p_abort) +{ + if (mode != open_mode_read) throw exception_io_denied(); + pfc::string8 archive,file; + if (!g_parse_unpack_path(path,archive,file)) throw exception_io_not_found(); + open_archive(p_out,archive,file,p_abort); +} + + +void archive_impl::remove(const char * path,abort_callback & p_abort) { + throw exception_io_denied(); +} + +void archive_impl::move(const char * src,const char * dst,abort_callback & p_abort) { + throw exception_io_denied(); +} + +bool archive_impl::is_remote(const char * src) { + pfc::string8 archive,file; + if (g_parse_unpack_path(src,archive,file)) return g_is_remote(archive); + else throw exception_io_not_found(); +} + +bool archive_impl::relative_path_create(const char * file_path,const char * playlist_path,pfc::string_base & out) { + pfc::string8 archive,file; + if (g_parse_unpack_path(file_path,archive,file)) + { + pfc::string8 archive_rel; + if (g_relative_path_create(archive,playlist_path,archive_rel)) + { + pfc::string8 out_path; + make_unpack_path(out_path,archive_rel,file); + out.set_string(out_path); + return true; + } + } + return false; +} + +bool archive_impl::relative_path_parse(const char * relative_path,const char * playlist_path,pfc::string_base & out) +{ + if (!is_our_path(relative_path)) return false; + pfc::string8 archive_rel,file; + if (g_parse_unpack_path(relative_path,archive_rel,file)) + { + pfc::string8 archive; + if (g_relative_path_parse(archive_rel,playlist_path,archive)) + { + pfc::string8 out_path; + make_unpack_path(out_path,archive,file); + out.set_string(out_path); + return true; + } + } + return false; +} + +bool archive_impl::g_parse_unpack_path_ex(const char * path,pfc::string_base & archive,pfc::string_base & file, pfc::string_base & type) { + PFC_ASSERT( g_is_unpack_path(path) ); + const char * base = path + unpack_prefix_len; // strstr(path, "//"); + const char * split = strchr(path,'|'); + if (base == NULL || split == NULL || base > split) return false; + // base += 2; + type.set_string( base, split - base ); + int delta = path_unpack_string(archive,split); + if (delta<0) return false; + split += delta; + file = split; + return true; +} +bool archive_impl::g_parse_unpack_path(const char * path,pfc::string_base & archive,pfc::string_base & file) { + PFC_ASSERT( g_is_unpack_path(path) ); + path = strchr(path,'|'); + if (!path) return false; + int delta = path_unpack_string(archive,path); + if (delta<0) return false; + path += delta; + file = path; + return true; +} + +bool archive_impl::g_is_unpack_path(const char * path) { + return strncmp(path,unpack_prefix,unpack_prefix_len) == 0; +} + +void archive_impl::g_make_unpack_path(pfc::string_base & path,const char * archive,const char * file,const char * name) +{ + path = unpack_prefix; + path += name; + path_pack_string(path,archive); + path += file; +} + +void archive_impl::make_unpack_path(pfc::string_base & path,const char * archive,const char * file) {g_make_unpack_path(path,archive,file,get_archive_type());} + + +FILE * filesystem::streamio_open(const char * path,const char * flags) +{ + FILE * ret = 0; + pfc::string8 temp; + g_get_canonical_path(path,temp); + if (!strncmp(temp,"file://",7)) + { + ret = _wfopen(pfc::stringcvt::string_wide_from_utf8(path+7),pfc::stringcvt::string_wide_from_utf8(flags)); + } + return ret; +} + + +namespace { + + class directory_callback_isempty : public directory_callback + { + bool m_isempty; + public: + directory_callback_isempty() : m_isempty(true) {} + bool on_entry(filesystem * owner,abort_callback & p_abort,const char * url,bool is_subdirectory,const t_filestats & p_stats) + { + m_isempty = false; + return false; + } + bool isempty() {return m_isempty;} + }; + + class directory_callback_dummy : public directory_callback + { + public: + bool on_entry(filesystem * owner,abort_callback & p_abort,const char * url,bool is_subdirectory,const t_filestats & p_stats) {return false;} + }; + +} + +bool filesystem::g_is_empty_directory(const char * path,abort_callback & p_abort) +{ + directory_callback_isempty callback; + try { + g_list_directory(path,callback,p_abort); + } catch(exception_io const &) {return false;} + return callback.isempty(); +} + +bool filesystem::g_is_valid_directory(const char * path,abort_callback & p_abort) { + try { + directory_callback_dummy cb; + g_list_directory(path,cb,p_abort); + return true; + } catch(exception_io const &) {return false;} +} + +bool directory_callback_impl::on_entry(filesystem * owner,abort_callback & p_abort,const char * url,bool is_subdirectory,const t_filestats & p_stats) { + p_abort.check_e(); + if (is_subdirectory) { + if (m_recur) { + try { + owner->list_directory(url,*this,p_abort); + } catch(exception_io const &) {} + } + } else { + m_data.add_item(pfc::rcnew_t(url,p_stats)); + } + return true; +} + +namespace { + class directory_callback_impl_copy : public directory_callback + { + public: + directory_callback_impl_copy(const char * p_target, filesystem::ptr fs) : m_fs(fs) + { + m_target = p_target; + m_target.fix_dir_separator('\\'); + } + + bool on_entry(filesystem * owner,abort_callback & p_abort,const char * url,bool is_subdirectory,const t_filestats & p_stats) { + const char * fn = url + pfc::scan_filename(url); + t_size truncat = m_target.length(); + m_target += fn; + if (is_subdirectory) { + try { + m_fs->create_directory(m_target,p_abort); + } catch(exception_io_already_exists) {} + m_target += "\\"; + owner->list_directory(url,*this,p_abort); + } else { + _copy(url, m_target, owner, p_abort); + } + m_target.truncate(truncat); + return true; + } + void _copy(const char * src, const char * dst, filesystem * srcFS, abort_callback & p_abort) { + service_ptr_t r_src,r_dst; + t_filesize size; + + srcFS->open(r_src,src,filesystem::open_mode_read,p_abort); + size = r_src->get_size_ex(p_abort); + m_fs->open(r_dst,dst,filesystem::open_mode_write_new,p_abort); + + if (size > 0) { + try { + file::g_transfer_object(r_src,r_dst,size,p_abort); + } catch(...) { + r_dst.release(); + abort_callback_dummy dummy; + try {m_fs->remove(dst,dummy);} catch(...) {} + throw; + } + } + } + private: + pfc::string8_fastalloc m_target; + filesystem::ptr m_fs; + }; +} + +void filesystem::copy_directory(const char * src, const char * dst, abort_callback & p_abort) { + try { + this->create_directory( dst, p_abort ); + } catch(exception_io_already_exists) {} + directory_callback_impl_copy cb(dst, this); + list_directory(src, cb, p_abort); +} + +void filesystem::g_copy_directory(const char * src,const char * dst,abort_callback & p_abort) { + filesystem::ptr dstFS = filesystem::g_get_interface(dst); + try { + dstFS->create_directory( dst, p_abort ); + } catch(exception_io_already_exists) {} + directory_callback_impl_copy cb(dst, dstFS); + g_list_directory(src,cb,p_abort); +} + +void filesystem::g_copy(const char * src,const char * dst,abort_callback & p_abort) { + service_ptr_t r_src,r_dst; + t_filesize size; + + g_open(r_src,src,open_mode_read,p_abort); + size = r_src->get_size_ex(p_abort); + g_open(r_dst,dst,open_mode_write_new,p_abort); + + if (size > 0) { + try { + file::g_transfer_object(r_src,r_dst,size,p_abort); + } catch(...) { + r_dst.release(); + abort_callback_dummy dummy; + try {g_remove(dst,dummy);} catch(...) {} + throw; + } + } +} + +void stream_reader::read_object(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + if (read(p_buffer,p_bytes,p_abort) != p_bytes) throw exception_io_data_truncation(); +} + +t_filestats file::get_stats(abort_callback & p_abort) +{ + t_filestats temp; + temp.m_size = get_size(p_abort); + temp.m_timestamp = get_timestamp(p_abort); + return temp; +} + +t_filesize stream_reader::skip(t_filesize p_bytes,abort_callback & p_abort) +{ + t_uint8 temp[256]; + t_filesize todo = p_bytes, done = 0; + while(todo > 0) { + t_size delta,deltadone; + delta = sizeof(temp); + if (delta > todo) delta = (t_size) todo; + deltadone = read(temp,delta,p_abort); + done += deltadone; + todo -= deltadone; + if (deltadone < delta) break; + } + return done; +} + +void stream_reader::skip_object(t_filesize p_bytes,abort_callback & p_abort) { + if (skip(p_bytes,p_abort) != p_bytes) throw exception_io_data_truncation(); +} + +void filesystem::g_open_write_new(service_ptr_t & p_out,const char * p_path,abort_callback & p_abort) { + g_open(p_out,p_path,open_mode_write_new,p_abort); +} +void file::g_transfer_file(const service_ptr_t & p_from,const service_ptr_t & p_to,abort_callback & p_abort) { + t_filesize length = p_from->get_size(p_abort); + p_from->reopen( p_abort ); +// p_from->seek(0,p_abort); + p_to->seek(0,p_abort); + p_to->set_eof(p_abort); + if (length == filesize_invalid) { + g_transfer(p_from, p_to, ~0, p_abort); + } else if (length > 0) { + g_transfer_object(p_from,p_to,length,p_abort); + } +} + +void filesystem::g_open_temp(service_ptr_t & p_out,abort_callback & p_abort) { + g_open(p_out,"tempfile://",open_mode_write_new,p_abort); +} + +void filesystem::g_open_tempmem(service_ptr_t & p_out,abort_callback & p_abort) { + g_open(p_out,"tempmem://",open_mode_write_new,p_abort); +} + +file::ptr filesystem::g_open_tempmem() { + abort_callback_dummy aborter; + file::ptr f; g_open_tempmem(f, aborter); return f; +} + +void archive_impl::list_directory(const char * p_path,directory_callback & p_out,abort_callback & p_abort) { + throw exception_io_not_found(); +} + +void archive_impl::create_directory(const char * path,abort_callback &) { + throw exception_io_denied(); +} + +void filesystem::g_get_stats(const char * p_path,t_filestats & p_stats,bool & p_is_writeable,abort_callback & p_abort) { + TRACK_CALL_TEXT("filesystem::g_get_stats"); + return g_get_interface(p_path)->get_stats(p_path,p_stats,p_is_writeable,p_abort); +} + +void archive_impl::get_stats(const char * p_path,t_filestats & p_stats,bool & p_is_writeable,abort_callback & p_abort) { + pfc::string8 archive,file; + if (g_parse_unpack_path(p_path,archive,file)) { + if (g_is_remote(archive)) throw exception_io_object_is_remote(); + p_is_writeable = false; + p_stats = get_stats_in_archive(archive,file,p_abort); + } + else throw exception_io_not_found(); +} + + +bool file::is_eof(abort_callback & p_abort) { + t_filesize position,size; + position = get_position(p_abort); + size = get_size(p_abort); + if (size == filesize_invalid) return false; + return position >= size; +} + + +t_filetimestamp foobar2000_io::filetimestamp_from_system_timer() +{ + return pfc::fileTimeNow(); +} + +void stream_reader::read_string_ex(pfc::string_base & p_out,t_size p_bytes,abort_callback & p_abort) { + const t_size expBase = 64*1024; + if (p_bytes > expBase) { + pfc::array_t temp; + t_size allocWalk = expBase; + t_size done = 0; + for(;;) { + const t_size target = pfc::min_t(allocWalk, p_bytes); + temp.set_size(target); + read_object(temp.get_ptr() + done, target - done, p_abort); + if (target == p_bytes) break; + done = target; + allocWalk <<= 1; + } + p_out.set_string(temp.get_ptr(), p_bytes); + } else { + pfc::string_buffer buf(p_out, p_bytes); + read_object(buf.get_ptr(),p_bytes,p_abort); + } +} +void stream_reader::read_string(pfc::string_base & p_out,abort_callback & p_abort) +{ + t_uint32 length; + read_lendian_t(length,p_abort); + read_string_ex(p_out,length,p_abort); +} + +void stream_reader::read_string_raw(pfc::string_base & p_out,abort_callback & p_abort) { + enum {delta = 256}; + char buffer[delta]; + p_out.reset(); + for(;;) { + t_size delta_done; + delta_done = read(buffer,delta,p_abort); + p_out.add_string(buffer,delta_done); + if (delta_done < delta) break; + } +} +void stream_writer::write_string(const char * p_string,t_size p_len,abort_callback & p_abort) { + t_uint32 len = pfc::downcast_guarded(pfc::strlen_max(p_string,p_len)); + write_lendian_t(len,p_abort); + write_object(p_string,len,p_abort); +} + +void stream_writer::write_string(const char * p_string,abort_callback & p_abort) { + write_string(p_string,~0,p_abort); +} + +void stream_writer::write_string_raw(const char * p_string,abort_callback & p_abort) { + write_object(p_string,strlen(p_string),p_abort); +} + +void file::truncate(t_uint64 p_position,abort_callback & p_abort) { + if (p_position < get_size(p_abort)) resize(p_position,p_abort); +} + + +#ifdef _WIN32 +namespace { + //rare/weird win32 errors that didn't make it to the main API + PFC_DECLARE_EXCEPTION(exception_io_device_not_ready, exception_io,"Device not ready"); + PFC_DECLARE_EXCEPTION(exception_io_invalid_drive, exception_io_not_found,"Drive not found"); + PFC_DECLARE_EXCEPTION(exception_io_win32, exception_io,"Generic win32 I/O error"); + PFC_DECLARE_EXCEPTION(exception_io_buffer_overflow, exception_io,"The file name is too long"); + PFC_DECLARE_EXCEPTION(exception_io_invalid_path_syntax, exception_io,"Invalid path syntax"); + + class exception_io_win32_ex : public exception_io_win32 { + public: + exception_io_win32_ex(DWORD p_code) : m_msg(pfc::string_formatter() << "I/O error (win32 #" << (t_uint32)p_code << ")") {} + exception_io_win32_ex(const exception_io_win32_ex & p_other) {*this = p_other;} + const char * what() const throw() {return m_msg;} + private: + pfc::string8 m_msg; + }; +} + +PFC_NORETURN void foobar2000_io::win32_file_write_failure(DWORD p_code, const char * path) { + if (p_code == ERROR_ACCESS_DENIED) { + const DWORD attr = uGetFileAttributes(path); + if (attr != ~0 && (attr & FILE_ATTRIBUTE_READONLY) != 0) throw exception_io_denied_readonly(); + } + exception_io_from_win32(p_code); +} + +PFC_NORETURN void foobar2000_io::exception_io_from_win32(DWORD p_code) { + //pfc::string_fixed_t<32> debugMsg; debugMsg << "Win32 I/O error #" << (t_uint32)p_code; + //TRACK_CALL_TEXT(debugMsg); + switch(p_code) { + case ERROR_ALREADY_EXISTS: + case ERROR_FILE_EXISTS: + throw exception_io_already_exists(); + case ERROR_NETWORK_ACCESS_DENIED: + case ERROR_ACCESS_DENIED: + throw exception_io_denied(); + case ERROR_WRITE_PROTECT: + throw exception_io_write_protected(); + case ERROR_BUSY: + case ERROR_PATH_BUSY: + case ERROR_SHARING_VIOLATION: + case ERROR_LOCK_VIOLATION: + throw exception_io_sharing_violation(); + case ERROR_HANDLE_DISK_FULL: + case ERROR_DISK_FULL: + throw exception_io_device_full(); + case ERROR_FILE_NOT_FOUND: + case ERROR_PATH_NOT_FOUND: + throw exception_io_not_found(); + case ERROR_BROKEN_PIPE: + case ERROR_NO_DATA: + throw exception_io_no_data(); + case ERROR_NETWORK_UNREACHABLE: + case ERROR_NETNAME_DELETED: + throw exception_io_network_not_reachable(); + case ERROR_NOT_READY: + throw exception_io_device_not_ready(); + case ERROR_INVALID_DRIVE: + throw exception_io_invalid_drive(); + case ERROR_CRC: + case ERROR_FILE_CORRUPT: + case ERROR_DISK_CORRUPT: + throw exception_io_file_corrupted(); + case ERROR_BUFFER_OVERFLOW: + throw exception_io_buffer_overflow(); + case ERROR_DISK_CHANGE: + throw exception_io_disk_change(); + case ERROR_DIR_NOT_EMPTY: + throw exception_io_directory_not_empty(); + case ERROR_INVALID_NAME: + throw exception_io_invalid_path_syntax(); + case ERROR_NO_SYSTEM_RESOURCES: + case ERROR_NONPAGED_SYSTEM_RESOURCES: + case ERROR_PAGED_SYSTEM_RESOURCES: + case ERROR_WORKING_SET_QUOTA: + case ERROR_PAGEFILE_QUOTA: + case ERROR_COMMITMENT_LIMIT: + throw exception_io("Insufficient system resources"); + case ERROR_IO_DEVICE: + throw exception_io("Device error"); + default: + throw exception_io_win32_ex(p_code); + } +} +#endif + +t_filesize file::get_size_ex(abort_callback & p_abort) { + t_filesize temp = get_size(p_abort); + if (temp == filesize_invalid) throw exception_io_no_length(); + return temp; +} + +void file::ensure_local() { + if (is_remote()) throw exception_io_object_is_remote(); +} + +void file::ensure_seekable() { + if (!can_seek()) throw exception_io_object_not_seekable(); +} + +bool filesystem::g_is_recognized_path(const char * p_path) { + filesystem::ptr obj; + return g_get_interface(obj,p_path); +} + +t_filesize file::get_remaining(abort_callback & p_abort) { + t_filesize length = get_size_ex(p_abort); + t_filesize position = get_position(p_abort); + pfc::dynamic_assert(position <= length); + return length - position; +} + +void file::probe_remaining(t_filesize bytes, abort_callback & p_abort) { + t_filesize length = get_size(p_abort); + if (length != ~0) { + t_filesize remaining = length - get_position(p_abort); + if (remaining < bytes) throw exception_io_data_truncation(); + } +} + + +t_filesize file::g_transfer(service_ptr_t p_src,service_ptr_t p_dst,t_filesize p_bytes,abort_callback & p_abort) { + return g_transfer(pfc::implicit_cast(p_src.get_ptr()),pfc::implicit_cast(p_dst.get_ptr()),p_bytes,p_abort); +} + +void file::g_transfer_object(service_ptr_t p_src,service_ptr_t p_dst,t_filesize p_bytes,abort_callback & p_abort) { + if (p_bytes > 1024) /* don't bother on small objects */ + { + t_filesize srcFileSize = p_src->get_size(p_abort); // detect truncation + if (srcFileSize != ~0) { + t_filesize remaining = srcFileSize - p_src->get_position(p_abort); + if (p_bytes > remaining) throw exception_io_data_truncation(); + } + + t_filesize oldsize = p_dst->get_size(p_abort); // pre-resize the target file + if (oldsize != filesize_invalid) { + t_filesize newpos = p_dst->get_position(p_abort) + p_bytes; + if (newpos > oldsize) p_dst->resize(newpos ,p_abort); + } + + } + g_transfer_object(pfc::implicit_cast(p_src.get_ptr()),pfc::implicit_cast(p_dst.get_ptr()),p_bytes,p_abort); +} + + +void foobar2000_io::generate_temp_location_for_file(pfc::string_base & p_out, const char * p_origpath,const char * p_extension,const char * p_magic) { + hasher_md5_result hash; + { + static_api_ptr_t hasher; + hasher_md5_state state; + hasher->initialize(state); + hasher->process(state,p_origpath,strlen(p_origpath)); + hasher->process(state,p_extension,strlen(p_extension)); + hasher->process(state,p_magic,strlen(p_magic)); + hash = hasher->get_result(state); + } + + p_out = p_origpath; + p_out.truncate(p_out.scan_filename()); + p_out += "temp-"; + p_out += pfc::format_hexdump(hash.m_data,sizeof(hash.m_data),""); + p_out += "."; + p_out += p_extension; +} + +t_filesize file::skip_seek(t_filesize p_bytes,abort_callback & p_abort) { + const t_filesize size = get_size(p_abort); + if (size != filesize_invalid) { + const t_filesize position = get_position(p_abort); + const t_filesize toskip = pfc::min_t( p_bytes, size - position ); + seek(position + toskip,p_abort); + return toskip; + } else { + this->seek_ex( p_bytes, seek_from_current, p_abort ); + return p_bytes; + } +} + +t_filesize file::skip(t_filesize p_bytes,abort_callback & p_abort) { + if (p_bytes > 1024 && can_seek()) { + const t_filesize size = get_size(p_abort); + if (size != filesize_invalid) { + const t_filesize position = get_position(p_abort); + const t_filesize toskip = pfc::min_t( p_bytes, size - position ); + seek(position + toskip,p_abort); + return toskip; + } + } + return stream_reader::skip(p_bytes,p_abort); +} + +bool foobar2000_io::is_native_filesystem( const char * p_fspath ) { + return _extract_native_path_ptr( p_fspath ); +} + +bool foobar2000_io::_extract_native_path_ptr(const char * & p_fspath) { + static const char header[] = "file://"; static const t_size headerLen = 7; + if (strncmp(p_fspath,header,headerLen) != 0) return false; + p_fspath += headerLen; + return true; +} +bool foobar2000_io::extract_native_path(const char * p_fspath,pfc::string_base & p_native) { + if (!_extract_native_path_ptr(p_fspath)) return false; + p_native = p_fspath; + return true; +} + +bool foobar2000_io::extract_native_path_ex(const char * p_fspath, pfc::string_base & p_native) { + if (!_extract_native_path_ptr(p_fspath)) return false; + if (p_fspath[0] != '\\' || p_fspath[1] != '\\') { + p_native = "\\\\?\\"; + p_native += p_fspath; + } else { + p_native = p_fspath; + } + return true; +} + +pfc::string stream_reader::read_string(abort_callback & p_abort) { + t_uint32 len; + read_lendian_t(len,p_abort); + return read_string_ex(len,p_abort); +} +pfc::string stream_reader::read_string_ex(t_size p_len,abort_callback & p_abort) { + pfc::rcptr_t temp; temp.new_t(); + read_object(temp->lock_buffer(p_len),p_len,p_abort); + temp->unlock_buffer(); + return pfc::string::t_data(temp); +} + + +void filesystem::remove_directory_content(const char * path, abort_callback & abort) { + class myCallback : public directory_callback { + public: + bool on_entry(filesystem * p_owner,abort_callback & p_abort,const char * p_url,bool p_is_subdirectory,const t_filestats & p_stats) { + if (p_is_subdirectory) p_owner->list_directory(p_url, *this, p_abort); + try { + p_owner->remove(p_url, p_abort); + } catch(exception_io_not_found) {} + return true; + } + }; + myCallback cb; + list_directory(path, cb, abort); +} +void filesystem::remove_object_recur(const char * path, abort_callback & abort) { + try { + remove_directory_content(path, abort); + } catch(exception_io_not_found) {} + remove(path, abort); +} + +void filesystem::g_remove_object_recur_timeout(const char * path, double timeout, abort_callback & abort) { + FB2K_RETRY_FILE_MOVE( g_remove_object_recur(path, abort), abort, timeout ); +} + +void filesystem::g_remove_object_recur(const char * path, abort_callback & abort) { + g_get_interface(path)->remove_object_recur(path, abort); +} + +void foobar2000_io::purgeOldFiles(const char * directory, t_filetimestamp period, abort_callback & abort) { + + class myCallback : public directory_callback { + public: + myCallback(t_filetimestamp period) : m_base(filetimestamp_from_system_timer() - period) {} + bool on_entry(filesystem * p_owner,abort_callback & p_abort,const char * p_url,bool p_is_subdirectory,const t_filestats & p_stats) { + if (!p_is_subdirectory && p_stats.m_timestamp < m_base) { + try { + filesystem::g_remove_timeout(p_url, 1, p_abort); + } catch(exception_io_not_found) {} + } + return true; + } + private: + const t_filetimestamp m_base; + }; + + myCallback cb(period); + filesystem::g_list_directory(directory, cb, abort); +} + +void stream_reader::read_string_nullterm( pfc::string_base & out, abort_callback & abort ) { + enum { bufCount = 256 }; + char buffer[bufCount]; + out.reset(); + size_t w = 0; + for(;;) { + char & c = buffer[w]; + this->read_object( &c, 1, abort ); + if (c == 0) { + out.add_string( buffer, w ); break; + } + if (++w == bufCount ) { + out.add_string( buffer, bufCount ); w = 0; + } + } +} + +t_filesize stream_reader::skip_till_eof(abort_callback & abort) { + t_filesize atOnce = 1024 * 1024; + t_filesize done = 0; + for (;; ) { + abort.check(); + t_filesize did = this->skip(atOnce, abort); + done += did; + if (did != atOnce) break; + } + return done; +} + + + +bool foobar2000_io::matchContentType(const char * fullString, const char * ourType) { + t_size lim = pfc::string_find_first(fullString, ';'); + if (lim != ~0) { + while(lim > 0 && fullString[lim-1] == ' ') --lim; + } + return pfc::stricmp_ascii_ex(fullString,lim, ourType, ~0) == 0; +} +bool foobar2000_io::matchProtocol(const char * fullString, const char * protocolName) { + const t_size len = strlen(protocolName); + if (pfc::stricmp_ascii_ex(fullString, len, protocolName, len) != 0) return false; + return fullString[len] == ':' && fullString[len+1] == '/' && fullString[len+2] == '/'; +} +void foobar2000_io::substituteProtocol(pfc::string_base & out, const char * fullString, const char * protocolName) { + const char * base = strstr(fullString, "://"); + if (base) { + out = protocolName; out << base; + } else { + PFC_ASSERT(!"Should not get here"); + out = fullString; + } +} \ No newline at end of file diff --git a/SDK/foobar2000/SDK/filesystem.h b/SDK/foobar2000/SDK/filesystem.h new file mode 100644 index 0000000..4853b47 --- /dev/null +++ b/SDK/foobar2000/SDK/filesystem.h @@ -0,0 +1,684 @@ +class file_info; + +//! Contains various I/O related structures and interfaces. + +namespace foobar2000_io +{ + //! Type used for file size related variables. + typedef t_uint64 t_filesize; + //! Type used for file size related variables when a signed value is needed. + typedef t_int64 t_sfilesize; + //! Type used for file timestamp related variables. 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601; 0 for invalid/unknown time. + typedef t_uint64 t_filetimestamp; + //! Invalid/unknown file timestamp constant. Also see: t_filetimestamp. + const t_filetimestamp filetimestamp_invalid = 0; + //! Invalid/unknown file size constant. Also see: t_filesize. + static const t_filesize filesize_invalid = (t_filesize)(~0); + + static const t_filetimestamp filetimestamp_1second_increment = 10000000; + + //! Generic I/O error. Root class for I/O failure exception. See relevant default message for description of each derived exception class. + PFC_DECLARE_EXCEPTION(exception_io, pfc::exception,"I/O error"); + //! Object not found. + PFC_DECLARE_EXCEPTION(exception_io_not_found, exception_io,"Object not found"); + //! Access denied. + PFC_DECLARE_EXCEPTION(exception_io_denied, exception_io,"Access denied"); + //! Access denied. + PFC_DECLARE_EXCEPTION(exception_io_denied_readonly, exception_io_denied,"File is read-only"); + //! Unsupported format or corrupted file (unexpected data encountered). + PFC_DECLARE_EXCEPTION(exception_io_data, exception_io,"Unsupported format or corrupted file"); + //! Unsupported format or corrupted file (truncation encountered). + PFC_DECLARE_EXCEPTION(exception_io_data_truncation, exception_io_data,"Unsupported format or corrupted file"); + //! Unsupported format (a subclass of "unsupported format or corrupted file" exception). + PFC_DECLARE_EXCEPTION(exception_io_unsupported_format, exception_io_data,"Unsupported file format"); + //! Object is remote, while specific operation is supported only for local objects. + PFC_DECLARE_EXCEPTION(exception_io_object_is_remote, exception_io,"This operation is not supported on remote objects"); + //! Sharing violation. + PFC_DECLARE_EXCEPTION(exception_io_sharing_violation, exception_io,"File is already in use"); + //! Device full. + PFC_DECLARE_EXCEPTION(exception_io_device_full, exception_io,"Device full"); + //! Attempt to seek outside valid range. + PFC_DECLARE_EXCEPTION(exception_io_seek_out_of_range, exception_io,"Seek offset out of range"); + //! This operation requires a seekable object. + PFC_DECLARE_EXCEPTION(exception_io_object_not_seekable, exception_io,"Object is not seekable"); + //! This operation requires an object with known length. + PFC_DECLARE_EXCEPTION(exception_io_no_length, exception_io,"Length of object is unknown"); + //! Invalid path. + PFC_DECLARE_EXCEPTION(exception_io_no_handler_for_path, exception_io,"Invalid path"); + //! Object already exists. + PFC_DECLARE_EXCEPTION(exception_io_already_exists, exception_io,"Object already exists"); + //! Pipe error. + PFC_DECLARE_EXCEPTION(exception_io_no_data, exception_io,"The process receiving or sending data has terminated"); + //! Network not reachable. + PFC_DECLARE_EXCEPTION(exception_io_network_not_reachable,exception_io,"Network not reachable"); + //! Media is write protected. + PFC_DECLARE_EXCEPTION(exception_io_write_protected, exception_io_denied,"The media is write protected"); + //! File is corrupted. This indicates filesystem call failure, not actual invalid data being read by the app. + PFC_DECLARE_EXCEPTION(exception_io_file_corrupted, exception_io,"The file is corrupted"); + //! The disc required for requested operation is not available. + PFC_DECLARE_EXCEPTION(exception_io_disk_change, exception_io,"Disc not available"); + //! The directory is not empty. + PFC_DECLARE_EXCEPTION(exception_io_directory_not_empty, exception_io,"Directory not empty"); + //! A network connectivity error + PFC_DECLARE_EXCEPTION( exception_io_net, exception_io, "Connection error"); + //! A network connectivity error, specifically a DNS query failure + PFC_DECLARE_EXCEPTION( exception_io_dns, exception_io_net, "DNS error"); + + + //! Stores file stats (size and timestamp). + struct t_filestats { + //! Size of the file. + t_filesize m_size; + //! Time of last file modification. + t_filetimestamp m_timestamp; + + inline bool operator==(const t_filestats & param) const {return m_size == param.m_size && m_timestamp == param.m_timestamp;} + inline bool operator!=(const t_filestats & param) const {return m_size != param.m_size || m_timestamp != param.m_timestamp;} + }; + + //! Invalid/unknown file stats constant. See: t_filestats. + static const t_filestats filestats_invalid = {filesize_invalid,filetimestamp_invalid}; + +#ifdef _WIN32 + PFC_NORETURN void exception_io_from_win32(DWORD p_code); +#define WIN32_IO_OP(X) {SetLastError(NO_ERROR); if (!(X)) exception_io_from_win32(GetLastError());} + + // SPECIAL WORKAROUND: throw "file is read-only" rather than "access denied" where appropriate + PFC_NORETURN void win32_file_write_failure(DWORD p_code, const char * path); +#endif + + //! Generic interface to read data from a nonseekable stream. Also see: stream_writer, file. \n + //! Error handling: all methods may throw exception_io or one of derivatives on failure; exception_aborted when abort_callback is signaled. + class NOVTABLE stream_reader { + public: + //! Attempts to reads specified number of bytes from the stream. + //! @param p_buffer Receives data being read. Must have at least p_bytes bytes of space allocated. + //! @param p_bytes Number of bytes to read. + //! @param p_abort abort_callback object signaling user aborting the operation. + //! @returns Number of bytes actually read. May be less than requested when EOF was reached. + virtual t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) = 0; + //! Reads specified number of bytes from the stream. If requested amount of bytes can't be read (e.g. EOF), throws exception_io_data_truncation. + //! @param p_buffer Receives data being read. Must have at least p_bytes bytes of space allocated. + //! @param p_bytes Number of bytes to read. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void read_object(void * p_buffer,t_size p_bytes,abort_callback & p_abort); + //! Attempts to skip specified number of bytes in the stream. + //! @param p_bytes Number of bytes to skip. + //! @param p_abort abort_callback object signaling user aborting the operation. + //! @returns Number of bytes actually skipped, May be less than requested when EOF was reached. + virtual t_filesize skip(t_filesize p_bytes,abort_callback & p_abort); + //! Skips specified number of bytes in the stream. If requested amount of bytes can't be skipped (e.g. EOF), throws exception_io_data_truncation. + //! @param p_bytes Number of bytes to skip. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void skip_object(t_filesize p_bytes,abort_callback & p_abort); + + //! Helper template built around read_object. Reads single raw object from the stream. + //! @param p_object Receives object read from the stream on success. + //! @param p_abort abort_callback object signaling user aborting the operation. + template inline void read_object_t(T& p_object,abort_callback & p_abort) {pfc::assert_raw_type(); read_object(&p_object,sizeof(p_object),p_abort);} + //! Helper template built around read_object. Reads single raw object from the stream; corrects byte order assuming stream uses little endian order. + //! @param p_object Receives object read from the stream on success. + //! @param p_abort abort_callback object signaling user aborting the operation. + template inline void read_lendian_t(T& p_object,abort_callback & p_abort) {read_object_t(p_object,p_abort); byte_order::order_le_to_native_t(p_object);} + //! Helper template built around read_object. Reads single raw object from the stream; corrects byte order assuming stream uses big endian order. + //! @param p_object Receives object read from the stream on success. + //! @param p_abort abort_callback object signaling user aborting the operation. + template inline void read_bendian_t(T& p_object,abort_callback & p_abort) {read_object_t(p_object,p_abort); byte_order::order_be_to_native_t(p_object);} + + //! Helper function; reads a string (with a 32-bit header indicating length in bytes followed by UTF-8 encoded data without a null terminator). + void read_string(pfc::string_base & p_out,abort_callback & p_abort); + //! Helper function; alternate way of storing strings; assumes string takes space up to end of stream. + void read_string_raw(pfc::string_base & p_out,abort_callback & p_abort); + //! Helper function; reads a string (with a 32-bit header indicating length in bytes followed by UTF-8 encoded data without a null terminator). + pfc::string read_string(abort_callback & p_abort); + + //! Helper function; reads a string of specified length from the stream. + void read_string_ex(pfc::string_base & p_out,t_size p_bytes,abort_callback & p_abort); + //! Helper function; reads a string of specified length from the stream. + pfc::string read_string_ex(t_size p_len,abort_callback & p_abort); + + void read_string_nullterm( pfc::string_base & out, abort_callback & abort ); + + t_filesize skip_till_eof(abort_callback & abort); + + template + void read_till_eof(t_outArray & out, abort_callback & abort) { + pfc::assert_raw_type(); + const t_size itemWidth = sizeof(typename t_outArray::t_item); + out.set_size(pfc::max_t(1,256 / itemWidth)); t_size done = 0; + for(;;) { + t_size delta = out.get_size() - done; + t_size delta2 = read(out.get_ptr() + done, delta * itemWidth, abort ) / itemWidth; + done += delta2; + if (delta2 != delta) break; + out.set_size(out.get_size() << 1); + } + out.set_size(done); + } + protected: + stream_reader() {} + ~stream_reader() {} + }; + + + //! Generic interface to write data to a nonseekable stream. Also see: stream_reader, file. \n + //! Error handling: all methods may throw exception_io or one of derivatives on failure; exception_aborted when abort_callback is signaled. + class NOVTABLE stream_writer { + public: + //! Writes specified number of bytes from specified buffer to the stream. + //! @param p_buffer Buffer with data to write. Must contain at least p_bytes bytes. + //! @param p_bytes Number of bytes to write. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) = 0; + + //! Helper. Same as write(), provided for consistency. + inline void write_object(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {write(p_buffer,p_bytes,p_abort);} + + //! Helper template. Writes single raw object to the stream. + //! @param p_object Object to write. + //! @param p_abort abort_callback object signaling user aborting the operation. + template inline void write_object_t(const T & p_object, abort_callback & p_abort) {pfc::assert_raw_type(); write_object(&p_object,sizeof(p_object),p_abort);} + //! Helper template. Writes single raw object to the stream; corrects byte order assuming stream uses little endian order. + //! @param p_object Object to write. + //! @param p_abort abort_callback object signaling user aborting the operation. + template inline void write_lendian_t(const T & p_object, abort_callback & p_abort) {T temp = p_object; byte_order::order_native_to_le_t(temp); write_object_t(temp,p_abort);} + //! Helper template. Writes single raw object to the stream; corrects byte order assuming stream uses big endian order. + //! @param p_object Object to write. + //! @param p_abort abort_callback object signaling user aborting the operation. + template inline void write_bendian_t(const T & p_object, abort_callback & p_abort) {T temp = p_object; byte_order::order_native_to_be_t(temp); write_object_t(temp,p_abort);} + + //! Helper function; writes string (with 32-bit header indicating length in bytes followed by UTF-8 encoded data without null terminator). + void write_string(const char * p_string,abort_callback & p_abort); + void write_string(const char * p_string,t_size p_len,abort_callback & p_abort); + + template + void write_string(const T& val,abort_callback & p_abort) {write_string(pfc::stringToPtr(val),p_abort);} + + //! Helper function; writes raw string to the stream, with no length info or null terminators. + void write_string_raw(const char * p_string,abort_callback & p_abort); + + void write_string_nullterm( const char * p_string, abort_callback & p_abort) {this->write( p_string, strlen(p_string)+1, p_abort); } + protected: + stream_writer() {} + ~stream_writer() {} + }; + + //! A class providing abstraction for an open file object, with reading/writing/seeking methods. See also: stream_reader, stream_writer (which it inherits read/write methods from). \n + //! Error handling: all methods may throw exception_io or one of derivatives on failure; exception_aborted when abort_callback is signaled. + class NOVTABLE file : public service_base, public stream_reader, public stream_writer { + public: + + //! Seeking mode constants. Note: these are purposedly defined to same values as standard C SEEK_* constants + enum t_seek_mode { + //! Seek relative to beginning of file (same as seeking to absolute offset). + seek_from_beginning = 0, + //! Seek relative to current position. + seek_from_current = 1, + //! Seek relative to end of file. + seek_from_eof = 2, + }; + + //! Retrieves size of the file. + //! @param p_abort abort_callback object signaling user aborting the operation. + //! @returns File size on success; filesize_invalid if unknown (nonseekable stream etc). + virtual t_filesize get_size(abort_callback & p_abort) = 0; + + + //! Retrieves read/write cursor position in the file. In case of non-seekable stream, this should return number of bytes read so far since open/reopen call. + //! @param p_abort abort_callback object signaling user aborting the operation. + //! @returns Read/write cursor position + virtual t_filesize get_position(abort_callback & p_abort) = 0; + + //! Resizes file to the specified size in bytes. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void resize(t_filesize p_size,abort_callback & p_abort) = 0; + + //! Sets read/write cursor position to the specified offset. Throws exception_io_seek_out_of_range if the specified offset is outside the valid range. + //! @param p_position position to seek to. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void seek(t_filesize p_position,abort_callback & p_abort) = 0; + + //! Same as seek() but throws exception_io_data instead of exception_io_seek_out_of_range. + void seek_probe(t_filesize p_position, abort_callback & p_abort); + + //! Sets read/write cursor position to the specified offset; extended form allowing seeking relative to current position or to end of file. + //! @param p_position Position to seek to; interpretation of this value depends on p_mode parameter. + //! @param p_mode Seeking mode; see t_seek_mode enum values for further description. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void seek_ex(t_sfilesize p_position,t_seek_mode p_mode,abort_callback & p_abort); + + //! Returns whether the file is seekable or not. If can_seek() returns false, all seek() or seek_ex() calls will fail; reopen() is still usable on nonseekable streams. + virtual bool can_seek() = 0; + + //! Retrieves mime type of the file. + //! @param p_out Receives content type string on success. + virtual bool get_content_type(pfc::string_base & p_out) = 0; + + //! Hint, returns whether the file is already fully buffered into memory. + virtual bool is_in_memory() {return false;} + + //! Optional, called by owner thread before sleeping. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void on_idle(abort_callback & p_abort) {} + + //! Retrieves last modification time of the file. + //! @param p_abort abort_callback object signaling user aborting the operation. + //! @returns Last modification time o fthe file; filetimestamp_invalid if N/A. + virtual t_filetimestamp get_timestamp(abort_callback & p_abort) {return filetimestamp_invalid;} + + //! Resets non-seekable stream, or seeks to zero on seekable file. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void reopen(abort_callback & p_abort) = 0; + + //! Indicates whether the file is a remote resource and non-sequential access may be slowed down by lag. This is typically returns to true on non-seekable sources but may also return true on seekable sources indicating that seeking is supported but will be relatively slow. + virtual bool is_remote() = 0; + + //! Retrieves file stats structure. Uses get_size() and get_timestamp(). + t_filestats get_stats(abort_callback & p_abort); + + //! Returns whether read/write cursor position is at the end of file. + bool is_eof(abort_callback & p_abort); + + //! Truncates file to specified size (while preserving read/write cursor position if possible); uses set_eof(). + void truncate(t_filesize p_position,abort_callback & p_abort); + + //! Truncates the file at current read/write cursor position. + void set_eof(abort_callback & p_abort) {resize(get_position(p_abort),p_abort);} + + + //! Helper; retrieves size of the file. If size is not available (get_size() returns filesize_invalid), throws exception_io_no_length. + t_filesize get_size_ex(abort_callback & p_abort); + + //! Helper; retrieves amount of bytes between read/write cursor position and end of file. Fails when length can't be determined. + t_filesize get_remaining(abort_callback & p_abort); + + //! Security helper; fails early with exception_io_data_truncation if it is not possible to read this amount of bytes from this file at this position. + void probe_remaining(t_filesize bytes, abort_callback & p_abort); + + //! Helper; throws exception_io_object_not_seekable if file is not seekable. + void ensure_seekable(); + + //! Helper; throws exception_io_object_is_remote if the file is remote. + void ensure_local(); + + //! Helper; transfers specified number of bytes between streams. + //! @returns number of bytes actually transferred. May be less than requested if e.g. EOF is reached. + static t_filesize g_transfer(stream_reader * src,stream_writer * dst,t_filesize bytes,abort_callback & p_abort); + //! Helper; transfers specified number of bytes between streams. Throws exception if requested number of bytes could not be read (EOF). + static void g_transfer_object(stream_reader * src,stream_writer * dst,t_filesize bytes,abort_callback & p_abort); + //! Helper; transfers entire file content from one file to another, erasing previous content. + static void g_transfer_file(const service_ptr_t & p_from,const service_ptr_t & p_to,abort_callback & p_abort); + + //! Helper; improved performance over g_transfer on streams (avoids disk fragmentation when transferring large blocks). + static t_filesize g_transfer(service_ptr_t p_src,service_ptr_t p_dst,t_filesize p_bytes,abort_callback & p_abort); + //! Helper; improved performance over g_transfer_file on streams (avoids disk fragmentation when transferring large blocks). + static void g_transfer_object(service_ptr_t p_src,service_ptr_t p_dst,t_filesize p_bytes,abort_callback & p_abort); + + + t_filesize skip(t_filesize p_bytes,abort_callback & p_abort); + t_filesize skip_seek(t_filesize p_bytes,abort_callback & p_abort); + + FB2K_MAKE_SERVICE_INTERFACE(file,service_base); + }; + + typedef service_ptr_t file_ptr; + + //! Extension for shoutcast dynamic metadata handling. + class file_dynamicinfo : public file { + FB2K_MAKE_SERVICE_INTERFACE(file_dynamicinfo,file); + public: + //! Retrieves "static" info that doesn't change in the middle of stream, such as station names etc. Returns true on success; false when static info is not available. + virtual bool get_static_info(class file_info & p_out) = 0; + //! Returns whether dynamic info is available on this stream or not. + virtual bool is_dynamic_info_enabled()=0; + //! Retrieves dynamic stream info (e.g. online stream track titles). Returns true on success, false when info has not changed since last call. + virtual bool get_dynamic_info(class file_info & p_out) = 0; + }; + + //! Extension for cached file access - allows callers to know that they're dealing with a cache layer, to prevent cache duplication. + class file_cached : public file { + FB2K_MAKE_SERVICE_INTERFACE(file_cached, file); + public: + virtual size_t get_cache_block_size() = 0; + virtual void suggest_grow_cache(size_t suggestSize) = 0; + + static file::ptr g_create(service_ptr_t p_base,abort_callback & p_abort, t_size blockSize); + static void g_create(service_ptr_t & p_out,service_ptr_t p_base,abort_callback & p_abort, t_size blockSize); + + static void g_decodeInitCache(file::ptr & theFile, abort_callback & abort, size_t blockSize); + }; + + //! Implementation helper - contains dummy implementations of methods that modify the file + template class file_readonly_t : public t_base { + public: + void resize(t_filesize p_size,abort_callback & p_abort) {throw exception_io_denied();} + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {throw exception_io_denied();} + }; + typedef file_readonly_t file_readonly; + + class file_streamstub : public file_readonly { + public: + t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) {return 0;} + t_filesize get_size(abort_callback & p_abort) {return filesize_invalid;} + t_filesize get_position(abort_callback & p_abort) {return 0;} + bool get_content_type(pfc::string_base & p_out) {return false;} + bool is_remote() {return true;} + void reopen(abort_callback&) {} + void seek(t_filesize p_position,abort_callback & p_abort) {throw exception_io_object_not_seekable();} + bool can_seek() {return false;} + }; + + class filesystem; + + class NOVTABLE directory_callback { + public: + //! @returns true to continue enumeration, false to abort. + virtual bool on_entry(filesystem * p_owner,abort_callback & p_abort,const char * p_url,bool p_is_subdirectory,const t_filestats & p_stats)=0; + }; + + + //! Entrypoint service for all filesystem operations.\n + //! Implementation: standard implementations for local filesystem etc are provided by core.\n + //! Instantiation: use static helper functions rather than calling filesystem interface methods directly, e.g. filesystem::g_open() to open a file. + class NOVTABLE filesystem : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(filesystem); + public: + //! Enumeration specifying how to open a file. See: filesystem::open(), filesystem::g_open(). + enum t_open_mode { + //! Opens an existing file for reading; if the file does not exist, the operation will fail. + open_mode_read, + //! Opens an existing file for writing; if the file does not exist, the operation will fail. + open_mode_write_existing, + //! Opens a new file for writing; if the file exists, its contents will be wiped. + open_mode_write_new, + }; + + virtual bool get_canonical_path(const char * p_path,pfc::string_base & p_out)=0; + virtual bool is_our_path(const char * p_path)=0; + virtual bool get_display_path(const char * p_path,pfc::string_base & p_out)=0; + + virtual void open(service_ptr_t & p_out,const char * p_path, t_open_mode p_mode,abort_callback & p_abort)=0; + virtual void remove(const char * p_path,abort_callback & p_abort)=0; + virtual void move(const char * p_src,const char * p_dst,abort_callback & p_abort)=0; + //! Queries whether a file at specified path belonging to this filesystem is a remove object or not. + virtual bool is_remote(const char * p_src) = 0; + + //! Retrieves stats of a file at specified path. + virtual void get_stats(const char * p_path,t_filestats & p_stats,bool & p_is_writeable,abort_callback & p_abort) = 0; + + virtual bool relative_path_create(const char * file_path,const char * playlist_path,pfc::string_base & out) {return false;} + virtual bool relative_path_parse(const char * relative_path,const char * playlist_path,pfc::string_base & out) {return false;} + + //! Creates a directory. + virtual void create_directory(const char * p_path,abort_callback & p_abort) = 0; + + virtual void list_directory(const char * p_path,directory_callback & p_out,abort_callback & p_abort)=0; + + //! Hint; returns whether this filesystem supports mime types. \n + //! When this returns false, all file::get_content_type() calls on files opened thru this filesystem implementation will return false; otherwise, file::get_content_type() calls may return true depending on the file. + virtual bool supports_content_types() = 0; + + static void g_get_canonical_path(const char * path,pfc::string_base & out); + static void g_get_display_path(const char * path,pfc::string_base & out); + //! Extracts the native filesystem path, sets out to the input path if native path cannot be extracted so the output is always set. + //! @returns True if native path was extracted successfully, false otherwise (but output is set anyway). + static bool g_get_native_path( const char * path, pfc::string_base & out); + + static bool g_get_interface(service_ptr_t & p_out,const char * path);//path is AFTER get_canonical_path + static filesystem::ptr g_get_interface(const char * path);// throws exception_io_no_handler_for_path on failure + static bool g_is_remote(const char * p_path);//path is AFTER get_canonical_path + static bool g_is_recognized_and_remote(const char * p_path);//path is AFTER get_canonical_path + static bool g_is_remote_safe(const char * p_path) {return g_is_recognized_and_remote(p_path);} + static bool g_is_remote_or_unrecognized(const char * p_path); + static bool g_is_recognized_path(const char * p_path); + + //! Opens file at specified path, with specified access privileges. + static void g_open(service_ptr_t & p_out,const char * p_path,t_open_mode p_mode,abort_callback & p_abort); + //! Attempts to open file at specified path; if the operation fails with sharing violation error, keeps retrying (with short sleep period between retries) for specified amount of time. + static void g_open_timeout(service_ptr_t & p_out,const char * p_path,t_open_mode p_mode,double p_timeout,abort_callback & p_abort); + static void g_open_write_new(service_ptr_t & p_out,const char * p_path,abort_callback & p_abort); + static void g_open_read(service_ptr_t & p_out,const char * path,abort_callback & p_abort) {return g_open(p_out,path,open_mode_read,p_abort);} + static void g_open_precache(service_ptr_t & p_out,const char * path,abort_callback & p_abort);//open only for precaching data (eg. will fail on http etc) + static bool g_exists(const char * p_path,abort_callback & p_abort); + static bool g_exists_writeable(const char * p_path,abort_callback & p_abort); + //! Removes file at specified path. + static void g_remove(const char * p_path,abort_callback & p_abort); + //! Attempts to remove file at specified path; if the operation fails with a sharing violation error, keeps retrying (with short sleep period between retries) for specified amount of time. + static void g_remove_timeout(const char * p_path,double p_timeout,abort_callback & p_abort); + //! Moves file from one path to another. + static void g_move(const char * p_src,const char * p_dst,abort_callback & p_abort); + //! Attempts to move file from one path to another; if the operation fails with a sharing violation error, keeps retrying (with short sleep period between retries) for specified amount of time. + static void g_move_timeout(const char * p_src,const char * p_dst,double p_timeout,abort_callback & p_abort); + + static void g_link(const char * p_src,const char * p_dst,abort_callback & p_abort); + static void g_link_timeout(const char * p_src,const char * p_dst,double p_timeout,abort_callback & p_abort); + + static void g_copy(const char * p_src,const char * p_dst,abort_callback & p_abort);//needs canonical path + static void g_copy_timeout(const char * p_src,const char * p_dst,double p_timeout,abort_callback & p_abort);//needs canonical path + static void g_copy_directory(const char * p_src,const char * p_dst,abort_callback & p_abort);//needs canonical path + static void g_get_stats(const char * p_path,t_filestats & p_stats,bool & p_is_writeable,abort_callback & p_abort); + static bool g_relative_path_create(const char * p_file_path,const char * p_playlist_path,pfc::string_base & out); + static bool g_relative_path_parse(const char * p_relative_path,const char * p_playlist_path,pfc::string_base & out); + + static void g_create_directory(const char * p_path,abort_callback & p_abort); + + //! If for some bloody reason you ever need stream io compatibility, use this, INSTEAD of calling fopen() on the path string you've got; will only work with file:// (and not with http://, unpack:// or whatever) + static FILE * streamio_open(const char * p_path,const char * p_flags); + + static void g_open_temp(service_ptr_t & p_out,abort_callback & p_abort); + static void g_open_tempmem(service_ptr_t & p_out,abort_callback & p_abort); + static file::ptr g_open_tempmem(); + + static void g_list_directory(const char * p_path,directory_callback & p_out,abort_callback & p_abort);// path must be canonical + + static bool g_is_valid_directory(const char * path,abort_callback & p_abort); + static bool g_is_empty_directory(const char * path,abort_callback & p_abort); + + void remove_object_recur(const char * path, abort_callback & abort); + void remove_directory_content(const char * path, abort_callback & abort); + static void g_remove_object_recur(const char * path, abort_callback & abort); + static void g_remove_object_recur_timeout(const char * path, double timeout, abort_callback & abort); + + // Presumes both source and destination belong to this filesystem. + void copy_directory(const char * p_src, const char * p_dst, abort_callback & p_abort); + }; + + class directory_callback_impl : public directory_callback + { + struct t_entry + { + pfc::string_simple m_path; + t_filestats m_stats; + t_entry(const char * p_path, const t_filestats & p_stats) : m_path(p_path), m_stats(p_stats) {} + }; + + + pfc::list_t > m_data; + bool m_recur; + + static int sortfunc(const pfc::rcptr_t & p1, const pfc::rcptr_t & p2) {return pfc::io::path::compare(p1->m_path,p2->m_path);} + public: + bool on_entry(filesystem * owner,abort_callback & p_abort,const char * url,bool is_subdirectory,const t_filestats & p_stats); + + directory_callback_impl(bool p_recur) : m_recur(p_recur) {} + t_size get_count() {return m_data.get_count();} + const char * operator[](t_size n) const {return m_data[n]->m_path;} + const char * get_item(t_size n) const {return m_data[n]->m_path;} + const t_filestats & get_item_stats(t_size n) const {return m_data[n]->m_stats;} + void sort() {m_data.sort_t(sortfunc);} + }; + + class archive; + + class NOVTABLE archive_callback : public abort_callback { + public: + virtual bool on_entry(archive * owner,const char * url,const t_filestats & p_stats,const service_ptr_t & p_reader) = 0; + }; + + //! Interface for archive reader services. When implementing, derive from archive_impl rather than from deriving from archive directly. + class NOVTABLE archive : public filesystem { + public: + virtual void archive_list(const char * p_path,const service_ptr_t & p_reader,archive_callback & p_callback,bool p_want_readers) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(archive,filesystem); + }; + + //! Root class for archive implementations. Derive from this instead of from archive directly. + class NOVTABLE archive_impl : public archive { + private: + //do not override these + bool get_canonical_path(const char * path,pfc::string_base & out); + bool is_our_path(const char * path); + bool get_display_path(const char * path,pfc::string_base & out); + void remove(const char * path,abort_callback & p_abort); + void move(const char * src,const char * dst,abort_callback & p_abort); + bool is_remote(const char * src); + bool relative_path_create(const char * file_path,const char * playlist_path,pfc::string_base & out); + bool relative_path_parse(const char * relative_path,const char * playlist_path,pfc::string_base & out); + void open(service_ptr_t & p_out,const char * path, t_open_mode mode,abort_callback & p_abort); + void create_directory(const char * path,abort_callback &); + void list_directory(const char * p_path,directory_callback & p_out,abort_callback & p_abort); + void get_stats(const char * p_path,t_filestats & p_stats,bool & p_is_writeable,abort_callback & p_abort); + protected: + //override these + virtual const char * get_archive_type()=0;//eg. "zip", must be lowercase + virtual t_filestats get_stats_in_archive(const char * p_archive,const char * p_file,abort_callback & p_abort) = 0; + virtual void open_archive(service_ptr_t & p_out,const char * archive,const char * file, abort_callback & p_abort)=0;//opens for reading + public: + //override these + virtual void archive_list(const char * path,const service_ptr_t & p_reader,archive_callback & p_out,bool p_want_readers)=0; + + + static bool g_is_unpack_path(const char * path); + static bool g_parse_unpack_path(const char * path,pfc::string_base & archive,pfc::string_base & file); + static bool g_parse_unpack_path_ex(const char * path,pfc::string_base & archive,pfc::string_base & file, pfc::string_base & type); + static void g_make_unpack_path(pfc::string_base & path,const char * archive,const char * file,const char * type); + void make_unpack_path(pfc::string_base & path,const char * archive,const char * file); + + + }; + + template + class archive_factory_t : public service_factory_single_t {}; + + + t_filetimestamp filetimestamp_from_system_timer(); + +#ifdef _WIN32 + inline t_filetimestamp import_filetimestamp(FILETIME ft) { + return *reinterpret_cast(&ft); + } +#endif + + void generate_temp_location_for_file(pfc::string_base & p_out, const char * p_origpath,const char * p_extension,const char * p_magic); + + + inline file_ptr fileOpen(const char * p_path,filesystem::t_open_mode p_mode,abort_callback & p_abort,double p_timeout) { + file_ptr temp; filesystem::g_open_timeout(temp,p_path,p_mode,p_timeout,p_abort); PFC_ASSERT(temp.is_valid()); return temp; + } + + inline file_ptr fileOpenReadExisting(const char * p_path,abort_callback & p_abort,double p_timeout = 0) { + return fileOpen(p_path,filesystem::open_mode_read,p_abort,p_timeout); + } + inline file_ptr fileOpenWriteExisting(const char * p_path,abort_callback & p_abort,double p_timeout = 0) { + return fileOpen(p_path,filesystem::open_mode_write_existing,p_abort,p_timeout); + } + inline file_ptr fileOpenWriteNew(const char * p_path,abort_callback & p_abort,double p_timeout = 0) { + return fileOpen(p_path,filesystem::open_mode_write_new,p_abort,p_timeout); + } + + template + class directory_callback_retrieveList : public directory_callback { + public: + directory_callback_retrieveList(t_list & p_list,bool p_getFiles,bool p_getSubDirectories) : m_list(p_list), m_getFiles(p_getFiles), m_getSubDirectories(p_getSubDirectories) {} + bool on_entry(filesystem * p_owner,abort_callback & p_abort,const char * p_url,bool p_is_subdirectory,const t_filestats & p_stats) { + p_abort.check(); + if (p_is_subdirectory ? m_getSubDirectories : m_getFiles) { + m_list.add_item(p_url); + } + return true; + } + private: + const bool m_getSubDirectories; + const bool m_getFiles; + t_list & m_list; + }; + template + class directory_callback_retrieveListEx : public directory_callback { + public: + directory_callback_retrieveListEx(t_list & p_files, t_list & p_directories) : m_files(p_files), m_directories(p_directories) {} + bool on_entry(filesystem * p_owner,abort_callback & p_abort,const char * p_url,bool p_is_subdirectory,const t_filestats & p_stats) { + p_abort.check(); + if (p_is_subdirectory) m_directories += p_url; + else m_files += p_url; + return true; + } + private: + t_list & m_files; + t_list & m_directories; + }; + template class directory_callback_retrieveListRecur : public directory_callback { + public: + directory_callback_retrieveListRecur(t_list & p_list) : m_list(p_list) {} + bool on_entry(filesystem * owner,abort_callback & p_abort,const char * path, bool isSubdir, const t_filestats&) { + if (isSubdir) { + try { owner->list_directory(path,*this,p_abort); } catch(exception_io) {} + } else { + m_list.add_item(path); + } + return true; + } + private: + t_list & m_list; + }; + + template + static void listFiles(const char * p_path,t_list & p_out,abort_callback & p_abort) { + directory_callback_retrieveList callback(p_out,true,false); + filesystem::g_list_directory(p_path,callback,p_abort); + } + template + static void listDirectories(const char * p_path,t_list & p_out,abort_callback & p_abort) { + directory_callback_retrieveList callback(p_out,false,true); + filesystem::g_list_directory(p_path,callback,p_abort); + } + template + static void listFilesAndDirectories(const char * p_path,t_list & p_files,t_list & p_directories,abort_callback & p_abort) { + directory_callback_retrieveListEx callback(p_files,p_directories); + filesystem::g_list_directory(p_path,callback,p_abort); + } + template + static void listFilesRecur(const char * p_path,t_list & p_out,abort_callback & p_abort) { + directory_callback_retrieveListRecur callback(p_out); + filesystem::g_list_directory(p_path,callback,p_abort); + } + + bool extract_native_path(const char * p_fspath,pfc::string_base & p_native); + bool _extract_native_path_ptr(const char * & p_fspath); + bool is_native_filesystem( const char * p_fspath ); + bool extract_native_path_ex(const char * p_fspath, pfc::string_base & p_native);//prepends \\?\ where needed + + template + pfc::string getPathDisplay(const T& source) { + pfc::string_formatter temp; + filesystem::g_get_display_path(pfc::stringToPtr(source),temp); + return temp.toString(); + } + template + pfc::string getPathCanonical(const T& source) { + pfc::string_formatter temp; + filesystem::g_get_canonical_path(pfc::stringToPtr(source),temp); + return temp.toString(); + } + + + bool matchContentType(const char * fullString, const char * ourType); + bool matchProtocol(const char * fullString, const char * protocolName); + void substituteProtocol(pfc::string_base & out, const char * fullString, const char * protocolName); + + void purgeOldFiles(const char * directory, t_filetimestamp period, abort_callback & abort); +} + +using namespace foobar2000_io; + +#include "filesystem_helper.h" diff --git a/SDK/foobar2000/SDK/filesystem_helper.cpp b/SDK/foobar2000/SDK/filesystem_helper.cpp new file mode 100644 index 0000000..62d0a84 --- /dev/null +++ b/SDK/foobar2000/SDK/filesystem_helper.cpp @@ -0,0 +1,222 @@ +#include "foobar2000.h" + +void stream_writer_chunk::write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + t_size remaining = p_bytes, written = 0; + while(remaining > 0) { + t_size delta = sizeof(m_buffer) - m_buffer_state; + if (delta > remaining) delta = remaining; + memcpy(m_buffer,(const t_uint8*)p_buffer + written,delta); + written += delta; + remaining -= delta; + + if (m_buffer_state == sizeof(m_buffer)) { + m_writer->write_lendian_t((t_uint8)m_buffer_state,p_abort); + m_writer->write_object(m_buffer,m_buffer_state,p_abort); + m_buffer_state = 0; + } + } +} + +void stream_writer_chunk::flush(abort_callback & p_abort) +{ + m_writer->write_lendian_t((t_uint8)m_buffer_state,p_abort); + if (m_buffer_state > 0) { + m_writer->write_object(m_buffer,m_buffer_state,p_abort); + m_buffer_state = 0; + } +} + +/* + stream_writer * m_writer; + unsigned m_buffer_state; + unsigned char m_buffer[255]; +*/ + +t_size stream_reader_chunk::read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) +{ + t_size todo = p_bytes, done = 0; + while(todo > 0) { + if (m_buffer_size == m_buffer_state) { + if (m_eof) break; + t_uint8 temp; + m_reader->read_lendian_t(temp,p_abort); + m_buffer_size = temp; + if (temp != sizeof(m_buffer)) m_eof = true; + m_buffer_state = 0; + if (m_buffer_size>0) { + m_reader->read_object(m_buffer,m_buffer_size,p_abort); + } + } + + + t_size delta = m_buffer_size - m_buffer_state; + if (delta > todo) delta = todo; + if (delta > 0) { + memcpy((unsigned char*)p_buffer + done,m_buffer + m_buffer_state,delta); + todo -= delta; + done += delta; + m_buffer_state += delta; + } + } + return done; +} + +void stream_reader_chunk::flush(abort_callback & p_abort) { + while(!m_eof) { + p_abort.check_e(); + t_uint8 temp; + m_reader->read_lendian_t(temp,p_abort); + m_buffer_size = temp; + if (temp != sizeof(m_buffer)) m_eof = true; + m_buffer_state = 0; + if (m_buffer_size>0) { + m_reader->skip_object(m_buffer_size,p_abort); + } + } +} + +/* + stream_reader * m_reader; + unsigned m_buffer_state, m_buffer_size; + bool m_eof; + unsigned char m_buffer[255]; +*/ + +void stream_reader_chunk::g_skip(stream_reader * p_stream,abort_callback & p_abort) { + stream_reader_chunk(p_stream).flush(p_abort); +} + +t_size reader_membuffer_base::read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + p_abort.check_e(); + t_size max = get_buffer_size(); + if (max < m_offset) uBugCheck(); + max -= m_offset; + t_size delta = p_bytes; + if (delta > max) delta = max; + memcpy(p_buffer,(char*)get_buffer() + m_offset,delta); + m_offset += delta; + return delta; +} + +void reader_membuffer_base::seek(t_filesize position,abort_callback & p_abort) { + p_abort.check_e(); + t_filesize max = get_buffer_size(); + if (position == filesize_invalid || position > max) throw exception_io_seek_out_of_range(); + m_offset = (t_size)position; +} + + + + +static void fileSanitySeek(file::ptr f, pfc::array_t const & content, size_t offset, abort_callback & aborter) { + const size_t readAmount = 64 * 1024; + pfc::array_staticsize_t buf; buf.set_size_discard(readAmount); + f->seek(offset, aborter); + t_filesize positionGot = f->get_position(aborter); + if (positionGot != offset) { + FB2K_console_formatter() << "File sanity: at " << offset << " reported position became " << positionGot; + throw std::runtime_error("Seek test failure"); + } + size_t did = f->read(buf.get_ptr(), readAmount, aborter); + size_t expected = pfc::min_t(readAmount, content.get_size() - offset); + if (expected != did) { + FB2K_console_formatter() << "File sanity: at " << offset << " bytes, expected read size of " << expected << ", got " << did; + if (did > expected) FB2K_console_formatter() << "Read past EOF"; + else FB2K_console_formatter() << "Premature EOF"; + throw std::runtime_error("Seek test failure"); + } + if (memcmp(buf.get_ptr(), content.get_ptr() + offset, did) != 0) { + FB2K_console_formatter() << "File sanity: data mismatch at " << offset << " - " << (offset + did) << " bytes"; + throw std::runtime_error("Seek test failure"); + } + positionGot = f->get_position(aborter); + if (positionGot != offset + did) { + FB2K_console_formatter() << "File sanity: at " << offset << "+" << did << "=" << (offset + did) << " reported position became " << positionGot; + throw std::runtime_error("Seek test failure"); + } +} + +bool fb2kFileSelfTest(file::ptr f, abort_callback & aborter) { + try { + pfc::array_t fileContent; + f->reopen(aborter); + f->read_till_eof(fileContent, aborter); + + { + t_filesize sizeClaimed = f->get_size(aborter); + if (sizeClaimed == filesize_invalid) { + FB2K_console_formatter() << "File sanity: file reports unknown size, actual size read is " << fileContent.get_size(); + } + else { + if (sizeClaimed != fileContent.get_size()) { + FB2K_console_formatter() << "File sanity: file reports size of " << sizeClaimed << ", actual size read is " << fileContent.get_size(); + throw std::runtime_error("File size mismatch"); + } + else { + FB2K_console_formatter() << "File sanity: file size check OK: " << sizeClaimed; + } + } + } + + { + FB2K_console_formatter() << "File sanity: testing N-first-bytes reads..."; + const size_t sizeUpTo = pfc::min_t(fileContent.get_size(), 1024 * 1024); + pfc::array_staticsize_t buf1; + buf1.set_size_discard(sizeUpTo); + + for (size_t w = 1; w <= sizeUpTo; w <<= 1) { + f->reopen(aborter); + size_t did = f->read(buf1.get_ptr(), w, aborter); + if (did != w) { + FB2K_console_formatter() << "File sanity: premature EOF reading first " << w << " bytes, got " << did; + throw std::runtime_error("Premature EOF"); + } + if (memcmp(fileContent.get_ptr(), buf1.get_ptr(), did) != 0) { + FB2K_console_formatter() << "File sanity: file content mismatch reading first " << w << " bytes"; + throw std::runtime_error("File content mismatch"); + } + } + } + if (f->can_seek()) { + FB2K_console_formatter() << "File sanity: testing random access..."; + + { + size_t sizeUpTo = pfc::min_t(fileContent.get_size(), 1024 * 1024); + for (size_t w = 1; w < sizeUpTo; w <<= 1) { + fileSanitySeek(f, fileContent, w, aborter); + } + fileSanitySeek(f, fileContent, fileContent.get_size(), aborter); + for (size_t w = 1; w < sizeUpTo; w <<= 1) { + fileSanitySeek(f, fileContent, fileContent.get_size() - w, aborter); + } + fileSanitySeek(f, fileContent, fileContent.get_size() / 2, aborter); + } + } + FB2K_console_formatter() << "File sanity test: all OK"; + return true; + } + catch (std::exception const & e) { + FB2K_console_formatter() << "File sanity test failure: " << e.what(); + return false; + } +} + + + +namespace { + class listDirectoryCallback : public directory_callback { + public: + bool on_entry(filesystem * p_owner,abort_callback & p_abort,const char * p_url,bool p_is_subdirectory,const t_filestats & p_stats) { + m_func( p_url, p_stats, p_is_subdirectory ); + return true; + } + listDirectoryFunc_t m_func; + }; + +} +namespace foobar2000_io { + void listDirectory( const char * path, abort_callback & aborter, listDirectoryFunc_t func) { + listDirectoryCallback cb; cb.m_func = func; + filesystem::g_list_directory(path, cb, aborter); + } +} diff --git a/SDK/foobar2000/SDK/filesystem_helper.h b/SDK/foobar2000/SDK/filesystem_helper.h new file mode 100644 index 0000000..07c1b1f --- /dev/null +++ b/SDK/foobar2000/SDK/filesystem_helper.h @@ -0,0 +1,893 @@ +#include + +namespace foobar2000_io { + typedef std::function< void (const char *, t_filestats const & , bool ) > listDirectoryFunc_t; + void listDirectory( const char * path, abort_callback & aborter, listDirectoryFunc_t func); +} + + +//helper +class file_path_canonical { +public: + file_path_canonical(const char * src) {filesystem::g_get_canonical_path(src,m_data);} + operator const char * () const {return m_data.get_ptr();} + const char * get_ptr() const {return m_data.get_ptr();} + t_size get_length() const {return m_data.get_length();} +private: + pfc::string8 m_data; +}; + +class file_path_display { +public: + file_path_display(const char * src) {filesystem::g_get_display_path(src,m_data);} + operator const char * () const {return m_data.get_ptr();} + const char * get_ptr() const {return m_data.get_ptr();} + t_size get_length() const {return m_data.get_length();} +private: + pfc::string8 m_data; +}; + + +class NOVTABLE reader_membuffer_base : public file_readonly { +public: + reader_membuffer_base() : m_offset(0) {} + + t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort); + + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {throw exception_io_denied();} + + t_filesize get_size(abort_callback & p_abort) {return get_buffer_size();} + t_filesize get_position(abort_callback & p_abort) {return m_offset;} + void seek(t_filesize position,abort_callback & p_abort); + void reopen(abort_callback & p_abort) {seek(0,p_abort);} + + bool can_seek() {return true;} + bool is_in_memory() {return true;} + +protected: + virtual const void * get_buffer() = 0; + virtual t_size get_buffer_size() = 0; + virtual t_filetimestamp get_timestamp(abort_callback & p_abort) = 0; + virtual bool get_content_type(pfc::string_base &) {return false;} + inline void seek_internal(t_size p_offset) {if (p_offset > get_buffer_size()) throw exception_io_seek_out_of_range(); m_offset = p_offset;} +private: + t_size m_offset; +}; + +class reader_membuffer_simple : public reader_membuffer_base { +public: + reader_membuffer_simple(const void * ptr, t_size size, t_filetimestamp ts = filetimestamp_invalid, bool is_remote = false) : m_isRemote(is_remote), m_ts(ts) { + m_data.set_size_discard(size); + memcpy(m_data.get_ptr(), ptr, size); + } + const void * get_buffer() {return m_data.get_ptr();} + t_size get_buffer_size() {return m_data.get_size();} + t_filetimestamp get_timestamp(abort_callback & p_abort) {return m_ts;} + bool is_remote() {return m_isRemote;} +private: + pfc::array_staticsize_t m_data; + t_filetimestamp m_ts; + bool m_isRemote; +}; + +class reader_membuffer_mirror : public reader_membuffer_base +{ +public: + t_filetimestamp get_timestamp(abort_callback & p_abort) {return m_timestamp;} + bool is_remote() {return m_remote;} + + //! Returns false when the object could not be mirrored (too big) or did not need mirroring. + static bool g_create(service_ptr_t & p_out,const service_ptr_t & p_src,abort_callback & p_abort) { + service_ptr_t ptr = new service_impl_t(); + if (!ptr->init(p_src,p_abort)) return false; + p_out = ptr.get_ptr(); + return true; + } + bool get_content_type(pfc::string_base & out) { + if (m_contentType.is_empty()) return false; + out = m_contentType; return true; + } +private: + const void * get_buffer() {return m_buffer.get_ptr();} + t_size get_buffer_size() {return m_buffer.get_size();} + + bool init(const service_ptr_t & p_src,abort_callback & p_abort) { + if (p_src->is_in_memory()) return false;//already buffered + if (!p_src->get_content_type(m_contentType)) m_contentType.reset(); + m_remote = p_src->is_remote(); + + t_size size = pfc::downcast_guarded(p_src->get_size(p_abort)); + + m_buffer.set_size(size); + + p_src->reopen(p_abort); + + p_src->read_object(m_buffer.get_ptr(),size,p_abort); + + m_timestamp = p_src->get_timestamp(p_abort); + + return true; + } + + + t_filetimestamp m_timestamp; + pfc::array_t m_buffer; + bool m_remote; + pfc::string8 m_contentType; + +}; + +class reader_limited : public file_readonly { + service_ptr_t r; + t_filesize begin; + t_filesize end; + +public: + static file::ptr g_create(file::ptr base, t_filesize offset, t_filesize size, abort_callback & abort) { + service_ptr_t r = new service_impl_t(); + if (offset + size < offset) throw pfc::exception_overflow(); + r->init(base, offset, offset + size, abort); + return r; + } + reader_limited() {begin=0;end=0;} + reader_limited(const service_ptr_t & p_r,t_filesize p_begin,t_filesize p_end,abort_callback & p_abort) { + r = p_r; + begin = p_begin; + end = p_end; + reopen(p_abort); + } + + void init(const service_ptr_t & p_r,t_filesize p_begin,t_filesize p_end,abort_callback & p_abort) { + r = p_r; + begin = p_begin; + end = p_end; + reopen(p_abort); + } + + t_filetimestamp get_timestamp(abort_callback & p_abort) {return r->get_timestamp(p_abort);} + + t_size read(void *p_buffer, t_size p_bytes,abort_callback & p_abort) { + t_filesize pos; + pos = r->get_position(p_abort); + if (p_bytes > end - pos) p_bytes = (t_size)(end - pos); + return r->read(p_buffer,p_bytes,p_abort); + } + + t_filesize get_size(abort_callback & p_abort) {return end-begin;} + + t_filesize get_position(abort_callback & p_abort) { + return r->get_position(p_abort) - begin; + } + + void seek(t_filesize position,abort_callback & p_abort) { + r->seek(position+begin,p_abort); + } + bool can_seek() {return r->can_seek();} + bool is_remote() {return r->is_remote();} + + bool get_content_type(pfc::string_base &) {return false;} + + void reopen(abort_callback & p_abort) { + seekInternal(begin, p_abort); + } +private: + void seekInternal( t_filesize position, abort_callback & abort ) { + if (r->can_seek()) { + r->seek(position, abort); + } else { + t_filesize positionWas = r->get_position(abort); + if (positionWas == filesize_invalid || positionWas > position) { + r->reopen(abort); + try { r->skip_object(position, abort); } + catch (exception_io_data) { throw exception_io_seek_out_of_range(); } + } else { + t_filesize skipMe = position - positionWas; + if (skipMe > 0) { + try { r->skip_object(skipMe, abort); } + catch (exception_io_data) { throw exception_io_seek_out_of_range(); } + } + } + } + } +}; + +class stream_reader_memblock_ref : public stream_reader +{ +public: + template stream_reader_memblock_ref(const t_array & p_array) : m_data(p_array.get_ptr()), m_data_size(p_array.get_size()), m_pointer(0) { + pfc::assert_byte_type(); + } + stream_reader_memblock_ref(const void * p_data,t_size p_data_size) : m_data((const unsigned char*)p_data), m_data_size(p_data_size), m_pointer(0) {} + stream_reader_memblock_ref() : m_data(NULL), m_data_size(0), m_pointer(0) {} + + template void set_data(const t_array & data) { + pfc::assert_byte_type(); + set_data(data.get_ptr(), data.get_size()); + } + + void set_data(const void * data, t_size dataSize) { + m_pointer = 0; + m_data = reinterpret_cast(data); + m_data_size = dataSize; + } + + t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + t_size delta = pfc::min_t(p_bytes, get_remaining()); + memcpy(p_buffer,m_data+m_pointer,delta); + m_pointer += delta; + return delta; + } + void read_object(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + if (p_bytes > get_remaining()) throw exception_io_data_truncation(); + memcpy(p_buffer,m_data+m_pointer,p_bytes); + m_pointer += p_bytes; + } + t_filesize skip(t_filesize p_bytes,abort_callback & p_abort) { + t_size remaining = get_remaining(); + if (p_bytes >= remaining) { + m_pointer = m_data_size; return remaining; + } else { + m_pointer += (t_size)p_bytes; return p_bytes; + } + } + void skip_object(t_filesize p_bytes,abort_callback & p_abort) { + if (p_bytes > get_remaining()) { + throw exception_io_data_truncation(); + } else { + m_pointer += (t_size)p_bytes; + } + } + void seek_(t_size offset) { + PFC_ASSERT( offset <= m_data_size ); + m_pointer = offset; + } + const void * get_ptr_() const {return m_data + m_pointer;} + t_size get_remaining() const {return m_data_size - m_pointer;} + void reset() {m_pointer = 0;} +private: + const unsigned char * m_data; + t_size m_data_size,m_pointer; +}; + +class stream_writer_buffer_simple : public stream_writer { +public: + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + p_abort.check(); + t_size base = m_buffer.get_size(); + if (base + p_bytes < base) throw std::bad_alloc(); + m_buffer.set_size(base + p_bytes); + memcpy( (t_uint8*) m_buffer.get_ptr() + base, p_buffer, p_bytes ); + } + + typedef pfc::array_t t_buffer; + + pfc::array_t m_buffer; +}; + +template +class stream_writer_buffer_append_ref_t : public stream_writer +{ +public: + stream_writer_buffer_append_ref_t(t_storage & p_output) : m_output(p_output) {} + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + PFC_STATIC_ASSERT( sizeof(m_output[0]) == 1 ); + p_abort.check(); + t_size base = m_output.get_size(); + if (base + p_bytes < base) throw std::bad_alloc(); + m_output.set_size(base + p_bytes); + memcpy( (t_uint8*) m_output.get_ptr() + base, p_buffer, p_bytes ); + } +private: + t_storage & m_output; +}; + +class stream_reader_limited_ref : public stream_reader { +public: + stream_reader_limited_ref(stream_reader * p_reader,t_filesize p_limit) : m_reader(p_reader), m_remaining(p_limit) {} + + t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + if (p_bytes > m_remaining) p_bytes = (t_size)m_remaining; + + t_size done = m_reader->read(p_buffer,p_bytes,p_abort); + m_remaining -= done; + return done; + } + + inline t_filesize get_remaining() const {return m_remaining;} + + t_filesize skip(t_filesize p_bytes,abort_callback & p_abort) { + if (p_bytes > m_remaining) p_bytes = m_remaining; + t_filesize done = m_reader->skip(p_bytes,p_abort); + m_remaining -= done; + return done; + } + + void flush_remaining(abort_callback & p_abort) { + if (m_remaining > 0) skip_object(m_remaining,p_abort); + } + +private: + stream_reader * m_reader; + t_filesize m_remaining; +}; + +class stream_writer_chunk_dwordheader : public stream_writer +{ +public: + stream_writer_chunk_dwordheader(const service_ptr_t & p_writer) : m_writer(p_writer) {} + + void initialize(abort_callback & p_abort) { + m_headerposition = m_writer->get_position(p_abort); + m_written = 0; + m_writer->write_lendian_t((t_uint32)0,p_abort); + } + + void finalize(abort_callback & p_abort) { + t_filesize end_offset; + end_offset = m_writer->get_position(p_abort); + m_writer->seek(m_headerposition,p_abort); + m_writer->write_lendian_t(pfc::downcast_guarded(m_written),p_abort); + m_writer->seek(end_offset,p_abort); + } + + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + m_writer->write(p_buffer,p_bytes,p_abort); + m_written += p_bytes; + } + +private: + service_ptr_t m_writer; + t_filesize m_headerposition; + t_filesize m_written; +}; + +class stream_writer_chunk : public stream_writer +{ +public: + stream_writer_chunk(stream_writer * p_writer) : m_writer(p_writer), m_buffer_state(0) {} + + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort); + + void flush(abort_callback & p_abort);//must be called after writing before object is destroyed + +private: + stream_writer * m_writer; + unsigned m_buffer_state; + unsigned char m_buffer[255]; +}; + +class stream_reader_chunk : public stream_reader +{ +public: + stream_reader_chunk(stream_reader * p_reader) : m_reader(p_reader), m_buffer_state(0), m_buffer_size(0), m_eof(false) {} + + t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort); + + void flush(abort_callback & p_abort);//must be called after reading before object is destroyed + + static void g_skip(stream_reader * p_stream,abort_callback & p_abort); + +private: + stream_reader * m_reader; + t_size m_buffer_state, m_buffer_size; + bool m_eof; + unsigned char m_buffer[255]; +}; + +class stream_reader_dummy : public stream_reader { t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) {return 0;} }; + + + + + + + + + + + + + + + + + + +template class stream_reader_formatter { +public: + stream_reader_formatter(stream_reader & p_stream,abort_callback & p_abort) : m_stream(p_stream), m_abort(p_abort) {} + + template void read_int(t_int & p_out) { + if (isBigEndian) m_stream.read_bendian_t(p_out,m_abort); + else m_stream.read_lendian_t(p_out,m_abort); + } + + void read_raw(void * p_buffer,t_size p_bytes) { + m_stream.read_object(p_buffer,p_bytes,m_abort); + } + + void skip(t_size p_bytes) {m_stream.skip_object(p_bytes,m_abort);} + + template void read_raw(TArray& data) { + pfc::assert_byte_type(); + read_raw(data.get_ptr(),data.get_size()); + } + template void read_byte_block(TArray & data) { + pfc::assert_byte_type(); + t_uint32 size; read_int(size); data.set_size(size); + read_raw(data); + } + template void read_array(TArray & data) { + t_uint32 size; *this >> size; data.set_size(size); + for(t_uint32 walk = 0; walk < size; ++walk) *this >> data[walk]; + } + void read_string_nullterm( pfc::string_base & out ) { + m_stream.read_string_nullterm( out, m_abort ); + } + stream_reader & m_stream; + abort_callback & m_abort; +}; + +template class stream_writer_formatter { +public: + stream_writer_formatter(stream_writer & p_stream,abort_callback & p_abort) : m_stream(p_stream), m_abort(p_abort) {} + + template void write_int(t_int p_int) { + if (isBigEndian) m_stream.write_bendian_t(p_int,m_abort); + else m_stream.write_lendian_t(p_int,m_abort); + } + + void write_raw(const void * p_buffer,t_size p_bytes) { + m_stream.write_object(p_buffer,p_bytes,m_abort); + } + template void write_raw(const TArray& data) { + pfc::assert_byte_type(); + write_raw(data.get_ptr(),data.get_size()); + } + + template void write_byte_block(const TArray& data) { + pfc::assert_byte_type(); + write_int( pfc::downcast_guarded(data.get_size()) ); + write_raw( data ); + } + template void write_array(const TArray& data) { + const t_uint32 size = pfc::downcast_guarded(data.get_size()); + *this << size; + for(t_uint32 walk = 0; walk < size; ++walk) *this << data[walk]; + } + + void write_string(const char * str) { + const t_size len = strlen(str); + *this << pfc::downcast_guarded(len); + write_raw(str, len); + } + void write_string(const char * str, t_size len_) { + const t_size len = pfc::strlen_max(str, len_); + *this << pfc::downcast_guarded(len); + write_raw(str, len); + } + void write_string_nullterm( const char * str ) { + this->write_raw( str, strlen(str)+1 ); + } + + stream_writer & m_stream; + abort_callback & m_abort; +}; + + +#define __DECLARE_INT_OVERLOADS(TYPE) \ + template inline stream_reader_formatter & operator>>(stream_reader_formatter & p_stream,TYPE & p_int) {typename pfc::sized_int_t::t_unsigned temp;p_stream.read_int(temp); p_int = (TYPE) temp; return p_stream;} \ + template inline stream_writer_formatter & operator<<(stream_writer_formatter & p_stream,TYPE p_int) {p_stream.write_int((typename pfc::sized_int_t::t_unsigned)p_int); return p_stream;} + +__DECLARE_INT_OVERLOADS(char); +__DECLARE_INT_OVERLOADS(signed char); +__DECLARE_INT_OVERLOADS(unsigned char); +__DECLARE_INT_OVERLOADS(signed short); +__DECLARE_INT_OVERLOADS(unsigned short); + +__DECLARE_INT_OVERLOADS(signed int); +__DECLARE_INT_OVERLOADS(unsigned int); + +__DECLARE_INT_OVERLOADS(signed long); +__DECLARE_INT_OVERLOADS(unsigned long); + +__DECLARE_INT_OVERLOADS(signed long long); +__DECLARE_INT_OVERLOADS(unsigned long long); + +__DECLARE_INT_OVERLOADS(wchar_t); + + +#undef __DECLARE_INT_OVERLOADS + +template class _IsTypeByte { +public: + enum {value = pfc::is_same_type::value || pfc::is_same_type::value || pfc::is_same_type::value}; +}; + +template stream_reader_formatter & operator>>(stream_reader_formatter & p_stream,TVal (& p_array)[Count]) { + if (_IsTypeByte::value) { + p_stream.read_raw(p_array,Count); + } else { + for(t_size walk = 0; walk < Count; ++walk) p_stream >> p_array[walk]; + } + return p_stream; +} + +template stream_writer_formatter & operator<<(stream_writer_formatter & p_stream,TVal const (& p_array)[Count]) { + if (_IsTypeByte::value) { + p_stream.write_raw(p_array,Count); + } else { + for(t_size walk = 0; walk < Count; ++walk) p_stream << p_array[walk]; + } + return p_stream; +} + +#define FB2K_STREAM_READER_OVERLOAD(type) \ + template stream_reader_formatter & operator>>(stream_reader_formatter & stream,type & value) + +#define FB2K_STREAM_WRITER_OVERLOAD(type) \ + template stream_writer_formatter & operator<<(stream_writer_formatter & stream,const type & value) + +FB2K_STREAM_READER_OVERLOAD(GUID) { + return stream >> value.Data1 >> value.Data2 >> value.Data3 >> value.Data4; +} + +FB2K_STREAM_WRITER_OVERLOAD(GUID) { + return stream << value.Data1 << value.Data2 << value.Data3 << value.Data4; +} + +FB2K_STREAM_READER_OVERLOAD(pfc::string) { + t_uint32 len; stream >> len; + value = stream.m_stream.read_string_ex(len,stream.m_abort); + return stream; +} + +FB2K_STREAM_WRITER_OVERLOAD(pfc::string) { + stream << pfc::downcast_guarded(value.length()); + stream.write_raw(value.ptr(),value.length()); + return stream; +} + +FB2K_STREAM_READER_OVERLOAD(pfc::string_base) { + stream.m_stream.read_string(value, stream.m_abort); + return stream; +} +FB2K_STREAM_WRITER_OVERLOAD(pfc::string_base) { + const char * val = value.get_ptr(); + const t_size len = strlen(val); + stream << pfc::downcast_guarded(len); + stream.write_raw(val,len); + return stream; +} + + +FB2K_STREAM_WRITER_OVERLOAD(float) { + union { + float f; t_uint32 i; + } u; u.f = value; + return stream << u.i; +} + +FB2K_STREAM_READER_OVERLOAD(float) { + union { float f; t_uint32 i;} u; + stream >> u.i; value = u.f; + return stream; +} + +FB2K_STREAM_WRITER_OVERLOAD(double) { + union { + double f; t_uint64 i; + } u; u.f = value; + return stream << u.i; +} + +FB2K_STREAM_READER_OVERLOAD(double) { + union { double f; t_uint64 i;} u; + stream >> u.i; value = u.f; + return stream; +} + +FB2K_STREAM_WRITER_OVERLOAD(bool) { + t_uint8 temp = value ? 1 : 0; + return stream << temp; +} +FB2K_STREAM_READER_OVERLOAD(bool) { + t_uint8 temp; stream >> temp; value = temp != 0; + return stream; +} + +template +class stream_writer_formatter_simple : public stream_writer_formatter { +public: + stream_writer_formatter_simple() : stream_writer_formatter(_m_stream,_m_abort), m_buffer(_m_stream.m_buffer) {} + + typedef stream_writer_buffer_simple::t_buffer t_buffer; + t_buffer & m_buffer; +private: + stream_writer_buffer_simple _m_stream; + abort_callback_dummy _m_abort; +}; + +template +class stream_reader_formatter_simple_ref : public stream_reader_formatter { +public: + stream_reader_formatter_simple_ref(const void * source, t_size sourceSize) : stream_reader_formatter(_m_stream,_m_abort), _m_stream(source,sourceSize) {} + template stream_reader_formatter_simple_ref(const TSource& source) : stream_reader_formatter(_m_stream,_m_abort), _m_stream(source) {} + stream_reader_formatter_simple_ref() : stream_reader_formatter(_m_stream,_m_abort) {} + + void set_data(const void * source, t_size sourceSize) {_m_stream.set_data(source,sourceSize);} + template void set_data(const TSource & source) {_m_stream.set_data(source);} + + void reset() {_m_stream.reset();} + t_size get_remaining() {return _m_stream.get_remaining();} + + const void * get_ptr_() const {return _m_stream.get_ptr_();} +private: + stream_reader_memblock_ref _m_stream; + abort_callback_dummy _m_abort; +}; + +template +class stream_reader_formatter_simple : public stream_reader_formatter_simple_ref { +public: + stream_reader_formatter_simple() {} + stream_reader_formatter_simple(const void * source, t_size sourceSize) {set_data(source,sourceSize);} + template stream_reader_formatter_simple(const TSource & source) {set_data(source);} + + void set_data(const void * source, t_size sourceSize) { + m_content.set_data_fromptr(reinterpret_cast(source), sourceSize); + onContentChange(); + } + template void set_data(const TSource & source) { + m_content = source; + onContentChange(); + } +private: + void onContentChange() { + stream_reader_formatter_simple_ref::set_data(m_content); + } + pfc::array_t m_content; +}; + + + + + + +template class _stream_reader_formatter_translator { +public: + _stream_reader_formatter_translator(stream_reader_formatter & stream) : m_stream(stream) {} + typedef _stream_reader_formatter_translator t_self; + template t_self & operator||(t_what & out) {m_stream >> out; return *this;} +private: + stream_reader_formatter & m_stream; +}; +template class _stream_writer_formatter_translator { +public: + _stream_writer_formatter_translator(stream_writer_formatter & stream) : m_stream(stream) {} + typedef _stream_writer_formatter_translator t_self; + template t_self & operator||(const t_what & in) {m_stream << in; return *this;} +private: + stream_writer_formatter & m_stream; +}; + +#define FB2K_STREAM_RECORD_OVERLOAD(type, code) \ + FB2K_STREAM_READER_OVERLOAD(type) { \ + _stream_reader_formatter_translator streamEx(stream); \ + streamEx || code; \ + return stream; \ + } \ + FB2K_STREAM_WRITER_OVERLOAD(type) { \ + _stream_writer_formatter_translator streamEx(stream); \ + streamEx || code; \ + return stream; \ + } + + + + +#define FB2K_RETRY_ON_EXCEPTION(OP, ABORT, TIMEOUT, EXCEPTION) \ + { \ + pfc::lores_timer timer; timer.start(); \ + for(;;) { \ + try { {OP;} break; } \ + catch(EXCEPTION) { if (timer.query() > TIMEOUT) throw;} \ + ABORT.sleep(0.05); \ + } \ + } + +#define FB2K_RETRY_ON_EXCEPTION2(OP, ABORT, TIMEOUT, EXCEPTION1, EXCEPTION2) \ + { \ + pfc::lores_timer timer; timer.start(); \ + for(;;) { \ + try { {OP;} break; } \ + catch(EXCEPTION1) { if (timer.query() > TIMEOUT) throw;} \ + catch(EXCEPTION2) { if (timer.query() > TIMEOUT) throw;} \ + ABORT.sleep(0.05); \ + } \ + } + +#define FB2K_RETRY_ON_EXCEPTION3(OP, ABORT, TIMEOUT, EXCEPTION1, EXCEPTION2, EXCEPTION3) \ + { \ + pfc::lores_timer timer; timer.start(); \ + for(;;) { \ + try { {OP;} break; } \ + catch(EXCEPTION1) { if (timer.query() > TIMEOUT) throw;} \ + catch(EXCEPTION2) { if (timer.query() > TIMEOUT) throw;} \ + catch(EXCEPTION3) { if (timer.query() > TIMEOUT) throw;} \ + ABORT.sleep(0.05); \ + } \ + } + +#define FB2K_RETRY_ON_SHARING_VIOLATION(OP, ABORT, TIMEOUT) FB2K_RETRY_ON_EXCEPTION(OP, ABORT, TIMEOUT, exception_io_sharing_violation) + +// **** WINDOWS SUCKS **** +// File move ops must be retried on all these because you get access-denied when some idiot is holding open handles to something you're trying to move, or already-exists on something you just told Windows to move away +#define FB2K_RETRY_FILE_MOVE(OP, ABORT, TIMEOUT) FB2K_RETRY_ON_EXCEPTION3(OP, ABORT, TIMEOUT, exception_io_sharing_violation, exception_io_denied, exception_io_already_exists) + +class fileRestorePositionScope { +public: + fileRestorePositionScope(file::ptr f, abort_callback & a) : m_file(f), m_abort(a) { + m_offset = f->get_position(a); + } + ~fileRestorePositionScope() { + try { + if (!m_abort.is_aborting()) m_file->seek(m_offset, m_abort); + } catch(...) {} + } +private: + file::ptr m_file; + t_filesize m_offset; + abort_callback & m_abort; +}; + + +// A more clever version of reader_membuffer_*. +// Behaves more nicely with large files within 32bit address space. +class reader_bigmem : public file_readonly { +public: + reader_bigmem() : m_offset() {} + t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + pfc::min_acc( p_bytes, remaining() ); + m_mem.read( p_buffer, p_bytes, m_offset ); + m_offset += p_bytes; + return p_bytes; + } + void read_object(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + if (p_bytes > remaining()) throw exception_io_data_truncation(); + m_mem.read( p_buffer, p_bytes, m_offset ); + m_offset += p_bytes; + } + t_filesize skip(t_filesize p_bytes,abort_callback & p_abort) { + pfc::min_acc( p_bytes, (t_filesize) remaining() ); + m_offset += (size_t) p_bytes; + return p_bytes; + } + void skip_object(t_filesize p_bytes,abort_callback & p_abort) { + if (p_bytes > remaining()) throw exception_io_data_truncation(); + m_offset += (size_t) p_bytes; + } + + t_filesize get_size(abort_callback & p_abort) {p_abort.check(); return m_mem.size();} + t_filesize get_position(abort_callback & p_abort) {p_abort.check(); return m_offset;} + void seek(t_filesize p_position,abort_callback & p_abort) { + if (p_position > m_mem.size()) throw exception_io_seek_out_of_range(); + m_offset = (size_t) p_position; + } + bool can_seek() {return true;} + bool is_in_memory() {return true;} + void reopen(abort_callback & p_abort) {seek(0, p_abort);} + + // To be overridden by individual derived classes + bool get_content_type(pfc::string_base & p_out) {return false;} + t_filetimestamp get_timestamp(abort_callback & p_abort) {return filetimestamp_invalid;} + bool is_remote() {return false;} +protected: + void resize(size_t newSize) { + m_offset = 0; + m_mem.resize( newSize ); + } + size_t remaining() const {return m_mem.size() - m_offset;} + pfc::bigmem m_mem; + size_t m_offset; +}; + +class reader_bigmem_mirror : public reader_bigmem { +public: + reader_bigmem_mirror() {} + + void init(file::ptr source, abort_callback & abort) { + source->reopen(abort); + t_filesize fs = source->get_size(abort); + if (fs > 1024*1024*1024) { // reject > 1GB + throw std::bad_alloc(); + } + size_t s = (size_t) fs; + resize(s); + for(size_t walk = 0; walk < m_mem._sliceCount(); ++walk) { + source->read( m_mem._slicePtr(walk), m_mem._sliceSize(walk), abort ); + } + + if (!source->get_content_type( m_contentType ) ) m_contentType.reset(); + m_isRemote = source->is_remote(); + m_ts = source->get_timestamp( abort ); + } + + bool get_content_type(pfc::string_base & p_out) { + if (m_contentType.is_empty()) return false; + p_out = m_contentType; return true; + } + t_filetimestamp get_timestamp(abort_callback & p_abort) {return m_ts;} + bool is_remote() {return m_isRemote;} +private: + t_filetimestamp m_ts; + pfc::string8 m_contentType; + bool m_isRemote; +}; + +class file_chain : public file { +public: + t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + return m_file->read(p_buffer, p_bytes, p_abort); + } + void read_object(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + m_file->read_object(p_buffer, p_bytes, p_abort); + } + t_filesize skip(t_filesize p_bytes,abort_callback & p_abort) { + return m_file->skip( p_bytes, p_abort ); + } + void skip_object(t_filesize p_bytes,abort_callback & p_abort) { + m_file->skip_object(p_bytes, p_abort); + } + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + m_file->write( p_buffer, p_bytes, p_abort ); + } + + t_filesize get_size(abort_callback & p_abort) { + return m_file->get_size( p_abort ); + } + + t_filesize get_position(abort_callback & p_abort) { + return m_file->get_position( p_abort ); + } + + void resize(t_filesize p_size,abort_callback & p_abort) { + m_file->resize( p_size, p_abort ); + } + + void seek(t_filesize p_position,abort_callback & p_abort) { + m_file->seek( p_position, p_abort ); + } + + void seek_ex(t_sfilesize p_position,t_seek_mode p_mode,abort_callback & p_abort) { + m_file->seek_ex( p_position, p_mode, p_abort ); + } + + bool can_seek() {return m_file->can_seek();} + bool get_content_type(pfc::string_base & p_out) {return m_file->get_content_type( p_out );} + bool is_in_memory() {return m_file->is_in_memory();} + void on_idle(abort_callback & p_abort) {m_file->on_idle(p_abort);} +#if FOOBAR2000_TARGET_VERSION >= 2000 + t_filestats get_stats(abort_callback & abort) { return m_file->get_stats(abort); } +#else + t_filetimestamp get_timestamp(abort_callback & p_abort) {return m_file->get_timestamp( p_abort );} +#endif + void reopen(abort_callback & p_abort) {m_file->reopen( p_abort );} + bool is_remote() {return m_file->is_remote();} + + file_chain( file::ptr chain ) : m_file(chain) {} +private: + file::ptr m_file; +}; + +class file_chain_readonly : public file_chain { +public: + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {throw exception_io_denied();} + void resize(t_filesize p_size,abort_callback & p_abort) {throw exception_io_denied();} + file_chain_readonly( file::ptr chain ) : file_chain(chain) {} + static file::ptr create( file::ptr chain ) { return new service_impl_t< file_chain_readonly > ( chain ); } +}; + +//! Debug self-test function for testing a file object implementation, performs various behavior validity checks, random access etc. Output goes to fb2k console. +//! Returns true on success, false on failure (buggy file object implementation). +bool fb2kFileSelfTest(file::ptr f, abort_callback & aborter); diff --git a/SDK/foobar2000/SDK/foobar2000.h b/SDK/foobar2000/SDK/foobar2000.h new file mode 100644 index 0000000..f857efa --- /dev/null +++ b/SDK/foobar2000/SDK/foobar2000.h @@ -0,0 +1,120 @@ +// This is the master foobar2000 SDK header file; it includes headers for all functionality exposed through the SDK project. #include this in your source code, never reference any of the other headers directly. + +#ifndef _FOOBAR2000_H_ +#define _FOOBAR2000_H_ + +#ifndef UNICODE +#error Only UNICODE environment supported. +#endif + +// #define FOOBAR2000_TARGET_VERSION 75 // 0.9.6 +// #define FOOBAR2000_TARGET_VERSION 76 // 1.0 +//#define FOOBAR2000_TARGET_VERSION 77 // 1.1 +#if SIZE_MAX < UINT64_MAX +#define FOOBAR2000_TARGET_VERSION 78 // 1.3 +#else +#define FOOBAR2000_TARGET_VERSION 81 // 2.0 +#endif + +#define FOOBAR2000_DESKTOP +#define FOOBAR2000_DESKTOP_WINDOWS + +#include "../../pfc/pfc.h" + +#include "../shared/shared.h" + +#ifndef NOTHROW +#ifdef _MSC_VER +#define NOTHROW __declspec(nothrow) +#else +#define NOTHROW +#endif +#endif + +#define FB2KAPI /*NOTHROW*/ + +typedef const char * pcchar; + +#include "core_api.h" +#include "service.h" + +#include "completion_notify.h" +#include "abort_callback.h" +#include "componentversion.h" +#include "preferences_page.h" +#include "coreversion.h" +#include "filesystem.h" +#include "audio_chunk.h" +#include "cfg_var.h" +#include "mem_block_container.h" +#include "audio_postprocessor.h" +#include "playable_location.h" +#include "file_info.h" +#include "file_info_impl.h" +#include "hasher_md5.h" +#include "metadb_handle.h" +#include "metadb.h" +#include "console.h" +#include "dsp.h" +#include "dsp_manager.h" +#include "initquit.h" +#include "event_logger.h" +#include "input.h" +#include "input_impl.h" +#include "decode_postprocessor.h" +#include "menu.h" +#include "contextmenu.h" +#include "contextmenu_manager.h" +#include "menu_helpers.h" +#include "modeless_dialog.h" +#include "playback_control.h" +#include "play_callback.h" +#include "playlist.h" +#include "playlist_loader.h" +#include "replaygain.h" +#include "resampler.h" +#include "tag_processor.h" +#include "titleformat.h" +#include "ui.h" +#include "unpack.h" +#include "vis.h" +#include "packet_decoder.h" +#include "commandline.h" +#include "genrand.h" +#include "file_operation_callback.h" +#include "library_manager.h" +#include "config_io_callback.h" +#include "popup_message.h" +#include "app_close_blocker.h" +#include "config_object.h" +#include "config_object_impl.h" +#include "threaded_process.h" +#include "message_loop.h" +#include "input_file_type.h" +#include "chapterizer.h" +#include "link_resolver.h" +#include "main_thread_callback.h" +#include "advconfig.h" +#include "info_lookup_handler.h" +#include "track_property.h" + +#include "album_art.h" +#include "album_art_helpers.h" +#include "icon_remap.h" +#include "ui_element.h" +#include "ole_interaction.h" +#include "search_tools.h" +#include "autoplaylist.h" +#include "replaygain_scanner.h" +#include "ui_edit_context.h" + +#include "system_time_keeper.h" +#include "playback_stream_capture.h" +#include "http_client.h" +#include "exceptions.h" + +#include "progress_meter.h" + +#include "output.h" + +#endif //_FOOBAR2000_H_ diff --git a/SDK/foobar2000/SDK/foobar2000_SDK.vcxproj b/SDK/foobar2000/SDK/foobar2000_SDK.vcxproj new file mode 100644 index 0000000..98092ca --- /dev/null +++ b/SDK/foobar2000/SDK/foobar2000_SDK.vcxproj @@ -0,0 +1,348 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {E8091321-D79D-4575-86EF-064EA1A4A20D} + foobar2000_SDK + + + + StaticLibrary + false + Unicode + true + v143 + + + StaticLibrary + false + Unicode + v143 + + + StaticLibrary + false + Unicode + true + v143 + + + StaticLibrary + false + Unicode + v143 + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(Configuration)\ + $(Configuration)\ + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + $(Configuration)\ + $(Configuration)\ + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + + + + Disabled + WIN32;_DEBUG;_WINDOWS;_WIN32_WINNT=0x501;%(PreprocessorDefinitions) + EnableFastChecks + Use + foobar2000.h + Level3 + true + ProgramDatabase + MultiThreadedDebugDLL + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + X64 + + + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + Use + foobar2000.h + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + MinSpace + WIN32;NDEBUG;_WINDOWS;_WIN32_WINNT=0x501;%(PreprocessorDefinitions) + true + false + Fast + false + Use + foobar2000.h + Level3 + true + ProgramDatabase + MultiThreadedDLL + NotSet + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + X64 + + + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + Fast + false + Use + foobar2000.h + Level3 + true + MultiThreadedDLL + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Create + Create + Create + Create + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SDK/foobar2000/SDK/foobar2000_SDK.vcxproj.filters b/SDK/foobar2000/SDK/foobar2000_SDK.vcxproj.filters new file mode 100644 index 0000000..7ee869e --- /dev/null +++ b/SDK/foobar2000/SDK/foobar2000_SDK.vcxproj.filters @@ -0,0 +1,422 @@ + + + + + {6c35c7a7-723a-401f-acdc-c63af942abae} + *.h + + + {3b2ccd60-8f0c-4241-830a-fda069a5d440} + *.cpp + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/SDK/foobar2000/SDK/foobar2000_SDK.vcxproj.user b/SDK/foobar2000/SDK/foobar2000_SDK.vcxproj.user new file mode 100644 index 0000000..0f14913 --- /dev/null +++ b/SDK/foobar2000/SDK/foobar2000_SDK.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/SDK/foobar2000/SDK/genrand.h b/SDK/foobar2000/SDK/genrand.h new file mode 100644 index 0000000..34738f8 --- /dev/null +++ b/SDK/foobar2000/SDK/genrand.h @@ -0,0 +1,22 @@ +//! PRNG service. Implemented by the core, do not reimplement. Use g_create() helper function to instantiate. +class NOVTABLE genrand_service : public service_base +{ +public: + //! Seeds the PRNG with specified value. + virtual void seed(unsigned val) = 0; + //! Returns random value N, where 0 <= N < range. + virtual unsigned genrand(unsigned range)=0; + + double genrand_f() { return (double)genrand(0xFFFFFFFF) / (double)0xFFFFFFFF; } + + static service_ptr_t g_create() {return standard_api_create_t();} + + void generate_random_order(t_size * out, t_size count) { + unsigned genrandMax = (unsigned) pfc::min_t(count, 0xFFFFFFFF); + t_size n; + for(n=0;n= 76 +FOOGUIDDECL const GUID playlist_loader::class_guid = { 0x7103cae9, 0x91c, 0x4d80, { 0xbc, 0x1d, 0x28, 0x4a, 0xc1, 0x3f, 0x1e, 0x8c } }; +FOOGUIDDECL const GUID playlist_loader_callback::class_guid = { 0x924470a0, 0x1478, 0x4141, { 0xa7, 0x5a, 0xc5, 0x2f, 0x1f, 0xfa, 0xef, 0xea } }; +FOOGUIDDECL const GUID playlist_loader_callback_v2::class_guid = { 0xcb5941bb, 0x9085, 0x4d7e, { 0x9b, 0xc2, 0x19, 0x71, 0xd3, 0x47, 0x96, 0x2a } }; +#endif + +FOOGUIDDECL const GUID album_art_manager_v2::class_guid = { 0xb420664f, 0x4033, 0x465e, { 0x81, 0xb1, 0xce, 0x42, 0x43, 0x89, 0x1f, 0x59 } }; +FOOGUIDDECL const GUID album_art_extractor_instance_v2::class_guid = { 0x951bbeb1, 0xa94a, 0x4d9a, { 0xa2, 0x85, 0xd6, 0x1e, 0xe4, 0x66, 0xe8, 0xcc } }; +FOOGUIDDECL const GUID album_art_path_list::class_guid = { 0xbb26233f, 0x1051, 0x4b01, { 0x9f, 0xd8, 0xf0, 0xe4, 0x20, 0x7, 0xd7, 0xe6 } }; +FOOGUIDDECL const GUID album_art_fallback::class_guid = { 0x45481581, 0x40b3, 0x4930, { 0xab, 0x6d, 0x4e, 0x6e, 0x56, 0x58, 0x6c, 0x82 } }; + + +FOOGUIDDECL const GUID preferences_page_callback::class_guid = { 0x3d26e08e, 0x861c, 0x4599, { 0x9c, 0x89, 0xaa, 0xa7, 0x19, 0xaf, 0x50, 0x70 } }; +FOOGUIDDECL const GUID preferences_page_instance::class_guid = { 0x6893a996, 0xa816, 0x49fe, { 0x82, 0xce, 0xc, 0xb8, 0x4, 0xa4, 0xcf, 0xec } }; +FOOGUIDDECL const GUID preferences_page_v3::class_guid = { 0xd6d0f741, 0x9f17, 0x4df8, { 0x9d, 0x5c, 0x87, 0xf2, 0x8b, 0x1f, 0xe, 0x64 } }; + +FOOGUIDDECL const GUID advconfig_entry_string_v2::class_guid = { 0x2ec9b1fa, 0xe1e4, 0x42f0, { 0x87, 0x97, 0x4a, 0x63, 0x16, 0x94, 0x86, 0xbc } }; +FOOGUIDDECL const GUID advconfig_entry_checkbox_v2::class_guid = { 0xe29b37d0, 0xa957, 0x4a85, { 0x82, 0x40, 0x1e, 0x96, 0xc7, 0x29, 0xb6, 0x69 } }; + +FOOGUIDDECL const GUID config_io_callback_v2::class_guid = { 0xfe784bf0, 0x9504, 0x4e35, { 0x85, 0xe4, 0x72, 0x53, 0x82, 0x62, 0xa1, 0x99 } }; + +FOOGUIDDECL const GUID contextmenu_item_v2::class_guid = { 0x4bd830ca, 0xe3e6, 0x404e, { 0x95, 0x44, 0xc9, 0xb7, 0xd1, 0x5a, 0x3f, 0x49 } }; +FOOGUIDDECL const GUID contextmenu_group_manager::class_guid = { 0x92ba0c5, 0x5572, 0x48cd, { 0xa4, 0xca, 0x7b, 0x73, 0xde, 0xb, 0x2a, 0xec } }; +FOOGUIDDECL const GUID contextmenu_group::class_guid = { 0x9dcfc219, 0x779, 0x4669, { 0x98, 0xc1, 0x83, 0x6d, 0xf6, 0x7, 0xc5, 0xd4 } }; +FOOGUIDDECL const GUID contextmenu_group_popup::class_guid = { 0x97636ad5, 0x5b2d, 0x4ad6, { 0x9f, 0x79, 0xc9, 0x64, 0x63, 0x88, 0xc8, 0x29 } }; + +FOOGUIDDECL const GUID contextmenu_groups::root = { 0xe6e7dc71, 0x114b, 0x4848, { 0x92, 0x8c, 0x2a, 0xdc, 0x3f, 0x86, 0xbe, 0xb4 } }; +FOOGUIDDECL const GUID contextmenu_groups::tagging = { 0xc24b5125, 0xad58, 0x4dfd, { 0x99, 0x76, 0xff, 0xbe, 0xba, 0xad, 0xc9, 0x79 } }; +FOOGUIDDECL const GUID contextmenu_groups::tagging_pictures = { 0x7ba1a031, 0xe710, 0x48dc, { 0xbb, 0x11, 0xe0, 0xbe, 0xd8, 0x33, 0x66, 0x9e } }; + +FOOGUIDDECL const GUID contextmenu_groups::utilities = { 0xfb0a55d6, 0xe693, 0x4c4a, { 0x8c, 0x62, 0xf2, 0x4e, 0xa0, 0xce, 0xf8, 0xb7 } }; +FOOGUIDDECL const GUID contextmenu_groups::replaygain = { 0x9640f207, 0x9c98, 0x47b5, { 0x85, 0x7, 0x6c, 0x9c, 0x14, 0x3e, 0x64, 0x15 } }; +FOOGUIDDECL const GUID contextmenu_groups::fileoperations = { 0x62a0e2a4, 0x251d, 0x4315, { 0x88, 0x9b, 0x1, 0x8f, 0x30, 0x8c, 0x7, 0x7a } }; +FOOGUIDDECL const GUID contextmenu_groups::convert = { 0x70429638, 0x502b, 0x466d, { 0xbf, 0x24, 0x46, 0xd, 0xae, 0x23, 0x10, 0x91 } }; +FOOGUIDDECL const GUID contextmenu_groups::playbackstatistics = { 0x12ad3123, 0xd934, 0x4241, { 0xa7, 0x1, 0x92, 0x7e, 0x87, 0x7, 0xd1, 0xdc } }; +FOOGUIDDECL const GUID contextmenu_groups::properties = { 0xb38cb9f, 0xa92d, 0x4fa4, { 0xb4, 0x58, 0x70, 0xd2, 0xfd, 0x39, 0x25, 0xba } }; +FOOGUIDDECL const GUID contextmenu_groups::legacy = { 0xbebb1711, 0x20e, 0x46ed, { 0xa7, 0xf8, 0xa3, 0x26, 0x27, 0x18, 0x4a, 0x88 } }; + +FOOGUIDDECL const GUID mainmenu_commands_v2::class_guid = { 0xe682e810, 0x41f3, 0x434d, { 0xb0, 0xc7, 0xd4, 0x96, 0x90, 0xe6, 0x5f, 0x87 } }; +FOOGUIDDECL const GUID mainmenu_node::class_guid = { 0xabba6512, 0x377d, 0x414f, { 0x81, 0x3e, 0x68, 0x6, 0xc2, 0x2d, 0x4d, 0xb1 } }; + +FOOGUIDDECL const GUID system_time_keeper::class_guid = { 0xdc5d4938, 0x7927, 0x48ba, { 0xbf, 0x84, 0xda, 0x2f, 0xb1, 0xb, 0x36, 0xf2 } }; + +FOOGUIDDECL const GUID component_installation_validator::class_guid = { 0x639283e, 0x3004, 0x4e5c, { 0xb1, 0xb3, 0x6d, 0xff, 0x8, 0xa7, 0x92, 0x84 } }; + +FOOGUIDDECL const GUID playback_stream_capture::class_guid = { 0x9423439e, 0x8cd5, 0x45d7, { 0xaa, 0x6d, 0x4b, 0x98, 0xc, 0x22, 0x93, 0x3e } }; + +FOOGUIDDECL const GUID http_request::class_guid = { 0x48580056, 0x2c5f, 0x45a8, { 0xb8, 0x6e, 0x5, 0x83, 0x55, 0x3e, 0xaa, 0x4f } }; +FOOGUIDDECL const GUID http_request_post::class_guid = { 0xe254b804, 0xeac5, 0x4be0, { 0x99, 0x4d, 0x53, 0x1c, 0x17, 0xea, 0xfd, 0x37 } }; +FOOGUIDDECL const GUID http_client::class_guid = { 0x3b5ffe0c, 0xd75a, 0x491e, { 0xbb, 0x6f, 0x10, 0x3f, 0x73, 0x1e, 0x81, 0x84 } }; +FOOGUIDDECL const GUID http_reply::class_guid = { 0x7f02bf78, 0x5c98, 0x4d6d, { 0x83, 0x6b, 0xb7, 0x77, 0xa4, 0xa3, 0x3e, 0xe5 } }; + +FOOGUIDDECL const GUID popup_message_v2::class_guid = { 0x18b74f55, 0x10e1, 0x4645, { 0x91, 0xf6, 0xb0, 0xe0, 0x4c, 0x28, 0x21, 0xe9 } }; +FOOGUIDDECL const GUID metadb_index_client::class_guid = { 0x52637e7d, 0x7f3, 0x49bf, { 0x90, 0x19, 0x36, 0x20, 0x83, 0xcc, 0x7e, 0x59 } }; +FOOGUIDDECL const GUID metadb_index_manager::class_guid = { 0xb9633863, 0x2683, 0x4163, { 0xa5, 0x8d, 0x26, 0x47, 0x5d, 0xb0, 0xe7, 0x9b } }; +FOOGUIDDECL const GUID init_stage_callback::class_guid = { 0xaf51c159, 0x6326, 0x4da5, { 0x90, 0xb0, 0xf1, 0x1f, 0x99, 0x64, 0xcc, 0x2e } }; +FOOGUIDDECL const GUID metadb_io_edit_callback::class_guid = { 0x2388a50f, 0x33d, 0x4b7c, { 0x91, 0xf2, 0x51, 0x53, 0x69, 0x43, 0xe9, 0xed } }; +FOOGUIDDECL const GUID decode_postprocessor_entry::class_guid = { 0xb105c345, 0xf642, 0x4a26, { 0xa7, 0x80, 0xbb, 0x90, 0xe1, 0xb4, 0xac, 0xb1 } }; +FOOGUIDDECL const GUID decode_postprocessor_instance::class_guid = { 0xfacabec0, 0xeeee, 0x46d1, { 0xa5, 0x39, 0xaa, 0x57, 0x5, 0xaf, 0x5d, 0x45 } }; + +FOOGUIDDECL const GUID progress_meter_instance::class_guid = { 0x13915b24, 0xefef, 0x42b5, { 0xae, 0x1d, 0x55, 0x24, 0x5e, 0x22, 0x22, 0xc5 } }; +FOOGUIDDECL const GUID progress_meter::class_guid = { 0x5e98da34, 0xa9c7, 0x4925, { 0xb0, 0xec, 0x90, 0x9d, 0xe0, 0x16, 0xfa, 0x68 } }; + +FOOGUIDDECL const GUID album_art_manager_config::class_guid = { 0xffa6f79b, 0x6e58, 0x459b, { 0xb7, 0x82, 0xc8, 0x61, 0xe6, 0x3d, 0xb0, 0x75 } }; +FOOGUIDDECL const GUID album_art_manager_v3::class_guid = { 0x125841a4, 0x9507, 0x4d93, { 0x98, 0x60, 0x15, 0xd3, 0xc3, 0x45, 0x47, 0xd6 } }; + +FOOGUIDDECL const GUID album_art_editor_instance_v2::class_guid = { 0xcf0f46ca, 0xe34a, 0x4be7, { 0xaf, 0x40, 0xf, 0x31, 0x5c, 0xa1, 0x23, 0x98 } }; + +FOOGUIDDECL const GUID input_info_writer_v2::class_guid = { 0x601c0b4c, 0xf915, 0x486c, { 0xa3, 0x77, 0x0, 0xe3, 0x9c, 0x4d, 0xb7, 0xe4 } }; + +FOOGUIDDECL const GUID playback_control_v3::class_guid = { 0x67008b05, 0x2792, 0x43b5, { 0x80, 0xbb, 0xf9, 0x41, 0xd7, 0xc3, 0xc9, 0x2 } }; + +FOOGUIDDECL const GUID metadb_info_container::class_guid = { 0xd1fdcc01, 0x1e84, 0x48e6, { 0xbf, 0x5f, 0x37, 0x74, 0xd1, 0xcd, 0xc0, 0xe } }; + +FOOGUIDDECL const GUID metadb_hint_list_v3::class_guid = { 0x3e7d9438, 0x7be9, 0x437b, { 0x8a, 0xc8, 0x2b, 0xc2, 0x88, 0xce, 0x1e, 0x22 } }; +FOOGUIDDECL const GUID track_property_provider_v3::class_guid = { 0xdbbce29c, 0x6431, 0x464b, { 0x9c, 0x68, 0x7f, 0x38, 0xfc, 0x34, 0xaf, 0xe7 } }; + + +FOOGUIDDECL const GUID output::class_guid = { 0xb9632c4f, 0x596e, 0x43ee, { 0xb2, 0x14, 0x71, 0x4, 0x48, 0x4b, 0x65, 0xf1 } }; +FOOGUIDDECL const GUID output_entry::class_guid = { 0xe7480b4f, 0x4941, 0x4dd2, { 0xad, 0xbf, 0x96, 0x6c, 0x76, 0x63, 0x43, 0x92 } }; +FOOGUIDDECL const GUID output_entry_v2::class_guid = { 0xaacc17f3, 0xb7cc, 0x48c2, { 0x95, 0x6e, 0x52, 0xba, 0x72, 0x89, 0x42, 0xe5 } }; +FOOGUIDDECL const GUID volume_control::class_guid = { 0x39f9fc0c, 0x4dc9, 0x4a7a, { 0xb9, 0xad, 0x75, 0x8b, 0x78, 0x57, 0x78, 0xad } }; +FOOGUIDDECL const GUID output_v2::class_guid = { 0x4f679e4b, 0x79e0, 0x4fc9, { 0x90, 0x27, 0x55, 0x49, 0x85, 0x72, 0x26, 0xbf } }; + +FOOGUIDDECL const GUID output_manager::class_guid = { 0x6cc5827e, 0x2c89, 0x42ff, { 0x83, 0x51, 0x76, 0xa9, 0x2e, 0x2f, 0x34, 0x50 } }; + +FOOGUIDDECL const GUID ui_element_instance::class_guid = { 0xb55d4525, 0xddc8, 0x40d7,{ 0xb9, 0x19, 0x6d, 0x7c, 0x48, 0x38, 0xf2, 0xdb } }; +FOOGUIDDECL const GUID ui_element::class_guid = { 0xb52c703, 0x1586, 0x42f7,{ 0xa8, 0x4c, 0x70, 0x54, 0xcd, 0xc8, 0x22, 0x55 } }; +FOOGUIDDECL const GUID ui_element_v2::class_guid = { 0x2e1fe21e, 0x8e0f, 0x43be,{ 0x9f, 0xdb, 0xd5, 0xdd, 0xf4, 0xc9, 0xba, 0xba } }; +FOOGUIDDECL const GUID ui_element_instance_callback::class_guid = { 0xcd3647c6, 0x12d9, 0x4122,{ 0xa5, 0x28, 0x4a, 0xba, 0x34, 0x90, 0x89, 0x5c } }; +FOOGUIDDECL const GUID ui_element_instance_callback_v2::class_guid = { 0x5b11faa3, 0x48ee, 0x41a1,{ 0xb7, 0xf9, 0x16, 0x7a, 0xba, 0x6c, 0x60, 0x41 } }; +FOOGUIDDECL const GUID ui_element_children_enumerator::class_guid = { 0x6c7a3a46, 0xdc54, 0x4499,{ 0x98, 0x66, 0xae, 0x3, 0x55, 0xe, 0xf3, 0x1c } }; +FOOGUIDDECL const GUID ui_element_common_methods::class_guid = { 0xedee8cd9, 0x3072, 0x410e,{ 0xb2, 0x66, 0x37, 0x5d, 0x9f, 0x6f, 0xb0, 0x36 } }; +FOOGUIDDECL const GUID ui_element_common_methods_v2::class_guid = { 0x2dc90e34, 0x38fc, 0x4ad1,{ 0x92, 0x80, 0xff, 0x1f, 0xac, 0x14, 0x52, 0xd0 } }; +FOOGUIDDECL const GUID ui_element_popup_host::class_guid = { 0xfcc381e9, 0xe527, 0x4887,{ 0xae, 0x63, 0x27, 0xc0, 0x3f, 0x4, 0xd, 0x1 } }; +FOOGUIDDECL const GUID ui_element_popup_host_callback::class_guid = { 0x2993a043, 0x2e70, 0x4d8f,{ 0x81, 0xb, 0x41, 0x3, 0x37, 0x73, 0x97, 0xcd } }; +FOOGUIDDECL const GUID ui_element_config::class_guid = { 0xd34bba46, 0x1bad, 0x4547,{ 0xba, 0xb4, 0x17, 0xe2, 0x44, 0xd5, 0xeb, 0x94 } }; +FOOGUIDDECL const GUID ui_element_typable_window_manager::class_guid = { 0xbaa99ee2, 0xf770, 0x4981,{ 0x9e, 0x50, 0xf3, 0x4c, 0x5c, 0x6d, 0x98, 0x81 } }; +FOOGUIDDECL const GUID ui_element_instance_callback_v3::class_guid = { 0x6d15c0c6, 0x90b6, 0x4c7e,{ 0xbf, 0x39, 0xe9, 0x39, 0xf2, 0xdf, 0x9b, 0x91 } }; +FOOGUIDDECL const GUID ui_element_popup_host_v2::class_guid = { 0x8caac11e, 0x52b6, 0x47f7,{ 0x97, 0xc9, 0x2c, 0x87, 0xdb, 0xdb, 0x2e, 0x5b } }; + + + + +FOOGUIDDECL const GUID ui_edit_context::class_guid = { 0xf9ba651b, 0x52dd, 0x466f,{ 0xaa, 0x77, 0xa9, 0x7a, 0x74, 0x98, 0x80, 0x7e } }; +FOOGUIDDECL const GUID ui_edit_context_manager::class_guid = { 0x3807f161, 0xaa17, 0x47df,{ 0x80, 0xf1, 0xe, 0xfc, 0xd2, 0x19, 0xb7, 0xa1 } }; +FOOGUIDDECL const GUID ui_edit_context_playlist::class_guid = { 0x6dec364d, 0x29f2, 0x47c8,{ 0xaf, 0x93, 0xbd, 0x35, 0x56, 0x3f, 0xa2, 0x25 } }; diff --git a/SDK/foobar2000/SDK/hasher_md5.cpp b/SDK/foobar2000/SDK/hasher_md5.cpp new file mode 100644 index 0000000..2a20a68 --- /dev/null +++ b/SDK/foobar2000/SDK/hasher_md5.cpp @@ -0,0 +1,35 @@ +#include "foobar2000.h" + +GUID hasher_md5::guid_from_result(const hasher_md5_result & param) +{ + assert(sizeof(GUID) == sizeof(hasher_md5_result)); + GUID temp = * reinterpret_cast(¶m); + byte_order::order_le_to_native_t(temp); + return temp; +} + +hasher_md5_result hasher_md5::process_single(const void * p_buffer,t_size p_bytes) +{ + hasher_md5_state state; + initialize(state); + process(state,p_buffer,p_bytes); + return get_result(state); +} + +GUID hasher_md5::process_single_guid(const void * p_buffer,t_size p_bytes) +{ + return guid_from_result(process_single(p_buffer,p_bytes)); +} + +t_uint64 hasher_md5_result::xorHalve() const { +#if PFC_BYTE_ORDER_IS_BIG_ENDIAN + t_uint64 ret = 0; + for(int walk = 0; walk < 8; ++walk) { + ret |= (t_uint64)((t_uint8)m_data[walk] ^ (t_uint8)m_data[walk+8]) << (walk * 8); + } + return ret; +#else + const t_uint64 * v = reinterpret_cast(&m_data); + return v[0] ^ v[1]; +#endif +} diff --git a/SDK/foobar2000/SDK/hasher_md5.h b/SDK/foobar2000/SDK/hasher_md5.h new file mode 100644 index 0000000..8cc65e1 --- /dev/null +++ b/SDK/foobar2000/SDK/hasher_md5.h @@ -0,0 +1,83 @@ +struct hasher_md5_state { + char m_data[128]; +}; + +struct hasher_md5_result { + char m_data[16]; + + t_uint64 xorHalve() const; + + static hasher_md5_result null() {hasher_md5_result h = {}; return h;} +}; + +inline bool operator==(const hasher_md5_result & p_item1,const hasher_md5_result & p_item2) {return memcmp(&p_item1,&p_item2,sizeof(hasher_md5_result)) == 0;} +inline bool operator!=(const hasher_md5_result & p_item1,const hasher_md5_result & p_item2) {return memcmp(&p_item1,&p_item2,sizeof(hasher_md5_result)) != 0;} + +namespace pfc { + template<> class traits_t : public traits_rawobject {}; + template<> class traits_t : public traits_rawobject {}; + + template<> inline int compare_t(const hasher_md5_result & p_item1, const hasher_md5_result & p_item2) { + return memcmp(&p_item1, &p_item2, sizeof(hasher_md5_result)); + } + +} + +class NOVTABLE hasher_md5 : public service_base +{ +public: + + virtual void initialize(hasher_md5_state & p_state) = 0; + virtual void process(hasher_md5_state & p_state,const void * p_buffer,t_size p_bytes) = 0; + virtual hasher_md5_result get_result(const hasher_md5_state & p_state) = 0; + + + static GUID guid_from_result(const hasher_md5_result & param); + + hasher_md5_result process_single(const void * p_buffer,t_size p_bytes); + hasher_md5_result process_single_string(const char * str) {return process_single(str, strlen(str));} + GUID process_single_guid(const void * p_buffer,t_size p_bytes); + GUID get_result_guid(const hasher_md5_state & p_state) {return guid_from_result(get_result(p_state));} + + + //! Helper + void process_string(hasher_md5_state & p_state,const char * p_string,t_size p_length = ~0) {return process(p_state,p_string,pfc::strlen_max(p_string,p_length));} + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(hasher_md5); +}; + + +class stream_writer_hasher_md5 : public stream_writer { +public: + stream_writer_hasher_md5() { + m_hasher->initialize(m_state); + } + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + p_abort.check(); + m_hasher->process(m_state,p_buffer,p_bytes); + } + hasher_md5_result result() const { + return m_hasher->get_result(m_state); + } + GUID resultGuid() const { + return hasher_md5::guid_from_result(result()); + } +private: + hasher_md5_state m_state; + static_api_ptr_t m_hasher; +}; +template +class stream_formatter_hasher_md5 : public stream_writer_formatter { +public: + stream_formatter_hasher_md5() : stream_writer_formatter(_m_stream,_m_abort) {} + + hasher_md5_result result() const { + return _m_stream.result(); + } + GUID resultGuid() const { + return hasher_md5::guid_from_result(result()); + } +private: + abort_callback_dummy _m_abort; + stream_writer_hasher_md5 _m_stream; +}; diff --git a/SDK/foobar2000/SDK/http_client.h b/SDK/foobar2000/SDK/http_client.h new file mode 100644 index 0000000..ef2e27f --- /dev/null +++ b/SDK/foobar2000/SDK/http_client.h @@ -0,0 +1,48 @@ +//! Implemented by file object returned by http_request::run methods. Allows you to retrieve various additional information returned by the server. \n +//! Warning: reply status may change when seeking on the file object since seek operations often require a new HTTP request to be fired. +class NOVTABLE http_reply : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(http_reply, service_base) +public: + //! Retrieves the status line, eg. "200 OK". + virtual void get_status(pfc::string_base & out) = 0; + //! Retrieves a HTTP header value, eg. "content-type". Note that get_http_header("content-type", out) is equivalent to get_content_type(out). If there are multiple matching header entries, value of the first one will be returned. + virtual bool get_http_header(const char * name, pfc::string_base & out) = 0; + //! Retrieves a HTTP header value, eg. "content-type". If there are multiple matching header entries, this will return all their values, delimited by \r\n. + virtual bool get_http_header_multi(const char * name, pfc::string_base & out) = 0; +}; + +class NOVTABLE http_request : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(http_request, service_base) +public: + //! Adds a HTTP request header line. + //! @param line Request to be added, without trailing \r\n. + virtual void add_header(const char * line) = 0; + //! Runs the request on the specified URL. Throws an exception on failure (connection error, invalid response from the server, reply code other than 2XX), returns a file::ptr interface to the stream on success. + virtual file::ptr run(const char * url, abort_callback & abort) = 0; + //! Runs the request on the specified URL. Throws an exception on failure but returns normally if the HTTP server returned a valid response other than 2XX, so the caller can still parse the received data stream if the server has returned an error. + virtual file::ptr run_ex(const char * url, abort_callback & abort) = 0; + + void add_header(const char * name, const char * value) { + add_header(PFC_string_formatter() << name << ": " << value); + } +}; + +class NOVTABLE http_request_post : public http_request { + FB2K_MAKE_SERVICE_INTERFACE(http_request_post, http_request); +public: + //! Adds a HTTP POST field. + //! @param name Field name. + //! @param fileName File name to be included in the POST request; leave empty ("") not to send a file name. + //! @param contentType Content type of the entry; leave empty ("") not to send content type. + virtual void add_post_data(const char * name, const void * data, t_size dataSize, const char * fileName, const char * contentType) = 0; + + void add_post_data(const char * name, const char * value) { add_post_data(name, value, strlen(value), "", ""); } +}; + +class NOVTABLE http_client : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(http_client) +public: + //! Creates a HTTP request object. + //! @param type Request type. Currently supported: "GET" and "POST". Throws pfc::exception_not_implemented for unsupported values. + virtual http_request::ptr create_request(const char * type) = 0; +}; diff --git a/SDK/foobar2000/SDK/icon_remap.h b/SDK/foobar2000/SDK/icon_remap.h new file mode 100644 index 0000000..977f5fe --- /dev/null +++ b/SDK/foobar2000/SDK/icon_remap.h @@ -0,0 +1,26 @@ +//! New in 0.9.5; allows your file format to use another icon than .ico when registering the file type with Windows shell. \n +//! Implementation: use icon_remapping_impl, or simply: static service_factory_single_t myicon("ext","iconname.ico"); +class icon_remapping : public service_base { +public: + //! @param p_extension File type extension being queried. + //! @param p_iconname Receives the icon name to use, including the .ico extension. + //! @returns True when p_iconname has been set, false if we don't recognize the specified extension. + virtual bool query(const char * p_extension,pfc::string_base & p_iconname) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(icon_remapping); +}; + +//! Standard implementation of icon_remapping. +class icon_remapping_impl : public icon_remapping { +public: + icon_remapping_impl(const char * p_extension,const char * p_iconname) : m_extension(p_extension), m_iconname(p_iconname) {} + bool query(const char * p_extension,pfc::string_base & p_iconname) { + if (pfc::stricmp_ascii(p_extension,m_extension) == 0) { + p_iconname = m_iconname; return true; + } else { + return false; + } + } +private: + pfc::string8 m_extension,m_iconname; +}; diff --git a/SDK/foobar2000/SDK/info_lookup_handler.h b/SDK/foobar2000/SDK/info_lookup_handler.h new file mode 100644 index 0000000..08e1562 --- /dev/null +++ b/SDK/foobar2000/SDK/info_lookup_handler.h @@ -0,0 +1,32 @@ +//! Service used to access various external (online) track info lookup services, such as freedb, to update file tags with info retrieved from those services. +class NOVTABLE info_lookup_handler : public service_base { +public: + enum { + flag_album_lookup = 1 << 0, + flag_track_lookup = 1 << 1, + }; + + //! Retrieves human-readable name of the lookup handler to display in user interface. + virtual void get_name(pfc::string_base & p_out) = 0; + + //! Returns one or more of flag_track_lookup, and flag_album_lookup. + virtual t_uint32 get_flags() = 0; + + virtual HICON get_icon(int p_width, int p_height) = 0; + + //! Performs a lookup. Creates a modeless dialog and returns immediately. + //! @param p_items Items to look up. + //! @param p_notify Callback to notify caller when the operation has completed. Call on_completion with status code 0 to signal failure/abort, or with code 1 to signal success / new infos in metadb. + //! @param p_parent Parent window for the lookup dialog. Caller will typically disable the window while lookup is in progress and enable it back when completion is signaled. + virtual void lookup(metadb_handle_list_cref items,completion_notify::ptr notify,HWND parent) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(info_lookup_handler); +}; + + +class NOVTABLE info_lookup_handler_v2 : public info_lookup_handler { + FB2K_MAKE_SERVICE_INTERFACE(info_lookup_handler_v2, info_lookup_handler); +public: + virtual double merit() {return 0;} + virtual void lookup_noninteractive(metadb_handle_list_cref items, completion_notify::ptr notify, HWND parent) = 0; +}; diff --git a/SDK/foobar2000/SDK/initquit.h b/SDK/foobar2000/SDK/initquit.h new file mode 100644 index 0000000..f5f96b6 --- /dev/null +++ b/SDK/foobar2000/SDK/initquit.h @@ -0,0 +1,39 @@ +//! Basic callback startup/shutdown callback, on_init is called after the main window has been created, on_quit is called before the main window is destroyed. \n +//! To register: static initquit_factory_t myclass_factory; \n +//! Note that you should be careful with calling other components during on_init/on_quit or \n +//! initializing services that are possibly used by other components by on_init/on_quit - \n +//! initialization order of components is undefined. +//! If some other service that you publish is not properly functional before you receive an on_init() call, \n +//! someone else might call this service before >your< on_init is invoked. +class NOVTABLE initquit : public service_base { +public: + virtual void on_init() {} + virtual void on_quit() {} + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(initquit); +}; + +template +class initquit_factory_t : public service_factory_single_t {}; + + +//! \since 1.1 +namespace init_stages { + enum { + before_config_read = 10, + after_config_read = 20, + before_library_init = 30, + after_library_init = 40, + before_ui_init = 50, + after_ui_init = 60, + }; +}; + +//! \since 1.1 +class NOVTABLE init_stage_callback : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(init_stage_callback) +public: + virtual void on_init_stage(t_uint32 stage) = 0; + + static void dispatch(t_uint32 stage) {FB2K_FOR_EACH_SERVICE(init_stage_callback, on_init_stage(stage));} +}; diff --git a/SDK/foobar2000/SDK/input.cpp b/SDK/foobar2000/SDK/input.cpp new file mode 100644 index 0000000..b1c4adf --- /dev/null +++ b/SDK/foobar2000/SDK/input.cpp @@ -0,0 +1,248 @@ +#include "foobar2000.h" + +bool input_entry::g_find_service_by_path(service_ptr_t & p_out,const char * p_path) +{ + pfc::string_extension ext(p_path); + return g_find_service_by_path(p_out, p_path, ext ); +} + +bool input_entry::g_find_service_by_path(service_ptr_t & p_out,const char * p_path, const char * p_ext) +{ + service_ptr_t ptr; + service_enum_t e; + while(e.next(ptr)) + { + if (ptr->is_our_path(p_path,p_ext)) + { + p_out = ptr; + return true; + } + } + return false; +} + +bool input_entry::g_find_service_by_content_type(service_ptr_t & p_out,const char * p_content_type) +{ + service_ptr_t ptr; + service_enum_t e; + while(e.next(ptr)) + { + if (ptr->is_our_content_type(p_content_type)) + { + p_out = ptr; + return true; + } + } + return false; +} + + +#if 0 +static void prepare_for_open(service_ptr_t & p_service,service_ptr_t & p_file,const char * p_path,filesystem::t_open_mode p_open_mode,abort_callback & p_abort,bool p_from_redirect) +{ + if (p_file.is_empty()) + { + service_ptr_t fs; + if (filesystem::g_get_interface(fs,p_path)) { + if (fs->supports_content_types()) { + fs->open(p_file,p_path,p_open_mode,p_abort); + } + } + } + + if (p_file.is_valid()) + { + pfc::string8 content_type; + if (p_file->get_content_type(content_type)) + { + if (input_entry::g_find_service_by_content_type(p_service,content_type)) + return; + } + } + + if (input_entry::g_find_service_by_path(p_service,p_path)) + { + if (p_from_redirect && p_service->is_redirect()) throw exception_io_unsupported_format(); + return; + } + + throw exception_io_unsupported_format(); +} +#endif + +namespace { + + bool g_find_inputs_by_content_type(pfc::list_base_t > & p_out,const char * p_content_type,bool p_from_redirect) { + service_enum_t e; + service_ptr_t ptr; + bool ret = false; + while(e.next(ptr)) { + if (!(p_from_redirect && ptr->is_redirect())) { + if (ptr->is_our_content_type(p_content_type)) {p_out.add_item(ptr); ret = true;} + } + } + return ret; + } + + bool g_find_inputs_by_path(pfc::list_base_t > & p_out,const char * p_path,bool p_from_redirect) { + service_enum_t e; + service_ptr_t ptr; + pfc::string_extension extension(p_path); + bool ret = false; + while(e.next(ptr)) { + if (!(p_from_redirect && ptr->is_redirect())) { + if (ptr->is_our_path(p_path,extension)) {p_out.add_item(ptr); ret = true;} + } + } + return ret; + } + + template void g_open_from_list(service_ptr_t & p_instance,pfc::list_base_const_t > const & p_list,service_ptr_t const & p_filehint,const char * p_path,abort_callback & p_abort) { + const t_size count = p_list.get_count(); + if (count == 1) { + p_list[0]->open(p_instance,p_filehint,p_path,p_abort); + } else { + unsigned bad_data_count = 0; + pfc::string8 bad_data_message; + for(t_size n=0;nopen(p_instance,p_filehint,p_path,p_abort); + return; + } catch(exception_io_unsupported_format) { + //do nothing, skip over + } catch(exception_io_data const & e) { + if (bad_data_count ++ == 0) bad_data_message = e.what(); + } + } + if (bad_data_count > 1) throw exception_io_data(); + else if (bad_data_count == 0) pfc::throw_exception_with_message(bad_data_message); + else throw exception_io_unsupported_format(); + } + } + + template bool needs_write_access() {return false;} + template<> bool needs_write_access() {return true;} + + template void g_open_t(service_ptr_t & p_instance,service_ptr_t const & p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect) { + service_ptr_t l_file = p_filehint; + if (l_file.is_empty()) { + service_ptr_t fs; + if (filesystem::g_get_interface(fs,p_path)) { + if (fs->supports_content_types()) { + fs->open(l_file,p_path,needs_write_access() ? filesystem::open_mode_write_existing : filesystem::open_mode_read,p_abort); + } + } + } + + if (l_file.is_valid()) { + pfc::string8 content_type; + if (l_file->get_content_type(content_type)) { + pfc::list_hybrid_t,4> list; + if (g_find_inputs_by_content_type(list,content_type,p_from_redirect)) { + g_open_from_list(p_instance,list,l_file,p_path,p_abort); + return; + } + } + } + + { + pfc::list_hybrid_t,4> list; + if (g_find_inputs_by_path(list,p_path,p_from_redirect)) { + g_open_from_list(p_instance,list,l_file,p_path,p_abort); + return; + } + } + + throw exception_io_unsupported_format(); + } +}; + +void input_entry::g_open_for_decoding(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect) { + TRACK_CALL_TEXT("input_entry::g_open_for_decoding"); +#if 1 + g_open_t(p_instance,p_filehint,p_path,p_abort,p_from_redirect); +#else + service_ptr_t filehint = p_filehint; + service_ptr_t entry; + + prepare_for_open(entry,filehint,p_path,filesystem::open_mode_read,p_abort,p_from_redirect); + + entry->open_for_decoding(p_instance,filehint,p_path,p_abort); +#endif + +} + +void input_entry::g_open_for_info_read(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect) { + TRACK_CALL_TEXT("input_entry::g_open_for_info_read"); +#if 1 + g_open_t(p_instance,p_filehint,p_path,p_abort,p_from_redirect); +#else + service_ptr_t filehint = p_filehint; + service_ptr_t entry; + + prepare_for_open(entry,filehint,p_path,filesystem::open_mode_read,p_abort,p_from_redirect); + + entry->open_for_info_read(p_instance,filehint,p_path,p_abort); +#endif +} + +void input_entry::g_open_for_info_write(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect) { + TRACK_CALL_TEXT("input_entry::g_open_for_info_write"); +#if 1 + g_open_t(p_instance,p_filehint,p_path,p_abort,p_from_redirect); +#else + service_ptr_t filehint = p_filehint; + service_ptr_t entry; + + prepare_for_open(entry,filehint,p_path,filesystem::open_mode_write_existing,p_abort,p_from_redirect); + + entry->open_for_info_write(p_instance,filehint,p_path,p_abort); +#endif +} + +void input_entry::g_open_for_info_write_timeout(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,abort_callback & p_abort,double p_timeout,bool p_from_redirect) { + pfc::lores_timer timer; + timer.start(); + for(;;) { + try { + g_open_for_info_write(p_instance,p_filehint,p_path,p_abort,p_from_redirect); + break; + } catch(exception_io_sharing_violation) { + if (timer.query() > p_timeout) throw; + p_abort.sleep(0.01); + } + } +} + +bool input_entry::g_is_supported_path(const char * p_path) +{ + service_ptr_t ptr; + service_enum_t e; + pfc::string_extension ext(p_path); + while(e.next(ptr)) + { + if (ptr->is_our_path(p_path,ext)) return true; + } + return false; +} + + + +void input_open_file_helper(service_ptr_t & p_file,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort) +{ + if (p_file.is_empty()) { + switch(p_reason) { + default: + uBugCheck(); + case input_open_info_read: + case input_open_decode: + filesystem::g_open(p_file,p_path,filesystem::open_mode_read,p_abort); + break; + case input_open_info_write: + filesystem::g_open(p_file,p_path,filesystem::open_mode_write_existing,p_abort); + break; + } + } else { + p_file->reopen(p_abort); + } +} \ No newline at end of file diff --git a/SDK/foobar2000/SDK/input.h b/SDK/foobar2000/SDK/input.h new file mode 100644 index 0000000..3057f3c --- /dev/null +++ b/SDK/foobar2000/SDK/input.h @@ -0,0 +1,210 @@ +PFC_DECLARE_EXCEPTION(exception_tagging_unsupported, exception_io_data, "Tagging of this file format is not supported") + +enum { + input_flag_no_seeking = 1 << 0, + input_flag_no_looping = 1 << 1, + input_flag_playback = 1 << 2, + input_flag_testing_integrity = 1 << 3, + input_flag_allow_inaccurate_seeking = 1 << 4, + input_flag_no_postproc = 1 << 5, + + input_flag_simpledecode = input_flag_no_seeking|input_flag_no_looping, +}; + +//! Class providing interface for retrieval of information (metadata, duration, replaygain, other tech infos) from files. Also see: file_info. \n +//! Instantiating: see input_entry.\n +//! Implementing: see input_impl. + +class NOVTABLE input_info_reader : public service_base +{ +public: + //! Retrieves count of subsongs in the file. 1 for non-multisubsong-enabled inputs. + //! Note: multi-subsong handling is disabled for remote files (see: filesystem::is_remote) for performance reasons. Remote files are always assumed to be single-subsong, with null index. + virtual t_uint32 get_subsong_count() = 0; + + //! Retrieves identifier of specified subsong; this identifier is meant to be used in playable_location as well as a parameter for input_info_reader::get_info(). + //! @param p_index Index of subsong to query. Must be >=0 and < get_subsong_count(). + virtual t_uint32 get_subsong(t_uint32 p_index) = 0; + + //! Retrieves information about specified subsong. + //! @param p_subsong Identifier of the subsong to query. See: input_info_reader::get_subsong(), playable_location. + //! @param p_info file_info object to fill. Must be empty on entry. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort) = 0; + + //! Retrieves file stats. Equivalent to calling get_stats() on file object. + virtual t_filestats get_file_stats(abort_callback & p_abort) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(input_info_reader,service_base); +}; + +//! Class providing interface for retrieval of PCM audio data from files.\n +//! Instantiating: see input_entry.\n +//! Implementing: see input_impl. + +class NOVTABLE input_decoder : public input_info_reader +{ +public: + //! Prepares to decode specified subsong; resets playback position to the beginning of specified subsong. This must be called first, before any other input_decoder methods (other than those inherited from input_info_reader). \n + //! It is legal to set initialize() more than once, with same or different subsong, to play either the same subsong again or another subsong from same file without full reopen.\n + //! Warning: this interface inherits from input_info_reader, it is legal to call any input_info_reader methods even during decoding! Call order is not defined, other than initialize() requirement before calling other input_decoder methods.\n + //! @param p_subsong Subsong to decode. Should always be 0 for non-multi-subsong-enabled inputs. + //! @param p_flags Specifies additional hints for decoding process. It can be null, or a combination of one or more following constants: \n + //! input_flag_no_seeking - Indicates that seek() will never be called. Can be used to avoid building potentially expensive seektables when only sequential reading is needed.\n + //! input_flag_no_looping - Certain input implementations can be configured to utilize looping info from file formats they process and keep playing single file forever, or keep repeating it specified number of times. This flag indicates that such features should be disabled, for e.g. ReplayGain scan or conversion.\n + //! input_flag_playback - Indicates that decoding process will be used for realtime playback rather than conversion. This can be used to reconfigure features that are relevant only for conversion and take a lot of resources, such as very slow secure CDDA reading. \n + //! input_flag_testing_integrity - Indicates that we're testing integrity of the file. Any recoverable problems where decoding would normally continue should cause decoder to fail with exception_io_data. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void initialize(t_uint32 p_subsong,unsigned p_flags,abort_callback & p_abort) = 0; + + //! Reads/decodes one chunk of audio data. Use false return value to signal end of file (no more data to return). Before calling run(), decoding must be initialized by initialize() call. + //! @param p_chunk audio_chunk object receiving decoded data. Contents are valid only the method returns true. + //! @param p_abort abort_callback object signaling user aborting the operation. + //! @returns true on success (new data decoded), false on EOF. + virtual bool run(audio_chunk & p_chunk,abort_callback & p_abort) = 0; + + //! Seeks to specified time offset. Before seeking or other decoding calls, decoding must be initialized with initialize() call. + //! @param p_seconds Time to seek to, in seconds. If p_seconds exceeds length of the object being decoded, succeed, and then return false from next run() call. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void seek(double p_seconds,abort_callback & p_abort) = 0; + + //! Queries whether resource being read/decoded is seekable. If p_value is set to false, all seek() calls will fail. Before calling can_seek() or other decoding calls, decoding must be initialized with initialize() call. + virtual bool can_seek() = 0; + + //! This function is used to signal dynamic VBR bitrate, etc. Called after each run() (or not called at all if caller doesn't care about dynamic info). + //! @param p_out Initially contains currently displayed info (either last get_dynamic_info result or current cached info), use this object to return changed info. + //! @param p_timestamp_delta Indicates when returned info should be displayed (in seconds, relative to first sample of last decoded chunk), initially set to 0. + //! @returns false to keep old info, or true to indicate that changes have been made to p_info and those should be displayed. + virtual bool get_dynamic_info(file_info & p_out, double & p_timestamp_delta) = 0; + + //! This function is used to signal dynamic live stream song titles etc. Called after each run() (or not called at all if caller doesn't care about dynamic info). The difference between this and get_dynamic_info() is frequency and relevance of dynamic info changes - get_dynamic_info_track() returns new info only on track change in the stream, returning new titles etc. + //! @param p_out Initially contains currently displayed info (either last get_dynamic_info_track result or current cached info), use this object to return changed info. + //! @param p_timestamp_delta Indicates when returned info should be displayed (in seconds, relative to first sample of last decoded chunk), initially set to 0. + //! @returns false to keep old info, or true to indicate that changes have been made to p_info and those should be displayed. + virtual bool get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) = 0; + + //! Called from playback thread before sleeping. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void on_idle(abort_callback & p_abort) = 0; + + + FB2K_MAKE_SERVICE_INTERFACE(input_decoder,input_info_reader); +}; + + +class NOVTABLE input_decoder_v2 : public input_decoder { + FB2K_MAKE_SERVICE_INTERFACE(input_decoder_v2, input_decoder) +public: + + //! OPTIONAL, throws pfc::exception_not_implemented() when not supported by this implementation. + //! Special version of run(). Returns an audio_chunk object as well as a raw data block containing original PCM stream. This is mainly used for MD5 checks on lossless formats. \n + //! If you set a "MD5" tech info entry in get_info(), you should make sure that run_raw() returns data stream that can be used to verify it. \n + //! Returned raw data should be possible to cut into individual samples; size in bytes should be divisible by audio_chunk's sample count for splitting in case partial output is needed (with cuesheets etc). + virtual bool run_raw(audio_chunk & out, mem_block_container & outRaw, abort_callback & abort) = 0; + + //! OPTIONAL, the call is ignored if this implementation doesn't support status logging. \n + //! Mainly used to generate logs when ripping CDs etc. + virtual void set_logger(event_logger::ptr ptr) = 0; +}; + +class NOVTABLE input_decoder_v3 : public input_decoder_v2 { + FB2K_MAKE_SERVICE_INTERFACE(input_decoder_v3, input_decoder_v2); +public: + //! OPTIONAL, in case your input cares about paused/unpaused state, handle this to do any necessary additional processing. Valid only after initialize() with input_flag_playback. + virtual void set_pause(bool paused) = 0; + //! OPTIONAL, should return false in most cases; return true to force playback buffer flush on unpause. Valid only after initialize() with input_flag_playback. + virtual bool flush_on_pause() = 0; +}; + +//! Class providing interface for writing metadata and replaygain info to files. Also see: file_info. \n +//! Instantiating: see input_entry.\n +//! Implementing: see input_impl. + +class NOVTABLE input_info_writer : public input_info_reader +{ +public: + //! Tells the service to update file tags with new info for specified subsong. + //! @param p_subsong Subsong to update. Should be always 0 for non-multisubsong-enabled inputs. + //! @param p_info New info to write. Sometimes not all contents of p_info can be written. Caller will typically read info back after successful write, so e.g. tech infos that change with retag are properly maintained. + //! @param p_abort abort_callback object signaling user aborting the operation. WARNING: abort_callback object is provided for consistency; if writing tags actually gets aborted, user will be likely left with corrupted file. Anything calling this should make sure that aborting is either impossible, or gives appropriate warning to the user first. + virtual void set_info(t_uint32 p_subsong,const file_info & p_info,abort_callback & p_abort) = 0; + + //! Commits pending updates. In case of multisubsong inputs, set_info should queue the update and perform actual file access in commit(). Otherwise, actual writing can be done in set_info() and then Commit() can just do nothing and always succeed. + //! @param p_abort abort_callback object signaling user aborting the operation. WARNING: abort_callback object is provided for consistency; if writing tags actually gets aborted, user will be likely left with corrupted file. Anything calling this should make sure that aborting is either impossible, or gives appropriate warning to the user first. + virtual void commit(abort_callback & p_abort) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(input_info_writer,input_info_reader); +}; + +class NOVTABLE input_info_writer_v2 : public input_info_writer { +public: + //! Removes all tags from this file. Cancels any set_info() requests on this object. Does not require a commit() afterwards. + virtual void remove_tags(abort_callback & abort) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(input_info_writer_v2, input_info_writer); +}; + +class NOVTABLE input_entry : public service_base +{ +public: + //! Determines whether specified content type can be handled by this input. + //! @param p_type Content type string to test. + virtual bool is_our_content_type(const char * p_type)=0; + + //! Determines whether specified file type can be handled by this input. This must not use any kind of file access; the result should be only based on file path / extension. + //! @param p_full_path Full URL of file being tested. + //! @param p_extension Extension of file being tested, provided by caller for performance reasons. + virtual bool is_our_path(const char * p_full_path,const char * p_extension)=0; + + //! Opens specified resource for decoding. + //! @param p_instance Receives new input_decoder instance if successful. + //! @param p_filehint Optional; passes file object to use for the operation; if set to null, the service will handle opening file by itself. Note that not all inputs operate on physical files that can be reached through filesystem API, some of them require this parameter to be set to null (tone and silence generators for an example). + //! @param p_path URL of resource being opened. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void open_for_decoding(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,abort_callback & p_abort) = 0; + + //! Opens specified file for reading info. + //! @param p_instance Receives new input_info_reader instance if successful. + //! @param p_filehint Optional; passes file object to use for the operation; if set to null, the service will handle opening file by itself. Note that not all inputs operate on physical files that can be reached through filesystem API, some of them require this parameter to be set to null (tone and silence generators for an example). + //! @param p_path URL of resource being opened. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void open_for_info_read(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,abort_callback & p_abort) = 0; + + //! Opens specified file for writing info. + //! @param p_instance Receives new input_info_writer instance if successful. + //! @param p_filehint Optional; passes file object to use for the operation; if set to null, the service will handle opening file by itself. Note that not all inputs operate on physical files that can be reached through filesystem API, some of them require this parameter to be set to null (tone and silence generators for an example). + //! @param p_path URL of resource being opened. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void open_for_info_write(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,abort_callback & p_abort) = 0; + + //! Reserved for future use. Do nothing and return until specifications are finalized. + virtual void get_extended_data(service_ptr_t p_filehint,const playable_location & p_location,const GUID & p_guid,mem_block_container & p_out,abort_callback & p_abort) = 0; + + enum { + //! Indicates that this service implements some kind of redirector that opens another input for decoding, used to avoid circular call possibility. + flag_redirect = 1, + //! Indicates that multi-CPU optimizations should not be used. + flag_parallel_reads_slow = 2, + }; + //! See flag_* enums. + virtual unsigned get_flags() = 0; + + inline bool is_redirect() {return (get_flags() & flag_redirect) != 0;} + inline bool are_parallel_reads_slow() {return (get_flags() & flag_parallel_reads_slow) != 0;} + + static bool g_find_service_by_path(service_ptr_t & p_out,const char * p_path); + static bool g_find_service_by_path(service_ptr_t & p_out,const char * p_path, const char * p_ext); + static bool g_find_service_by_content_type(service_ptr_t & p_out,const char * p_content_type); + static void g_open_for_decoding(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect = false); + static void g_open_for_info_read(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect = false); + static void g_open_for_info_write(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect = false); + static void g_open_for_info_write_timeout(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,abort_callback & p_abort,double p_timeout,bool p_from_redirect = false); + static bool g_is_supported_path(const char * p_path); + + + void open(service_ptr_t & p_instance,service_ptr_t const & p_filehint,const char * p_path,abort_callback & p_abort) {open_for_decoding(p_instance,p_filehint,p_path,p_abort);} + void open(service_ptr_t & p_instance,service_ptr_t const & p_filehint,const char * p_path,abort_callback & p_abort) {open_for_info_read(p_instance,p_filehint,p_path,p_abort);} + void open(service_ptr_t & p_instance,service_ptr_t const & p_filehint,const char * p_path,abort_callback & p_abort) {open_for_info_write(p_instance,p_filehint,p_path,p_abort);} + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(input_entry); +}; diff --git a/SDK/foobar2000/SDK/input_file_type.cpp b/SDK/foobar2000/SDK/input_file_type.cpp new file mode 100644 index 0000000..dbb24d5 --- /dev/null +++ b/SDK/foobar2000/SDK/input_file_type.cpp @@ -0,0 +1,113 @@ +#include "foobar2000.h" + +#if FOOBAR2000_TARGET_VERSION >= 76 + +typedef pfc::avltree_t t_fnList; + +static void formatMaskList(pfc::string_base & out, t_fnList const & in) { + pfc::const_iterator walk = in.first(); + if (walk.is_valid()) { + out << *walk; ++walk; + while(walk.is_valid()) { + out << ";" << *walk; ++walk; + } + } +} +static void formatMaskList(pfc::string_base & out, t_fnList const & in, const char * label) { + if (in.get_count() > 0) { + out << label << "|"; + formatMaskList(out,in); + out << "|"; + } +} + +void input_file_type::make_filetype_support_fingerprint(pfc::string_base & str) { + pfc::string_formatter out; + pfc::avltree_t names; + + { + componentversion::ptr ptr; service_enum_t e; + pfc::string_formatter name; + while(e.next(ptr)) { + name = ""; + ptr->get_component_name(name); + if (strstr(name, "decoder") != NULL || strstr(name, "Decoder") != NULL) names += name; + } + } + + + make_extension_support_fingerprint(out); + for(pfc::const_iterator walk = names.first(); walk.is_valid(); ++walk) { + if (!out.is_empty()) str << "|"; + out << *walk; + } + str = out; +} +void input_file_type::make_extension_support_fingerprint(pfc::string_base & str) { + pfc::avltree_t masks; + { + service_enum_t e; + service_ptr_t ptr; + pfc::string_formatter mask; + while(e.next(ptr)) { + const unsigned count = ptr->get_count(); + for(unsigned n=0;nget_mask(n,mask)) { + if (strchr(mask,'|') == NULL) masks += mask; + } + } + } + } + pfc::string_formatter out; + for(pfc::const_iterator walk = masks.first(); walk.is_valid(); ++walk) { + if (!out.is_empty()) out << "|"; + out << *walk; + } + str = out; +} +void input_file_type::build_openfile_mask(pfc::string_base & out, bool b_include_playlists) +{ + t_fnList extensionsAll, extensionsPl;; + + if (b_include_playlists) { + service_enum_t e; service_ptr_t ptr; + while(e.next(ptr)) { + if (ptr->is_associatable()) { + pfc::string_formatter temp; temp << "*." << ptr->get_extension(); + extensionsPl += temp; + extensionsAll += temp; + } + } + } + + typedef pfc::map_t t_masks; + t_masks masks; + { + service_enum_t e; + service_ptr_t ptr; + pfc::string_formatter name, mask; + while(e.next(ptr)) { + const unsigned count = ptr->get_count(); + for(unsigned n=0;nget_name(n,name) && ptr->get_mask(n,mask)) { + if (!strchr(name,'|') && !strchr(mask,'|')) { + masks.find_or_add(name) += mask; + extensionsAll += mask; + } + } + } + } + } + pfc::string_formatter outBuf; + outBuf << "All files|*.*|"; + formatMaskList(outBuf, extensionsAll, "All supported types"); + formatMaskList(outBuf, extensionsPl, "Playlists"); + for(t_masks::const_iterator walk = masks.first(); walk.is_valid(); ++walk) { + formatMaskList(outBuf,walk->m_value,walk->m_key); + } + out = outBuf; +} +#endif \ No newline at end of file diff --git a/SDK/foobar2000/SDK/input_file_type.h b/SDK/foobar2000/SDK/input_file_type.h new file mode 100644 index 0000000..435e9df --- /dev/null +++ b/SDK/foobar2000/SDK/input_file_type.h @@ -0,0 +1,109 @@ +//! Entrypoint interface for registering media file types that can be opened through "open file" dialogs or associated with foobar2000 application in Windows shell. \n +//! Instead of implementing this directly, use DECLARE_FILE_TYPE() / DECLARE_FILE_TYPE_EX() macros. +class input_file_type : public service_base { +public: + virtual unsigned get_count()=0; + virtual bool get_name(unsigned idx,pfc::string_base & out)=0;//eg. "MPEG files" + virtual bool get_mask(unsigned idx,pfc::string_base & out)=0;//eg. "*.MP3;*.MP2"; separate with semicolons + virtual bool is_associatable(unsigned idx) = 0; + +#if FOOBAR2000_TARGET_VERSION >= 76 + static void build_openfile_mask(pfc::string_base & out,bool b_include_playlists=true); + static void make_extension_support_fingerprint(pfc::string_base & str); + static void make_filetype_support_fingerprint(pfc::string_base & str); +#endif + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(input_file_type); +}; + +//! Extended interface for registering media file types that can be associated with foobar2000 application in Windows shell. \n +//! Instead of implementing this directly, use DECLARE_FILE_TYPE() / DECLARE_FILE_TYPE_EX() macros. +class input_file_type_v2 : public input_file_type { +public: + virtual void get_format_name(unsigned idx, pfc::string_base & out, bool isPlural) = 0; + virtual void get_extensions(unsigned idx, pfc::string_base & out) = 0; + + //Deprecated input_file_type method implementations: + bool get_name(unsigned idx, pfc::string_base & out) {get_format_name(idx, out, true); return true;} + bool get_mask(unsigned idx, pfc::string_base & out) { + pfc::string_formatter temp; get_extensions(idx,temp); + pfc::chain_list_v2_t exts; pfc::splitStringSimple_toList(exts,";",temp); + if (exts.get_count() == 0) return false;//should not happen + temp.reset(); + for(pfc::const_iterator walk = exts.first(); walk.is_valid(); ++walk) { + if (!temp.is_empty()) temp << ";"; + temp << "*." << walk->get_ptr(); + } + out = temp; + return true; + } + + FB2K_MAKE_SERVICE_INTERFACE(input_file_type_v2,input_file_type) +}; + + +//! Implementation helper. +class input_file_type_impl : public service_impl_single_t +{ + const char * name, * mask; + bool m_associatable; +public: + input_file_type_impl(const char * p_name, const char * p_mask,bool p_associatable) : name(p_name), mask(p_mask), m_associatable(p_associatable) {} + unsigned get_count() {return 1;} + bool get_name(unsigned idx,pfc::string_base & out) {if (idx==0) {out = name; return true;} else return false;} + bool get_mask(unsigned idx,pfc::string_base & out) {if (idx==0) {out = mask; return true;} else return false;} + bool is_associatable(unsigned idx) {return m_associatable;} +}; + + +//! Helper macro for registering our media file types. +//! Usage: DECLARE_FILE_TYPE("Blah files","*.blah;*.bleh"); +#define DECLARE_FILE_TYPE(NAME,MASK) \ + namespace { static input_file_type_impl g_filetype_instance(NAME,MASK,true); \ + static service_factory_single_ref_t g_filetype_service(g_filetype_instance); } + + + + +//! Implementation helper. +//! Usage: static input_file_type_factory mytype("blah type","*.bla;*.meh",true); +class input_file_type_factory : private service_factory_single_transparent_t +{ +public: + input_file_type_factory(const char * p_name,const char * p_mask,bool p_associatable) + : service_factory_single_transparent_t(p_name,p_mask,p_associatable) {} +}; + + + +class input_file_type_v2_impl : public input_file_type_v2 { +public: + input_file_type_v2_impl(const char * extensions,const char * name, const char * namePlural) : m_extensions(extensions), m_name(name), m_namePlural(namePlural) {} + unsigned get_count() {return 1;} + bool is_associatable(unsigned idx) {return true;} + void get_format_name(unsigned idx, pfc::string_base & out, bool isPlural) { + out = isPlural ? m_namePlural : m_name; + } + void get_extensions(unsigned idx, pfc::string_base & out) { + out = m_extensions; + } + +private: + const pfc::string8 m_name, m_namePlural, m_extensions; +}; + +//! Helper macro for registering our media file types, extended version providing separate singular/plural type names. +//! Usage: DECLARE_FILE_TYPE_EX("mp1;mp2;mp3","MPEG file","MPEG files") +#define DECLARE_FILE_TYPE_EX(extensions, name, namePlural) \ + namespace { static service_factory_single_t g_myfiletype(extensions, name, namePlural); } + + +//! Service for registering protocol types that can be associated with foobar2000. +class input_protocol_type : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(input_protocol_type) +public: + //! Returns the name of the protocol, such as "ftp" or "http". + virtual void get_protocol_name(pfc::string_base & out) = 0; + //! Returns a human-readable description of the protocol. + virtual void get_description(pfc::string_base & out) = 0; +}; diff --git a/SDK/foobar2000/SDK/input_impl.h b/SDK/foobar2000/SDK/input_impl.h new file mode 100644 index 0000000..b5b7b3a --- /dev/null +++ b/SDK/foobar2000/SDK/input_impl.h @@ -0,0 +1,342 @@ +enum t_input_open_reason { + input_open_info_read, + input_open_decode, + input_open_info_write +}; + +//! Helper function for input implementation use; ensures that file is open with relevant access mode. This is typically called from input_impl::open() and such. +//! @param p_file File object pointer to process. If passed pointer is non-null, the function does nothing and always succeeds; otherwise it attempts to open the file using filesystem API methods. +//! @param p_path Path to the file. +//! @param p_reason Type of input operation requested. See: input_impl::open() parameters. +//! @param p_abort abort_callback object signaling user aborting the operation. +void input_open_file_helper(service_ptr_t & p_file,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort); + + +//! This is a class that just declares prototypes of functions that each input needs to implement. See input_decoder / input_info_reader / input_info_writer interfaces for full descriptions of member functions. Since input implementation class is instantiated using a template, you don't need to derive from input_impl as virtual functions are not used on implementation class level. Use input_factory_t template to register input class based on input_impl. +class input_impl +{ +public: + //! Opens specified file for info read / decoding / info write. This is called only once, immediately after object creation, before any other methods, and no other methods are called if open() fails. + //! @param p_filehint Optional; passes file object to use for the operation; if set to null, the implementation should handle opening file by itself. Note that not all inputs operate on physical files that can be reached through filesystem API, some of them require this parameter to be set to null (tone and silence generators for an example). Typically, an input implementation that requires file access calls input_open_file_helper() function to ensure that file is open with relevant access mode (read or read/write). + //! @param p_path URL of resource being opened. + //! @param p_reason Type of operation requested. Possible values are: \n + //! - input_open_info_read - info retrieval methods are valid; \n + //! - input_open_decode - info retrieval and decoding methods are valid; \n + //! - input_open_info_write - info retrieval and retagging methods are valid; \n + //! Note that info retrieval methods are valid in all cases, and they may be called at any point of decoding/retagging process. Results of info retrieval methods (other than get_subsong_count() / get_subsong()) between retag_set_info() and retag_commit() are undefined however; those should not be called during that period. + //! @param p_abort abort_callback object signaling user aborting the operation. + void open(service_ptr_t p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort); + + //! See: input_info_reader::get_subsong_count(). Valid after open() with any reason. + unsigned get_subsong_count(); + //! See: input_info_reader::get_subsong(). Valid after open() with any reason. + t_uint32 get_subsong(unsigned p_index); + //! See: input_info_reader::get_info(). Valid after open() with any reason. + void get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort); + //! See: input_info_reader::get_file_stats(). Valid after open() with any reason. + t_filestats get_file_stats(abort_callback & p_abort); + + //! See: input_decoder::initialize(). Valid after open() with input_open_decode reason. + void decode_initialize(t_uint32 p_subsong,unsigned p_flags,abort_callback & p_abort); + //! See: input_decoder::run(). Valid after decode_initialize(). + bool decode_run(audio_chunk & p_chunk,abort_callback & p_abort); + //! See: input_decoder::seek(). Valid after decode_initialize(). + void decode_seek(double p_seconds,abort_callback & p_abort); + //! See: input_decoder::can_seek(). Valid after decode_initialize(). + bool decode_can_seek(); + //! See: input_decoder::get_dynamic_info(). Valid after decode_initialize(). + bool decode_get_dynamic_info(file_info & p_out, double & p_timestamp_delta); + //! See: input_decoder::get_dynamic_info_track(). Valid after decode_initialize(). + bool decode_get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta); + //! See: input_decoder::on_idle(). Valid after decode_initialize(). + void decode_on_idle(abort_callback & p_abort); + + //! See: input_info_writer::set_info(). Valid after open() with input_open_info_write reason. + void retag_set_info(t_uint32 p_subsong,const file_info & p_info,abort_callback & p_abort); + //! See: input_info_writer::commit(). Valid after open() with input_open_info_write reason. + void retag_commit(abort_callback & p_abort); + + //! See: input_entry::is_our_content_type(). + static bool g_is_our_content_type(const char * p_content_type); + //! See: input_entry::is_our_path(). + static bool g_is_our_path(const char * p_path,const char * p_extension); + + + //! See: input_decoder_v2::run_raw(). Relevant only when implementing input_decoder_v2. Valid after decode_initialize(). + bool decode_run_raw(audio_chunk & p_chunk, mem_block_container & p_raw, abort_callback & p_abort); + + //! See: input_decoder::set_logger(). Relevant only when implementing input_decoder_v2. Valid after any open(). + void set_logger(event_logger::ptr ptr); +protected: + input_impl() {} + ~input_impl() {} +}; + +//! This is a class that just declares prototypes of functions that each non-multitrack-enabled input needs to implement. See input_decoder / input_info_reader / input_info_writer interfaces for full descriptions of member functions. Since input implementation class is instantiated using a template, you don't need to derive from input_singletrack_impl as virtual functions are not used on implementation class level. Use input_singletrack_factory_t template to register input class based on input_singletrack_impl. +class input_singletrack_impl +{ +public: + //! Opens specified file for info read / decoding / info write. This is called only once, immediately after object creation, before any other methods, and no other methods are called if open() fails. + //! @param p_filehint Optional; passes file object to use for the operation; if set to null, the implementation should handle opening file by itself. Note that not all inputs operate on physical files that can be reached through filesystem API, some of them require this parameter to be set to null (tone and silence generators for an example). Typically, an input implementation that requires file access calls input_open_file_helper() function to ensure that file is open with relevant access mode (read or read/write). + //! @param p_path URL of resource being opened. + //! @param p_reason Type of operation requested. Possible values are: \n + //! - input_open_info_read - info retrieval methods are valid; \n + //! - input_open_decode - info retrieval and decoding methods are valid; \n + //! - input_open_info_write - info retrieval and retagging methods are valid; \n + //! Note that info retrieval methods are valid in all cases, and they may be called at any point of decoding/retagging process. Results of info retrieval methods (other than get_subsong_count() / get_subsong()) between retag_set_info() and retag_commit() are undefined however; those should not be called during that period. + //! @param p_abort abort_callback object signaling user aborting the operation. + void open(service_ptr_t p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort); + + //! See: input_info_reader::get_info(). Valid after open() with any reason. \n + //! Implementation warning: this is typically also called immediately after tag update and should return newly written content then. + void get_info(file_info & p_info,abort_callback & p_abort); + //! See: input_info_reader::get_file_stats(). Valid after open() with any reason. \n + //! Implementation warning: this is typically also called immediately after tag update and should return new values then. + t_filestats get_file_stats(abort_callback & p_abort); + + //! See: input_decoder::initialize(). Valid after open() with input_open_decode reason. + void decode_initialize(unsigned p_flags,abort_callback & p_abort); + //! See: input_decoder::run(). Valid after decode_initialize(). + bool decode_run(audio_chunk & p_chunk,abort_callback & p_abort); + //! See: input_decoder::seek(). Valid after decode_initialize(). + void decode_seek(double p_seconds,abort_callback & p_abort); + //! See: input_decoder::can_seek(). Valid after decode_initialize(). + bool decode_can_seek(); + //! See: input_decoder::get_dynamic_info(). Valid after decode_initialize(). + bool decode_get_dynamic_info(file_info & p_out, double & p_timestamp_delta); + //! See: input_decoder::get_dynamic_info_track(). Valid after decode_initialize(). + bool decode_get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta); + //! See: input_decoder::on_idle(). Valid after decode_initialize(). + void decode_on_idle(abort_callback & p_abort); + + //! See: input_info_writer::set_info(). Note that input_info_writer::commit() call isn't forwarded because it's useless in case of non-multitrack-enabled inputs. Valid after open() with input_open_info_write reason. + void retag(const file_info & p_info,abort_callback & p_abort); + + //! See: input_entry::is_our_content_type(). + static bool g_is_our_content_type(const char * p_content_type); + //! See: input_entry::is_our_path(). + static bool g_is_our_path(const char * p_path,const char * p_extension); + +protected: + input_singletrack_impl() {} + ~input_singletrack_impl() {} +}; + + +//! Used internally by standard input_entry implementation; do not use directly. Translates input_decoder / input_info_reader / input_info_writer calls to input_impl calls. +template +class input_impl_interface_wrapper_t : public t_base +{ +public: + void open(service_ptr_t p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort) { + m_instance.open(p_filehint,p_path,p_reason,p_abort); + } + + // input_info_reader methods + + t_uint32 get_subsong_count() { + return m_instance.get_subsong_count(); + } + + t_uint32 get_subsong(t_uint32 p_index) { + return m_instance.get_subsong(p_index); + } + + + void get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort) { + m_instance.get_info(p_subsong,p_info,p_abort); + } + + t_filestats get_file_stats(abort_callback & p_abort) { + return m_instance.get_file_stats(p_abort); + } + + // input_decoder methods + + void initialize(t_uint32 p_subsong,unsigned p_flags,abort_callback & p_abort) { + m_instance.decode_initialize(p_subsong,p_flags,p_abort); + } + + bool run(audio_chunk & p_chunk,abort_callback & p_abort) { + return m_instance.decode_run(p_chunk,p_abort); + } + + bool run_raw(audio_chunk & p_chunk, mem_block_container & p_raw, abort_callback & p_abort) { + return m_instance.decode_run_raw(p_chunk, p_raw, p_abort); + } + + void seek(double p_seconds,abort_callback & p_abort) { + m_instance.decode_seek(p_seconds,p_abort); + } + + bool can_seek() { + return m_instance.decode_can_seek(); + } + + bool get_dynamic_info(file_info & p_out, double & p_timestamp_delta) { + return m_instance.decode_get_dynamic_info(p_out,p_timestamp_delta); + } + + bool get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) { + return m_instance.decode_get_dynamic_info_track(p_out,p_timestamp_delta); + } + + void on_idle(abort_callback & p_abort) { + m_instance.decode_on_idle(p_abort); + } + + void set_logger(event_logger::ptr ptr) { + m_instance.set_logger(ptr); + } + + void set_pause(bool paused) { + m_instance.set_pause(paused); + } + bool flush_on_pause() { + return m_instance.flush_on_pause(); + } + + + // input_info_writer methods + + void set_info(t_uint32 p_subsong,const file_info & p_info,abort_callback & p_abort) { + m_instance.retag_set_info(p_subsong,p_info,p_abort); + } + + void commit(abort_callback & p_abort) { + m_instance.retag_commit(p_abort); + } + void remove_tags(abort_callback & p_abort) { + m_instance.remove_tags(p_abort); + } + +private: + I m_instance; +}; + +//! Helper used by input_singletrack_factory_t, do not use directly. Translates input_impl calls to input_singletrack_impl calls. +template +class input_wrapper_singletrack_t +{ +public: + input_wrapper_singletrack_t() {} + + void open(service_ptr_t p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort) { + m_instance.open(p_filehint,p_path,p_reason,p_abort); + } + + void get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort) { + if (p_subsong != 0) throw exception_io_data(); + m_instance.get_info(p_info,p_abort); + } + + t_uint32 get_subsong_count() { + return 1; + } + + t_uint32 get_subsong(t_uint32 p_index) { + assert(p_index == 0); + return 0; + } + + t_filestats get_file_stats(abort_callback & p_abort) { + return m_instance.get_file_stats(p_abort); + } + + void decode_initialize(t_uint32 p_subsong,unsigned p_flags,abort_callback & p_abort) { + if (p_subsong != 0) throw exception_io_data(); + m_instance.decode_initialize(p_flags,p_abort); + } + + bool decode_run(audio_chunk & p_chunk,abort_callback & p_abort) {return m_instance.decode_run(p_chunk,p_abort);} + void decode_seek(double p_seconds,abort_callback & p_abort) {m_instance.decode_seek(p_seconds,p_abort);} + bool decode_can_seek() {return m_instance.decode_can_seek();} + bool decode_get_dynamic_info(file_info & p_out, double & p_timestamp_delta) {return m_instance.decode_get_dynamic_info(p_out,p_timestamp_delta);} + bool decode_get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) {return m_instance.decode_get_dynamic_info_track(p_out,p_timestamp_delta);} + void decode_on_idle(abort_callback & p_abort) {m_instance.decode_on_idle(p_abort);} + + void retag_set_info(t_uint32 p_subsong,const file_info & p_info,abort_callback & p_abort) { + if (p_subsong != 0) throw exception_io_data(); + m_instance.retag(p_info,p_abort); + } + + bool decode_run_raw(audio_chunk & p_chunk, mem_block_container & p_raw, abort_callback & p_abort) { + return m_instance.decode_run_raw(p_chunk, p_raw, p_abort); + } + + void set_logger(event_logger::ptr ptr) {m_instance.set_logger(ptr);} + + void set_pause(bool paused) { + m_instance.set_pause(paused); + } + bool flush_on_pause() { + return m_instance.flush_on_pause(); + } + + void retag_commit(abort_callback & p_abort) {} + + void remove_tags(abort_callback & p_abort) { + m_instance.remove_tags(p_abort); + } + + static bool g_is_our_content_type(const char * p_content_type) {return I::g_is_our_content_type(p_content_type);} + static bool g_is_our_path(const char * p_path,const char * p_extension) {return I::g_is_our_path(p_path,p_extension);} + + +private: + I m_instance; +}; + +//! Helper; standard input_entry implementation. Do not instantiate this directly, use input_factory_t or one of other input_*_factory_t helpers instead. +template +class input_entry_impl_t : public input_entry +{ +private: + + template + void instantiate_t(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort) + { + service_ptr_t< service_impl_t > > temp; + temp = new service_impl_t >(); + temp->open(p_filehint,p_path,p_reason,p_abort); + p_instance = temp.get_ptr(); + } +public: + bool is_our_content_type(const char * p_type) {return I::g_is_our_content_type(p_type);} + bool is_our_path(const char * p_full_path,const char * p_extension) {return I::g_is_our_path(p_full_path,p_extension);} + + void open_for_decoding(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,abort_callback & p_abort) { + instantiate_t(p_instance,p_filehint,p_path,input_open_decode,p_abort); + } + + void open_for_info_read(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,abort_callback & p_abort) { + instantiate_t(p_instance,p_filehint,p_path,input_open_info_read,p_abort); + } + + void open_for_info_write(service_ptr_t & p_instance,service_ptr_t p_filehint,const char * p_path,abort_callback & p_abort) { + instantiate_t(p_instance,p_filehint,p_path,input_open_info_write,p_abort); + } + + void get_extended_data(service_ptr_t p_filehint,const playable_location & p_location,const GUID & p_guid,mem_block_container & p_out,abort_callback & p_abort) { + p_out.reset(); + } + + unsigned get_flags() {return t_flags;} +}; + + +//! Stardard input factory. For reference of functions that must be supported by registered class, see input_impl.\n Usage: static input_factory_t g_myinputclass_factory;\n Note that input classes can't be registered through service_factory_t template directly. +template +class input_factory_t : public service_factory_single_t > {}; + +//! Non-multitrack-enabled input factory (helper) - hides multitrack management functions from input implementation; use this for inputs that handle file types where each physical file can contain only one user-visible playable track. For reference of functions that must be supported by registered class, see input_singletrack_impl.\n Usage: static input_singletrack_factory_t g_myinputclass_factory;\n Note that input classes can't be registered through service_factory_t template directly.template +template +class input_singletrack_factory_t : public service_factory_single_t,0> > {}; + +//! Extended version of input_factory_t, with non-default flags and supported interfaces. See: input_factory_t, input_entry::get_flags(). +template +class input_factory_ex_t : public service_factory_single_t > {}; + +//! Extended version of input_singletrack_factory_t, with non-default flags and supported interfaces. See: input_singletrack_factory_t, input_entry::get_flags(). +template +class input_singletrack_factory_ex_t : public service_factory_single_t,t_flags, t_decoder, t_inforeader, t_infowriter> > {}; diff --git a/SDK/foobar2000/SDK/library_manager.h b/SDK/foobar2000/SDK/library_manager.h new file mode 100644 index 0000000..6dfe04f --- /dev/null +++ b/SDK/foobar2000/SDK/library_manager.h @@ -0,0 +1,197 @@ +/*! +This service implements methods allowing you to interact with the Media Library.\n +All methods are valid from main thread only, unless noted otherwise.\n +Usage: Use static_api_ptr_t to instantiate. +*/ + +class NOVTABLE library_manager : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(library_manager); +public: + //! Interface for use with library_manager::enum_items(). + class NOVTABLE enum_callback { + public: + //! Return true to continue enumeration, false to abort. + virtual bool on_item(const metadb_handle_ptr & p_item) = 0; + }; + + //! Returns whether the specified item is in the Media Library or not. + virtual bool is_item_in_library(const metadb_handle_ptr & p_item) = 0; + //! Returns whether current user settings allow the specified item to be added to the Media Library or not. + virtual bool is_item_addable(const metadb_handle_ptr & p_item) = 0; + //! Returns whether current user settings allow the specified item path to be added to the Media Library or not. + virtual bool is_path_addable(const char * p_path) = 0; + //! Retrieves path of the specified item relative to the Media Library folder it is in. Returns true on success, false when the item is not in the Media Library. + //! SPECIAL WARNING: to allow multi-CPU optimizations to parse relative track paths, this API works in threads other than the main app thread. Main thread MUST be blocked while working in such scenarios, it's NOT safe to call from worker threads while the Media Library content/configuration might be getting altered. + virtual bool get_relative_path(const metadb_handle_ptr & p_item,pfc::string_base & p_out) = 0; + //! Calls callback method for every item in the Media Library. Note that order of items in Media Library is undefined. + virtual void enum_items(enum_callback & p_callback) = 0; +protected: + //! OBSOLETE, do not call, does nothing. + __declspec(deprecated) virtual void add_items(const pfc::list_base_const_t & p_data) = 0; + //! OBSOLETE, do not call, does nothing. + __declspec(deprecated) virtual void remove_items(const pfc::list_base_const_t & p_data) = 0; + //! OBSOLETE, do not call, does nothing. + __declspec(deprecated) virtual void add_items_async(const pfc::list_base_const_t & p_data) = 0; + + //! OBSOLETE, do not call, does nothing. + __declspec(deprecated) virtual void on_files_deleted_sorted(const pfc::list_base_const_t & p_data) = 0; +public: + //! Retrieves the entire Media Library content. + virtual void get_all_items(pfc::list_base_t & p_out) = 0; + + //! Returns whether Media Library functionality is enabled or not (to be exact: whether there's at least one Media Library folder present in settings), for e.g. notifying the user to change settings when trying to use a Media Library viewer without having configured the Media Library first. + virtual bool is_library_enabled() = 0; + //! Pops up the Media Library preferences page. + virtual void show_preferences() = 0; + + //! OBSOLETE, do not call. + virtual void rescan() = 0; + +protected: + //! OBSOLETE, do not call, does nothing. + __declspec(deprecated) virtual void check_dead_entries(const pfc::list_base_t & p_list) = 0; +public: + + +}; + +//! \since 0.9.3 +class NOVTABLE library_manager_v2 : public library_manager { + FB2K_MAKE_SERVICE_INTERFACE(library_manager_v2,library_manager); +protected: + //! OBSOLETE, do not call, does nothing. + __declspec(deprecated) virtual bool is_rescan_running() = 0; + + //! OBSOLETE, do not call, does nothing. + __declspec(deprecated) virtual void rescan_async(HWND p_parent,completion_notify_ptr p_notify) = 0; + + //! OBSOLETE, do not call, does nothing. + __declspec(deprecated) virtual void check_dead_entries_async(const pfc::list_base_const_t & p_list,HWND p_parent,completion_notify_ptr p_notify) = 0; + + +}; + + +class NOVTABLE library_callback_dynamic { +public: + //! Called when new items are added to the Media Library. + virtual void on_items_added(const pfc::list_base_const_t & p_data) = 0; + //! Called when some items have been removed from the Media Library. + virtual void on_items_removed(const pfc::list_base_const_t & p_data) = 0; + //! Called when some items in the Media Library have been modified. + virtual void on_items_modified(const pfc::list_base_const_t & p_data) = 0; +}; + +//! \since 0.9.5 +class NOVTABLE library_manager_v3 : public library_manager_v2 { +public: + //! Retrieves directory path and subdirectory/filename formatting scheme for newly encoded/copied/moved tracks. + //! @returns True on success, false when the feature has not been configured. + virtual bool get_new_file_pattern_tracks(pfc::string_base & p_directory,pfc::string_base & p_format) = 0; + //! Retrieves directory path and subdirectory/filename formatting scheme for newly encoded/copied/moved full album images. + //! @returns True on success, false when the feature has not been configured. + virtual bool get_new_file_pattern_images(pfc::string_base & p_directory,pfc::string_base & p_format) = 0; + + virtual void register_callback(library_callback_dynamic * p_callback) = 0; + virtual void unregister_callback(library_callback_dynamic * p_callback) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(library_manager_v3,library_manager_v2); +}; + +class library_callback_dynamic_impl_base : public library_callback_dynamic { +public: + library_callback_dynamic_impl_base() {static_api_ptr_t()->register_callback(this);} + ~library_callback_dynamic_impl_base() {static_api_ptr_t()->unregister_callback(this);} + + //stub implementations - avoid pure virtual function call issues + void on_items_added(metadb_handle_list_cref p_data) {} + void on_items_removed(metadb_handle_list_cref p_data) {} + void on_items_modified(metadb_handle_list_cref p_data) {} + + PFC_CLASS_NOT_COPYABLE_EX(library_callback_dynamic_impl_base); +}; + +//! Callback service receiving notifications about Media Library content changes. Methods called only from main thread.\n +//! Use library_callback_factory_t template to register. +class NOVTABLE library_callback : public service_base { +public: + //! Called when new items are added to the Media Library. + virtual void on_items_added(const pfc::list_base_const_t & p_data) = 0; + //! Called when some items have been removed from the Media Library. + virtual void on_items_removed(const pfc::list_base_const_t & p_data) = 0; + //! Called when some items in the Media Library have been modified. + virtual void on_items_modified(const pfc::list_base_const_t & p_data) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(library_callback); +}; + +template +class library_callback_factory_t : public service_factory_single_t {}; + +//! Implement this service to appear on "library viewers" list in Media Library preferences page.\n +//! Use library_viewer_factory_t to register. +class NOVTABLE library_viewer : public service_base { +public: + //! Retrieves GUID of your preferences page (pfc::guid_null if you don't have one). + virtual GUID get_preferences_page() = 0; + //! Queries whether "activate" action is supported (relevant button will be disabled if it's not). + virtual bool have_activate() = 0; + //! Activates your Media Library viewer component (e.g. shows its window). + virtual void activate() = 0; + //! Retrieves GUID of your library_viewer implementation, for internal identification. Note that this not the same as preferences page GUID. + virtual GUID get_guid() = 0; + //! Retrieves name of your Media Library viewer, a null-terminated UTF-8 encoded string. + virtual const char * get_name() = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(library_viewer); +}; + +template +class library_viewer_factory_t : public service_factory_single_t {}; + + + + +//! \since 0.9.5.4 +//! Allows you to spawn a popup Media Library Search window with any query string that you specify. \n +//! Usage: static_api_ptr_t()->show("querygoeshere"); +class NOVTABLE library_search_ui : public service_base { +public: + virtual void show(const char * query) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(library_search_ui) +}; + +//! \since 0.9.6 +class NOVTABLE library_file_move_scope : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(library_file_move_scope, service_base) +public: +}; + +//! \since 0.9.6 +class NOVTABLE library_file_move_manager : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(library_file_move_manager) +public: + virtual library_file_move_scope::ptr acquire_scope() = 0; + virtual bool is_move_in_progress() = 0; +}; + +//! \since 0.9.6 +class NOVTABLE library_file_move_notify_ { +public: + virtual void on_state_change(bool isMoving) = 0; +}; + +//! \since 0.9.6 +class NOVTABLE library_file_move_notify : public service_base, public library_file_move_notify_ { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(library_file_move_notify) +public: +}; + + +//! \since 0.9.6.1 +class NOVTABLE library_meta_autocomplete : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(library_meta_autocomplete) +public: + virtual bool get_value_list(const char * metaName, pfc::com_ptr_t & out) = 0; +}; diff --git a/SDK/foobar2000/SDK/link_resolver.cpp b/SDK/foobar2000/SDK/link_resolver.cpp new file mode 100644 index 0000000..321e28a --- /dev/null +++ b/SDK/foobar2000/SDK/link_resolver.cpp @@ -0,0 +1,17 @@ +#include "foobar2000.h" + +bool link_resolver::g_find(service_ptr_t & p_out,const char * p_path) +{ + service_enum_t e; + service_ptr_t ptr; + pfc::string_extension ext(p_path); + while(e.next(ptr)) + { + if (ptr->is_our_path(p_path,ext)) + { + p_out = ptr; + return true; + } + } + return false; +} diff --git a/SDK/foobar2000/SDK/link_resolver.h b/SDK/foobar2000/SDK/link_resolver.h new file mode 100644 index 0000000..0c4ca85 --- /dev/null +++ b/SDK/foobar2000/SDK/link_resolver.h @@ -0,0 +1,33 @@ +#ifndef _foobar2000_sdk_link_resolver_h_ +#define _foobar2000_sdk_link_resolver_h_ + +//! Interface for resolving different sorts of link files. +//! Utilized by mechanisms that convert filesystem path into list of playable locations. +//! For security reasons, link may only point to playable object path, not to a playlist or another link. + +class NOVTABLE link_resolver : public service_base +{ +public: + + //! Tests whether specified file is supported by this link_resolver service. + //! @param p_path Path of file being queried. + //! @param p_extension Extension of file being queried. This is provided for performance reasons, path already includes it. + virtual bool is_our_path(const char * p_path,const char * p_extension) = 0; + + //! Resolves a link file. Before this is called, path must be accepted by is_our_path(). + //! @param p_filehint Optional file interface to use. If null/empty, implementation should open file by itself. + //! @param p_path Path of link file to resolve. + //! @param p_out Receives path the link is pointing to. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void resolve(service_ptr_t p_filehint,const char * p_path,pfc::string_base & p_out,abort_callback & p_abort) = 0; + + //! Helper function; finds link_resolver interface that supports specified link file. + //! @param p_out Receives link_resolver interface on success. + //! @param p_path Path of file to query. + //! @returns True on success, false on failure (no interface that supports specified path could be found). + static bool g_find(service_ptr_t & p_out,const char * p_path); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(link_resolver); +}; + +#endif //_foobar2000_sdk_link_resolver_h_ diff --git a/SDK/foobar2000/SDK/main_thread_callback.cpp b/SDK/foobar2000/SDK/main_thread_callback.cpp new file mode 100644 index 0000000..1b7ff34 --- /dev/null +++ b/SDK/foobar2000/SDK/main_thread_callback.cpp @@ -0,0 +1,29 @@ +#include "foobar2000.h" + + +void main_thread_callback::callback_enqueue() { + static_api_ptr_t< main_thread_callback_manager >()->add_callback( this ); +} + +void main_thread_callback_add(main_thread_callback::ptr ptr) { + static_api_ptr_t()->add_callback(ptr); +} + +namespace { + typedef std::function func_t; + class mtcallback_func : public main_thread_callback { + public: + mtcallback_func(func_t const & f) : m_f(f) {} + + void callback_run() { + m_f(); + } + + private: + func_t m_f; + }; +} + +void fb2k::inMainThread( std::function f ) { + main_thread_callback_add( new service_impl_t(f)); +} diff --git a/SDK/foobar2000/SDK/main_thread_callback.h b/SDK/foobar2000/SDK/main_thread_callback.h new file mode 100644 index 0000000..37a7bbb --- /dev/null +++ b/SDK/foobar2000/SDK/main_thread_callback.h @@ -0,0 +1,164 @@ +#include + +//! Callback object class for main_thread_callback_manager service. +class NOVTABLE main_thread_callback : public service_base { +public: + //! Gets called from main app thread. See main_thread_callback_manager description for more info. + virtual void callback_run() = 0; + + void callback_enqueue(); // helper + + FB2K_MAKE_SERVICE_INTERFACE(main_thread_callback,service_base); +}; + +/*! +Allows you to queue a callback object to be called from main app thread. This is commonly used to trigger main-thread-only API calls from worker threads.\n +This can be also used from main app thread, to avoid race conditions when trying to use APIs that dispatch global callbacks from inside some other global callback, or using message loops / modal dialogs inside global callbacks. +*/ +class NOVTABLE main_thread_callback_manager : public service_base { +public: + //! Queues a callback object. This can be called from any thread, implementation ensures multithread safety. Implementation will call p_callback->callback_run() once later. To get it called repeatedly, you would need to add your callback again. + virtual void add_callback(service_ptr_t p_callback) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(main_thread_callback_manager); +}; + + +void main_thread_callback_add(main_thread_callback::ptr ptr); + +template static void main_thread_callback_spawn() { + main_thread_callback_add(new service_impl_t); +} +template static void main_thread_callback_spawn(const t_param1 & p1) { + main_thread_callback_add(new service_impl_t(p1)); +} +template static void main_thread_callback_spawn(const t_param1 & p1, const t_param2 & p2) { + main_thread_callback_add(new service_impl_t(p1, p2)); +} + +// Proxy class - friend this to allow callInMainThread to access your private methods +class callInMainThread { +public: + template + static void callThis(host_t * host, param_t & param) { + host->inMainThread(param); + } + template + static void callThis( host_t * host ) { + host->inMainThread(); + } +}; + +// Internal class, do not use. +template +class _callInMainThreadSvc_t : public main_thread_callback { +public: + _callInMainThreadSvc_t(service_t * host, param_t const & param) : m_host(host), m_param(param) {} + void callback_run() { + callInMainThread::callThis(m_host.get_ptr(), m_param); + } +private: + service_ptr_t m_host; + param_t m_param; +}; + + +// Main thread callback helper. You can use this to easily invoke inMainThread(someparam) on your class without writing any wrapper code. +// Requires myservice_t to be a fb2k service class with reference counting. +template +static void callInMainThreadSvc(myservice_t * host, param_t const & param) { + typedef _callInMainThreadSvc_t impl_t; + service_ptr_t obj = new service_impl_t(host, param); + static_api_ptr_t()->add_callback( obj ); +} + + + + +//! Helper class to call methods of your class (host class) in main thread with convenience. \n +//! Deals with the otherwise ugly scenario of your class becoming invalid while a method is queued. \n +//! Have this as a member of your class, then use m_mthelper.add( this, somearg ) ; to defer a call to this->inMainThread(somearg). \n +//! If your class becomes invalid before inMainThread is executed, the pending callback is discarded. \n +//! You can optionally call shutdown() to invalidate all pending callbacks early (in a destructor of your class - without waiting for callInMainThreadHelper destructor to do the job. \n +//! In order to let callInMainThreadHelper access your private methods, declare friend class callInMainThread. +class callInMainThreadHelper { +public: + + typedef std::function< void () > func_t; + + typedef pfc::rcptr_t< bool > killswitch_t; + + class entryFunc : public main_thread_callback { + public: + entryFunc( func_t const & func, killswitch_t ks ) : m_ks(ks), m_func(func) {} + + void callback_run() { + if (!*m_ks) m_func(); + } + + private: + killswitch_t m_ks; + func_t m_func; + }; + + template + class entry : public main_thread_callback { + public: + entry( host_t * host, arg_t const & arg, killswitch_t ks ) : m_ks(ks), m_host(host), m_arg(arg) {} + void callback_run() { + if (!*m_ks) callInMainThread::callThis( m_host, m_arg ); + } + private: + killswitch_t m_ks; + host_t * m_host; + arg_t m_arg; + }; + template + class entryVoid : public main_thread_callback { + public: + entryVoid( host_t * host, killswitch_t ks ) : m_ks(ks), m_host(host) {} + void callback_run() { + if (!*m_ks) callInMainThread::callThis( m_host ); + } + private: + killswitch_t m_ks; + host_t * m_host; + }; + + void add(func_t f) { + add_( new service_impl_t< entryFunc > ( f, m_ks ) ); + } + + template + void add( host_t * host, arg_t const & arg) { + add_( new service_impl_t< entry >( host, arg, m_ks ) ); + } + template + void add( host_t * host ) { + add_( new service_impl_t< entryVoid >( host, m_ks ) ); + } + void add_( main_thread_callback::ptr cb ) { + main_thread_callback_add( cb ); + } + + callInMainThreadHelper() { + m_ks.new_t(); + * m_ks = false; + } + void shutdown() { + PFC_ASSERT( core_api::is_main_thread() ); + * m_ks = true; + } + ~callInMainThreadHelper() { + shutdown(); + } + +private: + killswitch_t m_ks; + +}; + +// Modern helper +namespace fb2k { + void inMainThread( std::function f ); +} \ No newline at end of file diff --git a/SDK/foobar2000/SDK/mainmenu.cpp b/SDK/foobar2000/SDK/mainmenu.cpp new file mode 100644 index 0000000..79eb5d2 --- /dev/null +++ b/SDK/foobar2000/SDK/mainmenu.cpp @@ -0,0 +1,57 @@ +#include "foobar2000.h" + +bool mainmenu_commands::g_execute_dynamic(const GUID & p_guid, const GUID & p_subGuid,service_ptr_t p_callback) { + mainmenu_commands::ptr ptr; t_uint32 index; + if (!menu_item_resolver::g_resolve_main_command(p_guid, ptr, index)) return false; + mainmenu_commands_v2::ptr v2; + if (!ptr->service_query_t(v2)) return false; + if (!v2->is_command_dynamic(index)) return false; + return v2->dynamic_execute(index, p_subGuid, p_callback); +} +bool mainmenu_commands::g_execute(const GUID & p_guid,service_ptr_t p_callback) { + mainmenu_commands::ptr ptr; t_uint32 index; + if (!menu_item_resolver::g_resolve_main_command(p_guid, ptr, index)) return false; + ptr->execute(index, p_callback); + return true; +} + +bool mainmenu_commands::g_find_by_name(const char * p_name,GUID & p_guid) { + service_enum_t e; + service_ptr_t ptr; + pfc::string8_fastalloc temp; + while(e.next(ptr)) { + const t_uint32 count = ptr->get_command_count(); + for(t_uint32 n=0;nget_name(n,temp); + if (stricmp_utf8(temp,p_name) == 0) { + p_guid = ptr->get_command(n); + return true; + } + } + } + return false; + +} + + +static bool dynamic_execute_recur(mainmenu_node::ptr node, const GUID & subID, service_ptr_t callback) { + switch(node->get_type()) { + case mainmenu_node::type_command: + if (subID == node->get_guid()) { + node->execute(callback); return true; + } + break; + case mainmenu_node::type_group: + { + const t_size total = node->get_children_count(); + for(t_size walk = 0; walk < total; ++walk) { + if (dynamic_execute_recur(node->get_child(walk), subID, callback)) return true; + } + } + break; + } + return false; +} +bool mainmenu_commands_v2::dynamic_execute(t_uint32 index, const GUID & subID, service_ptr_t callback) { + return dynamic_execute_recur(dynamic_instantiate(index), subID, callback); +} diff --git a/SDK/foobar2000/SDK/mem_block_container.cpp b/SDK/foobar2000/SDK/mem_block_container.cpp new file mode 100644 index 0000000..d347a87 --- /dev/null +++ b/SDK/foobar2000/SDK/mem_block_container.cpp @@ -0,0 +1,12 @@ +#include "foobar2000.h" + +void mem_block_container::from_stream(stream_reader * p_stream,t_size p_bytes,abort_callback & p_abort) { + if (p_bytes == 0) {set_size(0);} + set_size(p_bytes); + p_stream->read_object(get_ptr(),p_bytes,p_abort); +} + +void mem_block_container::set(const void * p_buffer,t_size p_size) { + set_size(p_size); + memcpy(get_ptr(),p_buffer,p_size); +} diff --git a/SDK/foobar2000/SDK/mem_block_container.h b/SDK/foobar2000/SDK/mem_block_container.h new file mode 100644 index 0000000..e9cc4a3 --- /dev/null +++ b/SDK/foobar2000/SDK/mem_block_container.h @@ -0,0 +1,95 @@ +//! Generic interface for a memory block; used by various other interfaces to return memory blocks while allowing caller to allocate. +class NOVTABLE mem_block_container { +public: + virtual const void * get_ptr() const = 0; + virtual void * get_ptr() = 0; + virtual t_size get_size() const = 0; + virtual void set_size(t_size p_size) = 0; + + void from_stream(stream_reader * p_stream,t_size p_bytes,abort_callback & p_abort); + + void set(const void * p_buffer,t_size p_size); + void set(const mem_block_container & source) {copy(source);} + template void set(const t_source & source) { + PFC_STATIC_ASSERT( sizeof(source[0]) == 1 ); + set(source.get_ptr(), source.get_size()); + } + + inline void copy(const mem_block_container & p_source) {set(p_source.get_ptr(),p_source.get_size());} + inline void reset() {set_size(0);} + + const mem_block_container & operator=(const mem_block_container & p_source) {copy(p_source);return *this;} + +protected: + mem_block_container() {} + ~mem_block_container() {} +}; + +//! mem_block_container implementation. +template class t_alloc = pfc::alloc_standard> +class mem_block_container_impl_t : public mem_block_container { +public: + const void * get_ptr() const {return m_data.get_ptr();} + void * get_ptr() {return m_data.get_ptr();} + t_size get_size() const {return m_data.get_size();} + void set_size(t_size p_size) { + m_data.set_size(p_size); + } +private: + pfc::array_t m_data; +}; + +typedef mem_block_container_impl_t<> mem_block_container_impl; + +template class mem_block_container_aligned_impl : public mem_block_container { +public: + const void * get_ptr() const {return m_data.get_ptr();} + void * get_ptr() {return m_data.get_ptr();} + t_size get_size() const {return m_data.get_size();} + void set_size(t_size p_size) {m_data.set_size(p_size);} +private: + pfc::mem_block_aligned<16> m_data; +}; + +template class mem_block_container_aligned_incremental_impl : public mem_block_container { +public: + mem_block_container_aligned_incremental_impl() : m_size() {} + const void * get_ptr() const {return m_data.get_ptr();} + void * get_ptr() {return m_data.get_ptr();} + t_size get_size() const {return m_size;} + void set_size(t_size p_size) { + if (m_data.size() < p_size) { + m_data.resize( pfc::multiply_guarded(p_size, 3) / 2 ); + } + m_size = p_size; + } +private: + pfc::mem_block_aligned<16> m_data; + size_t m_size; +}; + +class mem_block_container_temp_impl : public mem_block_container { +public: + mem_block_container_temp_impl(void * p_buffer,t_size p_size) : m_buffer(p_buffer), m_buffer_size(p_size), m_size(0) {} + const void * get_ptr() const {return m_buffer;} + void * get_ptr() {return m_buffer;} + t_size get_size() const {return m_size;} + void set_size(t_size p_size) {if (p_size > m_buffer_size) throw pfc::exception_overflow(); m_size = p_size;} +private: + t_size m_size,m_buffer_size; + void * m_buffer; +}; + +template +class mem_block_container_ref_impl : public mem_block_container { +public: + mem_block_container_ref_impl(t_ref & ref) : m_ref(ref) { + PFC_STATIC_ASSERT( sizeof(ref[0]) == 1 ); + } + const void * get_ptr() const {return m_ref.get_ptr();} + void * get_ptr() {return m_ref.get_ptr();} + t_size get_size() const {return m_ref.get_size();} + void set_size(t_size p_size) {m_ref.set_size(p_size);} +private: + t_ref & m_ref; +}; \ No newline at end of file diff --git a/SDK/foobar2000/SDK/menu.h b/SDK/foobar2000/SDK/menu.h new file mode 100644 index 0000000..33ddde0 --- /dev/null +++ b/SDK/foobar2000/SDK/menu.h @@ -0,0 +1,214 @@ +class NOVTABLE mainmenu_group : public service_base { +public: + virtual GUID get_guid() = 0; + virtual GUID get_parent() = 0; + virtual t_uint32 get_sort_priority() = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(mainmenu_group); +}; + +class NOVTABLE mainmenu_group_popup : public mainmenu_group { +public: + virtual void get_display_string(pfc::string_base & p_out) = 0; + void get_name(pfc::string_base & out) {get_display_string(out);} + + FB2K_MAKE_SERVICE_INTERFACE(mainmenu_group_popup,mainmenu_group); +}; + +class NOVTABLE mainmenu_commands : public service_base { +public: + enum { + flag_disabled = 1<<0, + flag_checked = 1<<1, + flag_radiochecked = 1<<2, + //! \since 1.0 + //! Replaces the old return-false-from-get_display() behavior - use this to make your command hidden by default but accessible when holding shift. + flag_defaulthidden = 1<<3, + sort_priority_base = 0x10000, + sort_priority_dontcare = 0x80000000, + sort_priority_last = ~0, + }; + + //! Retrieves number of implemented commands. Index parameter of other methods must be in 0....command_count-1 range. + virtual t_uint32 get_command_count() = 0; + //! Retrieves GUID of specified command. + virtual GUID get_command(t_uint32 p_index) = 0; + //! Retrieves name of item, for list of commands to assign keyboard shortcuts to etc. + virtual void get_name(t_uint32 p_index,pfc::string_base & p_out) = 0; + //! Retrieves item's description for statusbar etc. + virtual bool get_description(t_uint32 p_index,pfc::string_base & p_out) = 0; + //! Retrieves GUID of owning menu group. + virtual GUID get_parent() = 0; + //! Retrieves sorting priority of the command; the lower the number, the upper in the menu your commands will appear. Third party components should use sorting_priority_base and up (values below are reserved for internal use). In case of equal priority, order is undefined. + virtual t_uint32 get_sort_priority() {return sort_priority_dontcare;} + //! Retrieves display string and display flags to use when menu is about to be displayed. If returns false, menu item won't be displayed. You can create keyboard-shortcut-only commands by always returning false from get_display(). + virtual bool get_display(t_uint32 p_index,pfc::string_base & p_text,t_uint32 & p_flags) {p_flags = 0;get_name(p_index,p_text);return true;} + //! Executes the command. p_callback parameter is reserved for future use and should be ignored / set to null pointer. + virtual void execute(t_uint32 p_index,service_ptr_t p_callback) = 0; + + static bool g_execute(const GUID & p_guid,service_ptr_t p_callback = NULL); + static bool g_execute_dynamic(const GUID & p_guid, const GUID & p_subGuid,service_ptr_t p_callback = NULL); + static bool g_find_by_name(const char * p_name,GUID & p_guid); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(mainmenu_commands); +}; + +class NOVTABLE mainmenu_manager : public service_base { +public: + enum { + flag_show_shortcuts = 1 << 0, + flag_show_shortcuts_global = 1 << 1, + //! \since 1.0 + //! To control which commands are shown, you should specify either flag_view_reduced or flag_view_full. If neither is specified, the implementation will decide automatically based on shift key being pressed, for backwards compatibility. + flag_view_reduced = 1 << 2, + //! \since 1.0 + //! To control which commands are shown, you should specify either flag_view_reduced or flag_view_full. If neither is specified, the implementation will decide automatically based on shift key being pressed, for backwards compatibility. + flag_view_full = 1 << 3, + }; + + virtual void instantiate(const GUID & p_root) = 0; + +#ifdef _WIN32 + virtual void generate_menu_win32(HMENU p_menu,t_uint32 p_id_base,t_uint32 p_id_count,t_uint32 p_flags) = 0; +#else +#error portme +#endif + //@param p_id Identifier of command to execute, relative to p_id_base of generate_menu_*() + //@returns true if command was executed successfully, false if not (e.g. command with given identifier not found). + virtual bool execute_command(t_uint32 p_id,service_ptr_t p_callback = service_ptr_t()) = 0; + + virtual bool get_description(t_uint32 p_id,pfc::string_base & p_out) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(mainmenu_manager); +}; + +class mainmenu_groups { +public: + static const GUID file,view,edit,playback,library,help; + static const GUID file_open,file_add,file_playlist,file_etc; + static const GUID playback_controls,playback_etc; + static const GUID view_visualisations, view_alwaysontop; + static const GUID edit_part1,edit_part2,edit_part3; + static const GUID edit_part2_selection,edit_part2_sort,edit_part2_selection_sort; + static const GUID file_etc_preferences, file_etc_exit; + static const GUID help_about; + static const GUID library_refresh; + + enum {priority_edit_part1,priority_edit_part2,priority_edit_part3}; + enum {priority_edit_part2_commands,priority_edit_part2_selection,priority_edit_part2_sort}; + enum {priority_edit_part2_selection_commands,priority_edit_part2_selection_sort}; + enum {priority_file_open,priority_file_add,priority_file_playlist,priority_file_etc = mainmenu_commands::sort_priority_last}; +}; + + +class mainmenu_group_impl : public mainmenu_group { +public: + mainmenu_group_impl(const GUID & p_guid,const GUID & p_parent,t_uint32 p_priority) : m_guid(p_guid), m_parent(p_parent), m_priority(p_priority) {} + GUID get_guid() {return m_guid;} + GUID get_parent() {return m_parent;} + t_uint32 get_sort_priority() {return m_priority;} +private: + GUID m_guid,m_parent; t_uint32 m_priority; +}; + +class mainmenu_group_popup_impl : public mainmenu_group_popup { +public: + mainmenu_group_popup_impl(const GUID & p_guid,const GUID & p_parent,t_uint32 p_priority,const char * p_name) : m_guid(p_guid), m_parent(p_parent), m_priority(p_priority), m_name(p_name) {} + GUID get_guid() {return m_guid;} + GUID get_parent() {return m_parent;} + t_uint32 get_sort_priority() {return m_priority;} + void get_display_string(pfc::string_base & p_out) {p_out = m_name;} +private: + GUID m_guid,m_parent; t_uint32 m_priority; pfc::string8 m_name; +}; + +typedef service_factory_single_t __mainmenu_group_factory; +typedef service_factory_single_t __mainmenu_group_popup_factory; + +class mainmenu_group_factory : public __mainmenu_group_factory { +public: + mainmenu_group_factory(const GUID & p_guid,const GUID & p_parent,t_uint32 p_priority) : __mainmenu_group_factory(p_guid,p_parent,p_priority) {} +}; + +class mainmenu_group_popup_factory : public __mainmenu_group_popup_factory { +public: + mainmenu_group_popup_factory(const GUID & p_guid,const GUID & p_parent,t_uint32 p_priority,const char * p_name) : __mainmenu_group_popup_factory(p_guid,p_parent,p_priority,p_name) {} +}; + +template +class mainmenu_commands_factory_t : public service_factory_single_t {}; + + + + + + +// \since 1.0 +class NOVTABLE mainmenu_node : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(mainmenu_node, service_base) +public: + enum { //same as contextmenu_item_node::t_type + type_group,type_command,type_separator + }; + + virtual t_uint32 get_type() = 0; + virtual void get_display(pfc::string_base & text, t_uint32 & flags) = 0; + //! Valid only if type is type_group. + virtual t_size get_children_count() = 0; + //! Valid only if type is type_group. + virtual ptr get_child(t_size index) = 0; + //! Valid only if type is type_command. + virtual void execute(service_ptr_t callback) = 0; + //! Valid only if type is type_command. + virtual GUID get_guid() = 0; + //! Valid only if type is type_command. + virtual bool get_description(pfc::string_base & out) {return false;} + +}; + +class mainmenu_node_separator : public mainmenu_node { +public: + t_uint32 get_type() {return type_separator;} + void get_display(pfc::string_base & text, t_uint32 & flags) {text = ""; flags = 0;} + t_size get_children_count() {return 0;} + ptr get_child(t_size index) {throw pfc::exception_invalid_params();} + void execute(service_ptr_t) {} + GUID get_guid() {return pfc::guid_null;} +}; + +class mainmenu_node_command : public mainmenu_node { +public: + t_uint32 get_type() {return type_command;} + t_size get_children_count() {return 0;} + ptr get_child(t_size index) {throw pfc::exception_invalid_params();} +/* + void get_display(pfc::string_base & text, t_uint32 & flags); + void execute(service_ptr_t callback); + GUID get_guid(); + bool get_description(pfc::string_base & out) {return false;} +*/ +}; + +class mainmenu_node_group : public mainmenu_node { +public: + t_uint32 get_type() {return type_group;} + void execute(service_ptr_t callback) {} + GUID get_guid() {return pfc::guid_null;} +/* + void get_display(pfc::string_base & text, t_uint32 & flags); + t_size get_children_count(); + ptr get_child(t_size index); +*/ +}; + + +// \since 1.0 +class NOVTABLE mainmenu_commands_v2 : public mainmenu_commands { + FB2K_MAKE_SERVICE_INTERFACE(mainmenu_commands_v2, mainmenu_commands) +public: + virtual bool is_command_dynamic(t_uint32 index) = 0; + //! Valid only when is_command_dynamic() returns true. Behavior undefined otherwise. + virtual mainmenu_node::ptr dynamic_instantiate(t_uint32 index) = 0; + //! Default fallback implementation provided. + virtual bool dynamic_execute(t_uint32 index, const GUID & subID, service_ptr_t callback); +}; diff --git a/SDK/foobar2000/SDK/menu_helpers.cpp b/SDK/foobar2000/SDK/menu_helpers.cpp new file mode 100644 index 0000000..11bd8d1 --- /dev/null +++ b/SDK/foobar2000/SDK/menu_helpers.cpp @@ -0,0 +1,297 @@ +#include "foobar2000.h" + + +bool menu_helpers::context_get_description(const GUID& p_guid,pfc::string_base & out) { + service_ptr_t ptr; t_uint32 index; + if (!menu_item_resolver::g_resolve_context_command(p_guid, ptr, index)) return false; + bool rv = ptr->get_item_description(index, out); + if (!rv) out.reset(); + return rv; +} + +static bool run_context_command_internal(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t & data,const GUID & caller) { + if (data.get_count() == 0) return false; + service_ptr_t ptr; t_uint32 index; + if (!menu_item_resolver::g_resolve_context_command(p_command, ptr, index)) return false; + + { + TRACK_CALL_TEXT("menu_helpers::run_command(), by GUID"); + ptr->item_execute_simple(index, p_subcommand, data, caller); + } + + return true; +} + +bool menu_helpers::run_command_context(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t & data) +{ + return run_context_command_internal(p_command,p_subcommand,data,contextmenu_item::caller_undefined); +} + +bool menu_helpers::run_command_context_ex(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t & data,const GUID & caller) +{ + return run_context_command_internal(p_command,p_subcommand,data,caller); +} + +bool menu_helpers::test_command_context(const GUID & p_guid) +{ + service_ptr_t ptr; t_uint32 index; + return menu_item_resolver::g_resolve_context_command(p_guid, ptr, index); +} + +static bool g_is_checked(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t & data,const GUID & caller) +{ + service_ptr_t ptr; t_uint32 index; + if (!menu_item_resolver::g_resolve_context_command(p_command, ptr, index)) return false; + + unsigned displayflags = 0; + pfc::string_formatter dummystring; + if (!ptr->item_get_display_data(dummystring,displayflags,index,p_subcommand,data,caller)) return false; + return (displayflags & contextmenu_item_node::FLAG_CHECKED) != 0; + +} + +bool menu_helpers::is_command_checked_context(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t & data) +{ + return g_is_checked(p_command,p_subcommand,data,contextmenu_item::caller_undefined); +} + +bool menu_helpers::is_command_checked_context_playlist(const GUID & p_command,const GUID & p_subcommand) +{ + metadb_handle_list temp; + static_api_ptr_t api; + api->activeplaylist_get_selected_items(temp); + return g_is_checked(p_command,p_subcommand,temp,contextmenu_item::caller_playlist); +} + + + + + + + +bool menu_helpers::run_command_context_playlist(const GUID & p_command,const GUID & p_subcommand) +{ + metadb_handle_list temp; + static_api_ptr_t api; + api->activeplaylist_get_selected_items(temp); + return run_command_context_ex(p_command,p_subcommand,temp,contextmenu_item::caller_playlist); +} + +bool menu_helpers::run_command_context_now_playing(const GUID & p_command,const GUID & p_subcommand) +{ + metadb_handle_ptr item; + if (!static_api_ptr_t()->get_now_playing(item)) return false;//not playing + return run_command_context_ex(p_command,p_subcommand,pfc::list_single_ref_t(item),contextmenu_item::caller_now_playing); +} + + +bool menu_helpers::guid_from_name(const char * p_name,unsigned p_name_len,GUID & p_out) +{ + service_enum_t e; + service_ptr_t ptr; + pfc::string8_fastalloc nametemp; + while(e.next(ptr)) + { + unsigned n, m = ptr->get_num_items(); + for(n=0;nget_item_name(n,nametemp); + if (!strcmp_ex(nametemp,~0,p_name,p_name_len)) + { + p_out = ptr->get_item_guid(n); + return true; + } + } + } + return false; +} + +bool menu_helpers::name_from_guid(const GUID & p_guid,pfc::string_base & p_out) { + service_ptr_t ptr; t_uint32 index; + if (!menu_item_resolver::g_resolve_context_command(p_guid, ptr, index)) return false; + ptr->get_item_name(index, p_out); + return true; +} + + +static unsigned calc_total_action_count() +{ + service_enum_t e; + service_ptr_t ptr; + unsigned ret = 0; + while(e.next(ptr)) + ret += ptr->get_num_items(); + return ret; +} + + +const char * menu_helpers::guid_to_name_table::search(const GUID & p_guid) +{ + if (!m_inited) + { + m_data.set_size(calc_total_action_count()); + t_size dataptr = 0; + pfc::string8_fastalloc nametemp; + + service_enum_t e; + service_ptr_t ptr; + while(e.next(ptr)) + { + unsigned n, m = ptr->get_num_items(); + for(n=0;nget_item_name(n,nametemp); + m_data[dataptr].m_name = _strdup(nametemp); + m_data[dataptr].m_guid = ptr->get_item_guid(n); + dataptr++; + } + } + assert(dataptr == m_data.get_size()); + + pfc::sort_t(m_data,entry_compare,m_data.get_size()); + m_inited = true; + } + t_size index; + if (pfc::bsearch_t(m_data.get_size(),m_data,entry_compare_search,p_guid,index)) + return m_data[index].m_name; + else + return 0; +} + +int menu_helpers::guid_to_name_table::entry_compare_search(const entry & entry1,const GUID & entry2) +{ + return pfc::guid_compare(entry1.m_guid,entry2); +} + +int menu_helpers::guid_to_name_table::entry_compare(const entry & entry1,const entry & entry2) +{ + return pfc::guid_compare(entry1.m_guid,entry2.m_guid); +} + +menu_helpers::guid_to_name_table::guid_to_name_table() +{ + m_inited = false; +} + +menu_helpers::guid_to_name_table::~guid_to_name_table() +{ + t_size n, m = m_data.get_size(); + for(n=0;n e; + service_ptr_t ptr; + while(e.next(ptr)) + { + unsigned n, m = ptr->get_num_items(); + for(n=0;nget_item_name(n,nametemp); + m_data[dataptr].m_name = _strdup(nametemp); + m_data[dataptr].m_guid = ptr->get_item_guid(n); + dataptr++; + } + } + assert(dataptr == m_data.get_size()); + + pfc::sort_t(m_data,entry_compare,m_data.get_size()); + m_inited = true; + } + t_size index; + search_entry temp = {p_name,p_name_len}; + if (pfc::bsearch_t(m_data.get_size(),m_data,entry_compare_search,temp,index)) + { + p_out = m_data[index].m_guid; + return true; + } + else + return false; +} + +menu_helpers::name_to_guid_table::name_to_guid_table() +{ + m_inited = false; +} + +menu_helpers::name_to_guid_table::~name_to_guid_table() +{ + t_size n, m = m_data.get_size(); + for(n=0;n & p_item,unsigned & p_index) +{ + pfc::string8_fastalloc path,name; + service_enum_t e; + service_ptr_t ptr; + if (e.first(ptr)) do { +// if (ptr->get_type()==type) + { + unsigned action,num_actions = ptr->get_num_items(); + for(action=0;actionget_item_default_path(action,path); ptr->get_item_name(action,name); + if (!path.is_empty()) path += "/"; + path += name; + if (!stricmp_utf8(p_name,path)) + { + p_item = ptr; + p_index = action; + return true; + } + } + } + } while(e.next(ptr)); + return false; + +} + +bool menu_helpers::find_command_by_name(const char * p_name,GUID & p_command) +{ + service_ptr_t item; + unsigned index; + bool ret = find_command_by_name(p_name,item,index); + if (ret) p_command = item->get_item_guid(index); + return ret; +} + + +bool standard_commands::run_main(const GUID & p_guid) { + t_uint32 index; + mainmenu_commands::ptr ptr; + if (!menu_item_resolver::g_resolve_main_command(p_guid, ptr, index)) return false; + ptr->execute(index,service_ptr_t()); + return true; +} + +bool menu_item_resolver::g_resolve_context_command(const GUID & id, contextmenu_item::ptr & out, t_uint32 & out_index) { + return static_api_ptr_t()->resolve_context_command(id, out, out_index); +} +bool menu_item_resolver::g_resolve_main_command(const GUID & id, mainmenu_commands::ptr & out, t_uint32 & out_index) { + return static_api_ptr_t()->resolve_main_command(id, out, out_index); +} diff --git a/SDK/foobar2000/SDK/menu_helpers.h b/SDK/foobar2000/SDK/menu_helpers.h new file mode 100644 index 0000000..08bcb13 --- /dev/null +++ b/SDK/foobar2000/SDK/menu_helpers.h @@ -0,0 +1,183 @@ +namespace menu_helpers { +#ifdef _WIN32 + void win32_auto_mnemonics(HMENU menu); +#endif + + bool run_command_context(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t & data); + bool run_command_context_ex(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t & data,const GUID & caller); + bool run_command_context_playlist(const GUID & p_command,const GUID & p_subcommand); + bool run_command_context_now_playing(const GUID & p_command,const GUID & p_subcommand); + + bool test_command_context(const GUID & p_guid); + + bool is_command_checked_context(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t & data); + bool is_command_checked_context_playlist(const GUID & p_command,const GUID & p_subcommand); + + bool find_command_by_name(const char * p_name,service_ptr_t & p_item,unsigned & p_index); + bool find_command_by_name(const char * p_name,GUID & p_command); + + bool context_get_description(const GUID& p_guid,pfc::string_base & out); + + bool guid_from_name(const char * p_name,unsigned p_name_len,GUID & p_out); + bool name_from_guid(const GUID & p_guid,pfc::string_base & p_out); + + class guid_to_name_table + { + public: + guid_to_name_table(); + ~guid_to_name_table(); + const char * search(const GUID & p_guid); + private: + struct entry { + char* m_name; + GUID m_guid; + }; + pfc::array_t m_data; + bool m_inited; + + static int entry_compare_search(const entry & entry1,const GUID & entry2); + static int entry_compare(const entry & entry1,const entry & entry2); + }; + + class name_to_guid_table + { + public: + name_to_guid_table(); + ~name_to_guid_table(); + bool search(const char * p_name,unsigned p_name_len,GUID & p_out); + private: + struct entry { + char* m_name; + GUID m_guid; + }; + pfc::array_t m_data; + bool m_inited; + struct search_entry { + const char * m_name; unsigned m_name_len; + }; + + static int entry_compare_search(const entry & entry1,const search_entry & entry2); + static int entry_compare(const entry & entry1,const entry & entry2); + }; + +}; + + + +class standard_commands +{ +public: + static const GUID + guid_context_file_properties, guid_context_file_open_directory, guid_context_copy_names, + guid_context_send_to_playlist, guid_context_reload_info, guid_context_reload_info_if_changed, + guid_context_rewrite_info, guid_context_remove_tags, + guid_context_convert_run, guid_context_convert_run_singlefile,guid_context_convert_run_withcue, + guid_context_write_cd, + guid_context_rg_scan_track, guid_context_rg_scan_album, guid_context_rg_scan_album_multi, + guid_context_rg_remove, guid_context_save_playlist, guid_context_masstag_edit, + guid_context_masstag_rename, + guid_main_always_on_top, guid_main_preferences, guid_main_about, + guid_main_exit, guid_main_restart, guid_main_activate, + guid_main_hide, guid_main_activate_or_hide, guid_main_titleformat_help, + guid_main_next, guid_main_previous, + guid_main_next_or_random, guid_main_random, guid_main_pause, + guid_main_play, guid_main_play_or_pause, guid_main_rg_set_album, + guid_main_rg_set_track, guid_main_rg_disable, guid_main_rg_byorder, + guid_main_stop, + guid_main_stop_after_current, guid_main_volume_down, guid_main_volume_up, + guid_main_volume_mute, guid_main_add_directory, guid_main_add_files, + guid_main_add_location, guid_main_add_playlist, guid_main_clear_playlist, + guid_main_create_playlist, guid_main_highlight_playing, guid_main_load_playlist, + guid_main_next_playlist, guid_main_previous_playlist, guid_main_open, + guid_main_remove_playlist, guid_main_remove_dead_entries, guid_main_remove_duplicates, + guid_main_rename_playlist, guid_main_save_all_playlists, guid_main_save_playlist, + guid_main_playlist_search, guid_main_playlist_sel_crop, guid_main_playlist_sel_remove, + guid_main_playlist_sel_invert, guid_main_playlist_undo, guid_main_show_console, + guid_main_play_cd, guid_main_restart_resetconfig, guid_main_record, + guid_main_playlist_moveback, guid_main_playlist_moveforward, guid_main_playlist_redo, + guid_main_playback_follows_cursor, guid_main_cursor_follows_playback, guid_main_saveconfig, + guid_main_playlist_select_all, guid_main_show_now_playing, + + guid_seek_ahead_1s, guid_seek_ahead_5s, guid_seek_ahead_10s, guid_seek_ahead_30s, + guid_seek_ahead_1min, guid_seek_ahead_2min, guid_seek_ahead_5min, guid_seek_ahead_10min, + + guid_seek_back_1s, guid_seek_back_5s, guid_seek_back_10s, guid_seek_back_30s, + guid_seek_back_1min, guid_seek_back_2min, guid_seek_back_5min, guid_seek_back_10min + ; + + static bool run_main(const GUID & guid); + static inline bool run_context(const GUID & guid,const pfc::list_base_const_t &data) {return menu_helpers::run_command_context(guid,pfc::guid_null,data);} + static inline bool run_context(const GUID & guid,const pfc::list_base_const_t &data,const GUID& caller) {return menu_helpers::run_command_context_ex(guid,pfc::guid_null,data,caller);} + + static inline bool context_file_properties(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_file_properties,data,caller);} + static inline bool context_file_open_directory(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_file_open_directory,data,caller);} + static inline bool context_copy_names(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_copy_names,data,caller);} + static inline bool context_send_to_playlist(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_send_to_playlist,data,caller);} + static inline bool context_reload_info(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_reload_info,data,caller);} + static inline bool context_reload_info_if_changed(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_reload_info_if_changed,data,caller);} + static inline bool context_rewrite_info(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_rewrite_info,data,caller);} + static inline bool context_remove_tags(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_remove_tags,data,caller);} + static inline bool context_convert_run(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_convert_run,data,caller);} + static inline bool context_convert_run_singlefile(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_convert_run_singlefile,data,caller);} + static inline bool context_write_cd(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_write_cd,data,caller);} + static inline bool context_rg_scan_track(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_rg_scan_track,data,caller);} + static inline bool context_rg_scan_album(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_rg_scan_album,data,caller);} + static inline bool context_rg_scan_album_multi(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_rg_scan_album_multi,data,caller);} + static inline bool context_rg_remove(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_rg_remove,data,caller);} + static inline bool context_save_playlist(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_save_playlist,data,caller);} + static inline bool context_masstag_edit(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_masstag_edit,data,caller);} + static inline bool context_masstag_rename(const pfc::list_base_const_t &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_masstag_rename,data,caller);} + static inline bool main_always_on_top() {return run_main(guid_main_always_on_top);} + static inline bool main_preferences() {return run_main(guid_main_preferences);} + static inline bool main_about() {return run_main(guid_main_about);} + static inline bool main_exit() {return run_main(guid_main_exit);} + static inline bool main_restart() {return run_main(guid_main_restart);} + static inline bool main_activate() {return run_main(guid_main_activate);} + static inline bool main_hide() {return run_main(guid_main_hide);} + static inline bool main_activate_or_hide() {return run_main(guid_main_activate_or_hide);} + static inline bool main_titleformat_help() {return run_main(guid_main_titleformat_help);} + static inline bool main_playback_follows_cursor() {return run_main(guid_main_playback_follows_cursor);} + static inline bool main_next() {return run_main(guid_main_next);} + static inline bool main_previous() {return run_main(guid_main_previous);} + static inline bool main_next_or_random() {return run_main(guid_main_next_or_random);} + static inline bool main_random() {return run_main(guid_main_random);} + static inline bool main_pause() {return run_main(guid_main_pause);} + static inline bool main_play() {return run_main(guid_main_play);} + static inline bool main_play_or_pause() {return run_main(guid_main_play_or_pause);} + static inline bool main_rg_set_album() {return run_main(guid_main_rg_set_album);} + static inline bool main_rg_set_track() {return run_main(guid_main_rg_set_track);} + static inline bool main_rg_disable() {return run_main(guid_main_rg_disable);} + static inline bool main_stop() {return run_main(guid_main_stop);} + static inline bool main_stop_after_current() {return run_main(guid_main_stop_after_current);} + static inline bool main_volume_down() {return run_main(guid_main_volume_down);} + static inline bool main_volume_up() {return run_main(guid_main_volume_up);} + static inline bool main_volume_mute() {return run_main(guid_main_volume_mute);} + static inline bool main_add_directory() {return run_main(guid_main_add_directory);} + static inline bool main_add_files() {return run_main(guid_main_add_files);} + static inline bool main_add_location() {return run_main(guid_main_add_location);} + static inline bool main_add_playlist() {return run_main(guid_main_add_playlist);} + static inline bool main_clear_playlist() {return run_main(guid_main_clear_playlist);} + static inline bool main_create_playlist() {return run_main(guid_main_create_playlist);} + static inline bool main_highlight_playing() {return run_main(guid_main_highlight_playing);} + static inline bool main_load_playlist() {return run_main(guid_main_load_playlist);} + static inline bool main_next_playlist() {return run_main(guid_main_next_playlist);} + static inline bool main_previous_playlist() {return run_main(guid_main_previous_playlist);} + static inline bool main_open() {return run_main(guid_main_open);} + static inline bool main_remove_playlist() {return run_main(guid_main_remove_playlist);} + static inline bool main_remove_dead_entries() {return run_main(guid_main_remove_dead_entries);} + static inline bool main_remove_duplicates() {return run_main(guid_main_remove_duplicates);} + static inline bool main_rename_playlist() {return run_main(guid_main_rename_playlist);} + static inline bool main_save_all_playlists() {return run_main(guid_main_save_all_playlists);} + static inline bool main_save_playlist() {return run_main(guid_main_save_playlist);} + static inline bool main_playlist_search() {return run_main(guid_main_playlist_search);} + static inline bool main_playlist_sel_crop() {return run_main(guid_main_playlist_sel_crop);} + static inline bool main_playlist_sel_remove() {return run_main(guid_main_playlist_sel_remove);} + static inline bool main_playlist_sel_invert() {return run_main(guid_main_playlist_sel_invert);} + static inline bool main_playlist_undo() {return run_main(guid_main_playlist_undo);} + static inline bool main_show_console() {return run_main(guid_main_show_console);} + static inline bool main_play_cd() {return run_main(guid_main_play_cd);} + static inline bool main_restart_resetconfig() {return run_main(guid_main_restart_resetconfig);} + static inline bool main_playlist_moveback() {return run_main(guid_main_playlist_moveback);} + static inline bool main_playlist_moveforward() {return run_main(guid_main_playlist_moveforward);} + static inline bool main_saveconfig() {return run_main(guid_main_saveconfig);} +}; diff --git a/SDK/foobar2000/SDK/menu_item.cpp b/SDK/foobar2000/SDK/menu_item.cpp new file mode 100644 index 0000000..9d63089 --- /dev/null +++ b/SDK/foobar2000/SDK/menu_item.cpp @@ -0,0 +1,61 @@ +#include "foobar2000.h" + + + +bool contextmenu_item::item_get_display_data_root(pfc::string_base & p_out,unsigned & p_displayflags,unsigned p_index,const pfc::list_base_const_t & p_data,const GUID & p_caller) +{ + bool status = false; + pfc::ptrholder_t root ( instantiate_item(p_index,p_data,p_caller) ); + if (root.is_valid()) status = root->get_display_data(p_out,p_displayflags,p_data,p_caller); + return status; +} + + +static contextmenu_item_node * g_find_node(const GUID & p_guid,contextmenu_item_node * p_parent) +{ + if (p_parent->get_guid() == p_guid) return p_parent; + else if (p_parent->get_type() == contextmenu_item_node::TYPE_POPUP) + { + t_size n, m = p_parent->get_children_count(); + for(n=0;nget_child(n)); + if (temp) return temp; + } + return 0; + } + else return 0; +} + +bool contextmenu_item::item_get_display_data(pfc::string_base & p_out,unsigned & p_displayflags,unsigned p_index,const GUID & p_node,const pfc::list_base_const_t & p_data,const GUID & p_caller) +{ + bool status = false; + pfc::ptrholder_t root ( instantiate_item(p_index,p_data,p_caller) ); + if (root.is_valid()) + { + contextmenu_item_node * node = g_find_node(p_node,root.get_ptr()); + if (node) status = node->get_display_data(p_out,p_displayflags,p_data,p_caller); + } + return status; +} + + +GUID contextmenu_item::get_parent_fallback() { + unsigned total = get_num_items(); + if (total < 1) return pfc::guid_null; // hide the item + pfc::string_formatter path, base; this->get_item_default_path(0, base); + for(unsigned walk = 1; walk < total; ++walk) { + this->get_item_default_path(walk, path); + if (strcmp(path, base) != 0) return contextmenu_groups::legacy; + } + return static_api_ptr_t()->path_to_group(base); +} + +GUID contextmenu_item::get_parent_() { + contextmenu_item_v2::ptr v2; + if (service_query_t(v2)) { + return v2->get_parent(); + } else { + return get_parent_fallback(); + } +} diff --git a/SDK/foobar2000/SDK/menu_manager.cpp b/SDK/foobar2000/SDK/menu_manager.cpp new file mode 100644 index 0000000..aa3f86a --- /dev/null +++ b/SDK/foobar2000/SDK/menu_manager.cpp @@ -0,0 +1,410 @@ +#include "foobar2000.h" + +#ifdef WIN32 + +static void fix_ampersand(const char * src,pfc::string_base & out) +{ + out.reset(); + unsigned ptr = 0; + while(src[ptr]) + { + if (src[ptr]=='&') + { + out.add_string("&&"); + ptr++; + while(src[ptr]=='&') + { + out.add_string("&&"); + ptr++; + } + } + else out.add_byte(src[ptr++]); + } +} + +static unsigned flags_to_win32(unsigned flags) +{ + unsigned ret = 0; + if (flags & contextmenu_item_node::FLAG_RADIOCHECKED) {/* dealt with elsewhere */} + else if (flags & contextmenu_item_node::FLAG_CHECKED) ret |= MF_CHECKED; + if (flags & contextmenu_item_node::FLAG_DISABLED) ret |= MF_DISABLED; + if (flags & contextmenu_item_node::FLAG_GRAYED) ret |= MF_GRAYED; + return ret; +} + +void contextmenu_manager::win32_build_menu(HMENU menu,contextmenu_node * parent,int base_id,int max_id)//menu item identifiers are base_id<=Nget_type()==contextmenu_item_node::TYPE_POPUP) + { + pfc::string8_fastalloc temp; + t_size child_idx,child_num = parent->get_num_children(); + for(child_idx=0;child_idxget_child(child_idx); + if (child) + { + const char * name = child->get_name(); + if (strchr(name,'&')) {fix_ampersand(name,temp);name=temp;} + contextmenu_item_node::t_type type = child->get_type(); + if (type==contextmenu_item_node::TYPE_POPUP) + { + HMENU new_menu = CreatePopupMenu(); + uAppendMenu(menu,MF_STRING|MF_POPUP | flags_to_win32(child->get_display_flags()),(UINT_PTR)new_menu,name); + win32_build_menu(new_menu,child,base_id,max_id); + } + else if (type==contextmenu_item_node::TYPE_SEPARATOR) + { + uAppendMenu(menu,MF_SEPARATOR,0,0); + } + else if (type==contextmenu_item_node::TYPE_COMMAND) + { + int id = child->get_id(); + if (id>=0 && (max_id<0 || idget_display_flags(); + const UINT ID = base_id+id; + uAppendMenu(menu,MF_STRING | flags_to_win32(flags),ID,name); + if (flags & contextmenu_item_node::FLAG_RADIOCHECKED) CheckMenuRadioItem(menu,ID,ID,ID,MF_BYCOMMAND); + } + } + } + } + } +} + +#endif + +bool contextmenu_manager::get_description_by_id(unsigned id,pfc::string_base & out) { + contextmenu_node * ptr = find_by_id(id); + if (ptr == NULL) return false; + return ptr->get_description(out); +} +bool contextmenu_manager::execute_by_id(unsigned id) { + contextmenu_node * ptr = find_by_id(id); + if (ptr == NULL) return false; + ptr->execute(); + return true; +} + +#ifdef WIN32 + +void contextmenu_manager::win32_run_menu_popup(HWND parent,const POINT * pt) +{ + enum {ID_CUSTOM_BASE = 1}; + + int cmd; + + { + POINT p; + if (pt) p = *pt; + else GetCursorPos(&p); + + HMENU hmenu = CreatePopupMenu(); + try { + + win32_build_menu(hmenu,ID_CUSTOM_BASE,-1); + menu_helpers::win32_auto_mnemonics(hmenu); + + cmd = TrackPopupMenu(hmenu,TPM_RIGHTBUTTON|TPM_NONOTIFY|TPM_RETURNCMD,p.x,p.y,0,parent,0); + } catch(...) {DestroyMenu(hmenu); throw;} + + DestroyMenu(hmenu); + } + + if (cmd>0) + { + if (cmd>=ID_CUSTOM_BASE) + { + execute_by_id(cmd - ID_CUSTOM_BASE); + } + } +} + +void contextmenu_manager::win32_run_menu_context(HWND parent,const pfc::list_base_const_t & data,const POINT * pt,unsigned flags) +{ + service_ptr_t manager; + contextmenu_manager::g_create(manager); + manager->init_context(data,flags); + manager->win32_run_menu_popup(parent,pt); +} + +void contextmenu_manager::win32_run_menu_context_playlist(HWND parent,const POINT * pt,unsigned flags) +{ + service_ptr_t manager; + contextmenu_manager::g_create(manager); + manager->init_context_playlist(flags); + manager->win32_run_menu_popup(parent,pt); +} + + +namespace { + class mnemonic_manager + { + pfc::string8_fastalloc used; + bool is_used(unsigned c) + { + char temp[8]; + temp[pfc::utf8_encode_char(uCharLower(c),temp)]=0; + return !!strstr(used,temp); + } + + static bool is_alphanumeric(char c) + { + return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9'); + } + + + + + void insert(const char * src,unsigned idx,pfc::string_base & out) + { + out.reset(); + out.add_string(src,idx); + out.add_string("&"); + out.add_string(src+idx); + used.add_char(uCharLower(src[idx])); + } + public: + bool check_string(const char * src) + {//check for existing mnemonics + const char * ptr = src; + while(ptr = strchr(ptr,'&')) + { + if (ptr[1]=='&') ptr+=2; + else + { + unsigned c = 0; + if (pfc::utf8_decode_char(ptr+1,c)>0) + { + if (!is_used(c)) used.add_char(uCharLower(c)); + } + return true; + } + } + return false; + } + bool process_string(const char * src,pfc::string_base & out)//returns if changed + { + if (check_string(src)) {out=src;return false;} + unsigned idx=0; + while(src[idx]==' ') idx++; + while(src[idx]) + { + if (is_alphanumeric(src[idx]) && !is_used(src[idx])) + { + insert(src,idx,out); + return true; + } + + while(src[idx] && src[idx]!=' ' && src[idx]!='\t') idx++; + if (src[idx]=='\t') break; + while(src[idx]==' ') idx++; + } + + //no success picking first letter of one of words + idx=0; + while(src[idx]) + { + if (src[idx]=='\t') break; + if (is_alphanumeric(src[idx]) && !is_used(src[idx])) + { + insert(src,idx,out); + return true; + } + idx++; + } + + //giving up + out = src; + return false; + } + }; +} + +void menu_helpers::win32_auto_mnemonics(HMENU menu) +{ + mnemonic_manager mgr; + unsigned n, m = GetMenuItemCount(menu); + pfc::string8_fastalloc temp,temp2; + for(n=0;n & data,WPARAM wp,const GUID & caller) +{ + if (data.get_count()==0) return false; + return process_keydown_ex(TYPE_CONTEXT,data,get_key_code(wp),caller); +} + +bool keyboard_shortcut_manager::on_keydown_auto(WPARAM wp) +{ + if (on_keydown(TYPE_MAIN,wp)) return true; + if (on_keydown(TYPE_CONTEXT_PLAYLIST,wp)) return true; + if (on_keydown(TYPE_CONTEXT_NOW_PLAYING,wp)) return true; + return false; +} + +bool keyboard_shortcut_manager::on_keydown_auto_playlist(WPARAM wp) +{ + metadb_handle_list data; + static_api_ptr_t api; + api->activeplaylist_get_selected_items(data); + return on_keydown_auto_context(data,wp,contextmenu_item::caller_playlist); +} + +bool keyboard_shortcut_manager::on_keydown_auto_context(const pfc::list_base_const_t & data,WPARAM wp,const GUID & caller) +{ + if (on_keydown_context(data,wp,caller)) return true; + else return on_keydown_auto(wp); +} + +static bool should_relay_key_restricted(UINT p_key) { + switch(p_key) { + case VK_LEFT: + case VK_RIGHT: + case VK_UP: + case VK_DOWN: + return false; + default: + return (p_key >= VK_F1 && p_key <= VK_F24) || IsKeyPressed(VK_CONTROL) || IsKeyPressed(VK_LWIN) || IsKeyPressed(VK_RWIN); + } +} + +bool keyboard_shortcut_manager::on_keydown_restricted_auto(WPARAM wp) { + if (!should_relay_key_restricted(wp)) return false; + return on_keydown_auto(wp); +} +bool keyboard_shortcut_manager::on_keydown_restricted_auto_playlist(WPARAM wp) { + if (!should_relay_key_restricted(wp)) return false; + return on_keydown_auto_playlist(wp); +} +bool keyboard_shortcut_manager::on_keydown_restricted_auto_context(const pfc::list_base_const_t & data,WPARAM wp,const GUID & caller) { + if (!should_relay_key_restricted(wp)) return false; + return on_keydown_auto_context(data,wp,caller); +} + +static bool filterTypableWindowMessage(const MSG * msg, t_uint32 modifiers) { + if (keyboard_shortcut_manager::is_typing_key_combo((t_uint32)msg->wParam, modifiers)) { + try { + if (static_api_ptr_t()->is_registered(msg->hwnd)) return false; + } catch(exception_service_not_found) {} + } + return true; +} + +bool keyboard_shortcut_manager_v2::pretranslate_message(const MSG * msg, HWND thisPopupWnd) { + switch(msg->message) { + case WM_KEYDOWN: + case WM_SYSKEYDOWN: + if (thisPopupWnd != NULL && FindOwningPopup(msg->hwnd) == thisPopupWnd) { + const t_uint32 modifiers = GetHotkeyModifierFlags(); + if (filterTypableWindowMessage(msg, modifiers)) { + if (process_keydown_simple(get_key_code(msg->wParam,modifiers))) return true; + } + } + return false; + default: + return false; + } +} + +bool keyboard_shortcut_manager::is_text_key(t_uint32 vkCode) { + return vkCode == VK_SPACE + || (vkCode >= '0' && vkCode < 0x40) + || (vkCode > 0x40 && vkCode < VK_LWIN) + || (vkCode >= VK_NUMPAD0 && vkCode <= VK_DIVIDE) + || (vkCode >= VK_OEM_1 && vkCode <= VK_OEM_3) + || (vkCode >= VK_OEM_4 && vkCode <= VK_OEM_8) + ; +} + +bool keyboard_shortcut_manager::is_typing_key(t_uint32 vkCode) { + return is_text_key(vkCode) + || vkCode == VK_BACK + || vkCode == VK_RETURN + || vkCode == VK_INSERT + || (vkCode > VK_SPACE && vkCode < '0'); +} + +bool keyboard_shortcut_manager::is_typing_key_combo(t_uint32 vkCode, t_uint32 modifiers) { + if (!is_typing_modifier(modifiers)) return false; + return is_typing_key(vkCode); +} + +bool keyboard_shortcut_manager::is_typing_modifier(t_uint32 flags) { + flags &= ~MOD_SHIFT; + return flags == 0 || flags == (MOD_ALT | MOD_CONTROL); +} + +bool keyboard_shortcut_manager::is_typing_message(HWND editbox, const MSG * msg) { + if (msg->hwnd != editbox) return false; + return is_typing_message(msg); +} +bool keyboard_shortcut_manager::is_typing_message(const MSG * msg) { + if (msg->message != WM_KEYDOWN && msg->message != WM_SYSKEYDOWN) return false; + return is_typing_key_combo(msg->wParam, GetHotkeyModifierFlags()); +} diff --git a/SDK/foobar2000/SDK/message_loop.h b/SDK/foobar2000/SDK/message_loop.h new file mode 100644 index 0000000..88d8b2d --- /dev/null +++ b/SDK/foobar2000/SDK/message_loop.h @@ -0,0 +1,97 @@ +class NOVTABLE message_filter +{ +public: + virtual bool pretranslate_message(MSG * p_msg) = 0; +}; + +class NOVTABLE idle_handler { +public: + virtual bool on_idle() = 0; +}; + +class NOVTABLE message_loop : public service_base +{ +public: + virtual void add_message_filter(message_filter * ptr) = 0; + virtual void remove_message_filter(message_filter * ptr) = 0; + + virtual void add_idle_handler(idle_handler * ptr) = 0; + virtual void remove_idle_handler(idle_handler * ptr) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(message_loop); +}; + +class NOVTABLE message_loop_v2 : public message_loop { +public: + virtual void add_message_filter_ex(message_filter * ptr, t_uint32 lowest, t_uint32 highest) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(message_loop_v2, message_loop); +}; + +class message_filter_impl_base : public message_filter { +public: + message_filter_impl_base() {static_api_ptr_t()->add_message_filter(this);} + message_filter_impl_base(t_uint32 lowest, t_uint32 highest) { + static_api_ptr_t api; + message_loop_v2::ptr apiV2; + if (api->service_query_t(apiV2)) { + apiV2->add_message_filter_ex(this, lowest, highest); + } else { + api->add_message_filter(this); + } + } + ~message_filter_impl_base() {static_api_ptr_t()->remove_message_filter(this);} + bool pretranslate_message(MSG * p_msg) {return false;} + + PFC_CLASS_NOT_COPYABLE(message_filter_impl_base,message_filter_impl_base); +}; + +class message_filter_impl_accel : public message_filter_impl_base { +protected: + bool pretranslate_message(MSG * p_msg) { + if (m_wnd != NULL) { + if (GetActiveWindow() == m_wnd) { + if (TranslateAccelerator(m_wnd,m_accel.get(),p_msg) != 0) { + return true; + } + } + } + return false; + } +public: + message_filter_impl_accel(HINSTANCE p_instance,const TCHAR * p_accel) : m_wnd(NULL) { + m_accel.load(p_instance,p_accel); + } + void set_wnd(HWND p_wnd) {m_wnd = p_wnd;} +private: + HWND m_wnd; + win32_accelerator m_accel; + + PFC_CLASS_NOT_COPYABLE(message_filter_impl_accel,message_filter_impl_accel); +}; + +class message_filter_remap_f1 : public message_filter_impl_base { +public: + bool pretranslate_message(MSG * p_msg) { + if (IsOurMsg(p_msg) && m_wnd != NULL && GetActiveWindow() == m_wnd) { + ::PostMessage(m_wnd, WM_SYSCOMMAND, SC_CONTEXTHELP, -1); + return true; + } + return false; + } + void set_wnd(HWND wnd) {m_wnd = wnd;} +private: + static bool IsOurMsg(const MSG * msg) { + return msg->message == WM_KEYDOWN && msg->wParam == VK_F1; + } + HWND m_wnd; +}; + +class idle_handler_impl_base : public idle_handler { +public: + idle_handler_impl_base() {static_api_ptr_t()->add_idle_handler(this);} + ~idle_handler_impl_base() {static_api_ptr_t()->remove_idle_handler(this);} + bool on_idle() {return true;} + + PFC_CLASS_NOT_COPYABLE_EX(idle_handler_impl_base) +}; diff --git a/SDK/foobar2000/SDK/metadb.cpp b/SDK/foobar2000/SDK/metadb.cpp new file mode 100644 index 0000000..2814663 --- /dev/null +++ b/SDK/foobar2000/SDK/metadb.cpp @@ -0,0 +1,76 @@ +#include "foobar2000.h" + + +void metadb::handle_create_replace_path_canonical(metadb_handle_ptr & p_out,const metadb_handle_ptr & p_source,const char * p_new_path) { + handle_create(p_out,make_playable_location(p_new_path,p_source->get_subsong_index())); +} + +void metadb::handle_create_replace_path(metadb_handle_ptr & p_out,const metadb_handle_ptr & p_source,const char * p_new_path) { + pfc::string8 path; + filesystem::g_get_canonical_path(p_new_path,path); + handle_create_replace_path_canonical(p_out,p_source,path); +} + +void metadb::handle_replace_path_canonical(metadb_handle_ptr & p_out,const char * p_new_path) { + metadb_handle_ptr temp; + handle_create_replace_path_canonical(temp,p_out,p_new_path); + p_out = temp; +} + + +metadb_io::t_load_info_state metadb_io::load_info(metadb_handle_ptr p_item,t_load_info_type p_type,HWND p_parent_window,bool p_show_errors) { + return load_info_multi(pfc::list_single_ref_t(p_item),p_type,p_parent_window,p_show_errors); +} + +metadb_io::t_update_info_state metadb_io::update_info(metadb_handle_ptr p_item,file_info & p_info,HWND p_parent_window,bool p_show_errors) +{ + file_info * blah = &p_info; + return update_info_multi(pfc::list_single_ref_t(p_item),pfc::list_single_ref_t(blah),p_parent_window,p_show_errors); +} + + +void metadb_io::hint_async(metadb_handle_ptr p_item,const file_info & p_info,const t_filestats & p_stats,bool p_fresh) +{ + const file_info * blargh = &p_info; + hint_multi_async(pfc::list_single_ref_t(p_item),pfc::list_single_ref_t(blargh),pfc::list_single_ref_t(p_stats),bit_array_val(p_fresh)); +} + + +bool metadb::g_get_random_handle(metadb_handle_ptr & p_out) { + if (static_api_ptr_t()->get_now_playing(p_out)) return true; + + { + static_api_ptr_t api; + + t_size playlist_count = api->get_playlist_count(); + t_size active_playlist = api->get_active_playlist(); + if (active_playlist != ~0) { + if (api->playlist_get_focus_item_handle(p_out,active_playlist)) return true; + } + + for(t_size n = 0; n < playlist_count; n++) { + if (api->playlist_get_focus_item_handle(p_out,n)) return true; + } + + if (active_playlist != ~0) { + t_size item_count = api->playlist_get_item_count(active_playlist); + if (item_count > 0) { + if (api->playlist_get_item_handle(p_out,active_playlist,0)) return true; + } + } + + for(t_size n = 0; n < playlist_count; n++) { + t_size item_count = api->playlist_get_item_count(n); + if (item_count > 0) { + if (api->playlist_get_item_handle(p_out,n,0)) return true; + } + } + } + + return false; +} + + +void metadb_io_v2::update_info_async_simple(const pfc::list_base_const_t & p_list,const pfc::list_base_const_t & p_new_info, HWND p_parent_window,t_uint32 p_op_flags,completion_notify_ptr p_notify) { + update_info_async(p_list,new service_impl_t(p_list,p_new_info),p_parent_window,p_op_flags,p_notify); +} \ No newline at end of file diff --git a/SDK/foobar2000/SDK/metadb.h b/SDK/foobar2000/SDK/metadb.h new file mode 100644 index 0000000..ee5638a --- /dev/null +++ b/SDK/foobar2000/SDK/metadb.h @@ -0,0 +1,393 @@ +//! API for tag read/write operations. Legal to call from main thread only, except for hint_multi_async() / hint_async() / hint_reader().\n +//! Implemented only by core, do not reimplement.\n +//! Use static_api_ptr_t template to access metadb_io methods.\n +//! WARNING: Methods that perform file access (tag reads/writes) run a modal message loop. They SHOULD NOT be called from global callbacks and such. +class NOVTABLE metadb_io : public service_base +{ +public: + enum t_load_info_type { + load_info_default, + load_info_force, + load_info_check_if_changed + }; + + enum t_update_info_state { + update_info_success, + update_info_aborted, + update_info_errors, + }; + + enum t_load_info_state { + load_info_success, + load_info_aborted, + load_info_errors, + }; + + //! No longer used - returns false always. + __declspec(deprecated) virtual bool is_busy() = 0; + //! No longer used - returns false always. + __declspec(deprecated) virtual bool is_updating_disabled() = 0; + //! No longer used - returns false always. + __declspec(deprecated) virtual bool is_file_updating_blocked() = 0; + //! No longer used. + __declspec(deprecated) virtual void highlight_running_process() = 0; + //! Loads tags from multiple items. Use the async version in metadb_io_v2 instead if possible. + __declspec(deprecated) virtual t_load_info_state load_info_multi(metadb_handle_list_cref p_list,t_load_info_type p_type,HWND p_parent_window,bool p_show_errors) = 0; + //! Updates tags on multiple items. Use the async version in metadb_io_v2 instead if possible. + __declspec(deprecated) virtual t_update_info_state update_info_multi(metadb_handle_list_cref p_list,const pfc::list_base_const_t & p_new_info,HWND p_parent_window,bool p_show_errors) = 0; + //! Rewrites tags on multiple items. Use the async version in metadb_io_v2 instead if possible. + __declspec(deprecated) virtual t_update_info_state rewrite_info_multi(metadb_handle_list_cref p_list,HWND p_parent_window,bool p_show_errors) = 0; + //! Removes tags from multiple items. Use the async version in metadb_io_v2 instead if possible. + __declspec(deprecated) virtual t_update_info_state remove_info_multi(metadb_handle_list_cref p_list,HWND p_parent_window,bool p_show_errors) = 0; + + virtual void hint_multi(metadb_handle_list_cref p_list,const pfc::list_base_const_t & p_infos,const pfc::list_base_const_t & p_stats,const bit_array & p_fresh_mask) = 0; + + virtual void hint_multi_async(metadb_handle_list_cref p_list,const pfc::list_base_const_t & p_infos,const pfc::list_base_const_t & p_stats,const bit_array & p_fresh_mask) = 0; + + virtual void hint_reader(service_ptr_t p_reader,const char * p_path,abort_callback & p_abort) = 0; + + //! For internal use only. + virtual void path_to_handles_simple(const char * p_path, metadb_handle_list_ref p_out) = 0; + + //! Dispatches metadb_io_callback calls with specified items. To be used with metadb_display_field_provider when your component needs specified items refreshed. + virtual void dispatch_refresh(metadb_handle_list_cref p_list) = 0; + + void dispatch_refresh(metadb_handle_ptr const & handle) {dispatch_refresh(pfc::list_single_ref_t(handle));} + + void hint_async(metadb_handle_ptr p_item,const file_info & p_info,const t_filestats & p_stats,bool p_fresh); + + __declspec(deprecated) t_load_info_state load_info(metadb_handle_ptr p_item,t_load_info_type p_type,HWND p_parent_window,bool p_show_errors); + __declspec(deprecated) t_update_info_state update_info(metadb_handle_ptr p_item,file_info & p_info,HWND p_parent_window,bool p_show_errors); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(metadb_io); +}; + +//! Implementing this class gives you direct control over which part of file_info gets altered during a tag update uperation. To be used with metadb_io_v2::update_info_async(). +class NOVTABLE file_info_filter : public service_base { +public: + //! Alters specified file_info entry; called as a part of tag update process. Specified file_info has been read from a file, and will be written back.\n + //! WARNING: This will be typically called from another thread than main app thread (precisely, from thread created by tag updater). You should copy all relevant data to members of your file_info_filter instance in constructor and reference only member data in apply_filter() implementation. + //! @returns True when you have altered file_info and changes need to be written back to the file; false if no changes have been made. + virtual bool apply_filter(metadb_handle_ptr p_location,t_filestats p_stats,file_info & p_info) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(file_info_filter,service_base); +}; + +//! Advanced interface for passing infos read from files to metadb backend. Use metadb_io_v2::create_hint_list() to instantiate. +class NOVTABLE metadb_hint_list : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(metadb_hint_list,service_base); +public: + //! Adds a hint to the list. + //! @param p_location Location of the item the hint applies to. + //! @param p_info file_info object describing the item. + //! @param p_stats Information about the file containing item the hint applies to. + //! @param p_freshflag Set to true if the info has been directly read from the file, false if it comes from another source such as a playlist file. + virtual void add_hint(metadb_handle_ptr const & p_location,const file_info & p_info,const t_filestats & p_stats,bool p_freshflag) = 0; + //! Reads info from specified info reader instance and adds hints. May throw an exception in case info read has failed. + virtual void add_hint_reader(const char * p_path,service_ptr_t const & p_reader,abort_callback & p_abort) = 0; + //! Call this when you're done working with this metadb_hint_list instance, to apply hints and dispatch callbacks. If you don't call this, all added hints will be ignored. + virtual void on_done() = 0; +}; + +//! \since 1.0 +class NOVTABLE metadb_hint_list_v2 : public metadb_hint_list { + FB2K_MAKE_SERVICE_INTERFACE(metadb_hint_list_v2, metadb_hint_list); +public: + virtual void add_hint_browse(metadb_handle_ptr const & p_location,const file_info & p_info, t_filetimestamp browseTS) = 0; +}; + +//! \since 1.3 +class NOVTABLE metadb_hint_list_v3 : public metadb_hint_list_v2 { + FB2K_MAKE_SERVICE_INTERFACE(metadb_hint_list_v3, metadb_hint_list_v2); +public: + virtual void add_hint_v3(metadb_handle_ptr const & p_location, metadb_info_container::ptr info,bool p_freshflag) = 0; + virtual void add_hint_browse_v3(metadb_handle_ptr const & p_location,metadb_info_container::ptr info) = 0; + + virtual void add_hint_forced(metadb_handle_ptr const & p_location, const file_info & p_info,const t_filestats & p_stats,bool p_freshflag) = 0; + virtual void add_hint_forced_v3(metadb_handle_ptr const & p_location, metadb_info_container::ptr info,bool p_freshflag) = 0; + virtual void add_hint_forced_reader(const char * p_path,service_ptr_t const & p_reader,abort_callback & p_abort) = 0; +}; + + +//! New in 0.9.3. Extends metadb_io functionality with nonblocking versions of tag read/write functions, and some other utility features. +class NOVTABLE metadb_io_v2 : public metadb_io { +public: + enum { + //! By default, when some part of requested operation could not be performed for reasons other than user abort, a popup dialog with description of the problem is spawned.\n + //! Set this flag to disable error notification. + op_flag_no_errors = 1 << 0, + //! Set this flag to make the progress dialog not steal focus on creation. + op_flag_background = 1 << 1, + //! Set this flag to delay the progress dialog becoming visible, so it does not appear at all during short operations. Also implies op_flag_background effect. + op_flag_delay_ui = 1 << 2, + + //! \since 1.3 + //! Indicates that the caller is aware of the metadb partial info feature introduced at v1.3. + //! When not specified, affected info will be quietly preserved when updating tags. + op_flag_partial_info_aware = 1 << 3, + }; + + //! Preloads information from the specified tracks. + //! @param p_list List of items to process. + //! @param p_op_flags Can be null, or one or more of op_flag_* enum values combined, altering behaviors of the operation. + //! @param p_notify Called when the task is completed. Status code is one of t_load_info_state values. Can be null if caller doesn't care. + virtual void load_info_async(metadb_handle_list_cref p_list,t_load_info_type p_type,HWND p_parent_window,t_uint32 p_op_flags,completion_notify_ptr p_notify) = 0; + //! Updates tags of the specified tracks. + //! @param p_list List of items to process. + //! @param p_op_flags Can be null, or one or more of op_flag_* enum values combined, altering behaviors of the operation. + //! @param p_notify Called when the task is completed. Status code is one of t_update_info values. Can be null if caller doesn't care. + //! @param p_filter Callback handling actual file_info alterations. Typically used to replace entire meta part of file_info, or to alter something else such as ReplayGain while leaving meta intact. + virtual void update_info_async(metadb_handle_list_cref p_list,service_ptr_t p_filter,HWND p_parent_window,t_uint32 p_op_flags,completion_notify_ptr p_notify) = 0; + //! Rewrites tags of the specified tracks; similar to update_info_async() but using last known/cached file_info values rather than values passed by caller. + //! @param p_list List of items to process. + //! @param p_op_flags Can be null, or one or more of op_flag_* enum values combined, altering behaviors of the operation. + //! @param p_notify Called when the task is completed. Status code is one of t_update_info values. Can be null if caller doesn't care. + virtual void rewrite_info_async(metadb_handle_list_cref p_list,HWND p_parent_window,t_uint32 p_op_flags,completion_notify_ptr p_notify) = 0; + //! Strips all tags / metadata fields from the specified tracks. + //! @param p_list List of items to process. + //! @param p_op_flags Can be null, or one or more of op_flag_* enum values combined, altering behaviors of the operation. + //! @param p_notify Called when the task is completed. Status code is one of t_update_info values. Can be null if caller doesn't care. + virtual void remove_info_async(metadb_handle_list_cref p_list,HWND p_parent_window,t_uint32 p_op_flags,completion_notify_ptr p_notify) = 0; + + //! Creates a metadb_hint_list object. + virtual metadb_hint_list::ptr create_hint_list() = 0; + + //! Updates tags of the specified tracks. Helper; uses update_info_async internally. + //! @param p_list List of items to process. + //! @param p_op_flags Can be null, or one or more of op_flag_* enum values combined, altering behaviors of the operation. + //! @param p_notify Called when the task is completed. Status code is one of t_update_info values. Can be null if caller doesn't care. + //! @param p_new_info New infos to write to specified items. + void update_info_async_simple(metadb_handle_list_cref p_list,const pfc::list_base_const_t & p_new_info, HWND p_parent_window,t_uint32 p_op_flags,completion_notify_ptr p_notify); + + FB2K_MAKE_SERVICE_INTERFACE(metadb_io_v2,metadb_io); +}; + + +//! Dynamically-registered version of metadb_io_callback. See metadb_io_callback for documentation, register instances using metadb_io_v3::register_callback(). It's recommended that you use the metadb_io_callback_dynamic_impl_base helper class to manage registration/unregistration. +class NOVTABLE metadb_io_callback_dynamic { +public: + virtual void on_changed_sorted(metadb_handle_list_cref p_items_sorted, bool p_fromhook) = 0; +}; + +//! New (0.9.5) +class NOVTABLE metadb_io_v3 : public metadb_io_v2 { +public: + virtual void register_callback(metadb_io_callback_dynamic * p_callback) = 0; + virtual void unregister_callback(metadb_io_callback_dynamic * p_callback) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(metadb_io_v3,metadb_io_v2); +}; + +//! metadb_io_callback_dynamic implementation helper. +class metadb_io_callback_dynamic_impl_base : public metadb_io_callback_dynamic { +public: + void on_changed_sorted(metadb_handle_list_cref p_items_sorted, bool p_fromhook) {} + + metadb_io_callback_dynamic_impl_base() {static_api_ptr_t()->register_callback(this);} + ~metadb_io_callback_dynamic_impl_base() {static_api_ptr_t()->unregister_callback(this);} + + PFC_CLASS_NOT_COPYABLE_EX(metadb_io_callback_dynamic_impl_base) +}; +//! Callback service receiving notifications about metadb contents changes. +class NOVTABLE metadb_io_callback : public service_base { +public: + //! Called when metadb contents change. (Or, one of display hook component requests display update). + //! @param p_items_sorted List of items that have been updated. The list is always sorted by pointer value, to allow fast bsearch to test whether specific item has changed. + //! @param p_fromhook Set to true when actual file contents haven't changed but one of metadb_display_field_provider implementations requested an update so output of metadb_handle::format_title() etc has changed. + virtual void on_changed_sorted(metadb_handle_list_cref p_items_sorted, bool p_fromhook) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(metadb_io_callback); +}; + +//! \since 1.1 +//! Callback service receiving notifications about user-triggered tag edits. \n +//! You want to use metadb_io_callback instead most of the time, unless you specifically want to track tag edits for purposes other than updating user interface. +class NOVTABLE metadb_io_edit_callback : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(metadb_io_edit_callback) +public: + //! Called after the user has edited tags on a set of files. + typedef const pfc::list_base_const_t & t_infosref; + virtual void on_edited(metadb_handle_list_cref items, t_infosref before, t_infosref after) = 0; +}; + +//! Entrypoint service for metadb_handle related operations.\n +//! Implemented only by core, do not reimplement.\n +//! Use static_api_ptr_t template to access it, e.g. static_api_ptr_t()->handle_create(myhandle,mylocation); +class NOVTABLE metadb : public service_base +{ +protected: + //! OBSOLETE, DO NOT CALL + virtual void database_lock()=0; + //! OBSOLETE, DO NOT CALL + virtual void database_unlock()=0; +public: + + //! Returns a metadb_handle object referencing the specified location. If one doesn't exist yet a new one is created. There can be only one metadb_handle object referencing specific location. \n + //! This function should never fail unless there's something critically wrong (can't allocate memory for the new object, etc). \n + //! Speed: O(log(n)) to total number of metadb_handles present. It's recommended to pass metadb_handles around whenever possible rather than pass playable_locations then retrieve metadb_handles on demand when needed. + //! @param p_out Receives the metadb_handle pointer. + //! @param p_location Location to create a metadb_handle for. + virtual void handle_create(metadb_handle_ptr & p_out,const playable_location & p_location)=0; + + void handle_create_replace_path_canonical(metadb_handle_ptr & p_out,const metadb_handle_ptr & p_source,const char * p_new_path); + void handle_replace_path_canonical(metadb_handle_ptr & p_out,const char * p_new_path); + void handle_create_replace_path(metadb_handle_ptr & p_out,const metadb_handle_ptr & p_source,const char * p_new_path); + + //! Helper function; attempts to retrieve a handle to any known playable location to be used for e.g. titleformatting script preview.\n + //! @returns True on success; false on failure (no known playable locations). + static bool g_get_random_handle(metadb_handle_ptr & p_out); + + enum {case_sensitive = true}; + typedef pfc::comparator_strcmp path_comparator; + + inline static int path_compare_ex(const char * p1,t_size len1,const char * p2,t_size len2) {return case_sensitive ? pfc::strcmp_ex(p1,len1,p2,len2) : stricmp_utf8_ex(p1,len1,p2,len2);} + inline static int path_compare_nc(const char * p1, size_t len1, const char * p2, size_t len2) {return case_sensitive ? pfc::strcmp_nc(p1,len1,p2,len2) : stricmp_utf8_ex(p1,len1,p2,len2);} + inline static int path_compare(const char * p1,const char * p2) {return case_sensitive ? strcmp(p1,p2) : stricmp_utf8(p1,p2);} + inline static int path_compare_metadb_handle(const metadb_handle_ptr & p1,const metadb_handle_ptr & p2) {return path_compare(p1->get_path(),p2->get_path());} + + metadb_handle_ptr handle_create(playable_location const & l) {metadb_handle_ptr temp; handle_create(temp, l); return temp;} + metadb_handle_ptr handle_create(const char * path, uint32_t subsong) {return handle_create(make_playable_location(path, subsong));} + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(metadb); +}; + +class titleformat_text_out; +class titleformat_hook_function_params; + + +/*! + Implementing this service lets you provide your own title-formatting fields that are parsed globally with each call to metadb_handle::format_title methods. \n + Note that this API is meant to allow you to add your own component-specific fields - not to overlay your data over standard fields or over fields provided by other components. Any attempts to interfere with standard fields will have severe ill effects. \n + This should be implemented only where absolutely necessary, for safety and performance reasons. Any expensive operations inside the process_field() method may severely damage performance of affected title-formatting calls. \n + You must NEVER make any other foobar2000 API calls from inside process_field, other than possibly querying information from the passed metadb_handle pointer; you should read your own implementation-specific private data and return as soon as possible. You must not make any assumptions about calling context (threading etc). \n + It is guaranteed that process_field() is called only inside a metadb lock scope so you can safely call "locked" metadb_handle methods on the metadb_handle pointer you get. You must not lock metadb by yourself inside process_field() - while it is always called from inside a metadb lock scope, it may be called from another thread than the one maintaining the lock because of multi-CPU optimizations active. \n + If there are multiple metadb_display_field_provider services registered providing fields of the same name, the behavior is undefined. You must pick unique names for provided fields to ensure safe coexistence with other people's components. \n + IMPORTANT: Any components implementing metadb_display_field_provider MUST call metadb_io::dispatch_refresh() with affected metadb_handles whenever info that they present changes. Otherwise, anything rendering title-formatting strings that reference your data will not update properly, resulting in unreliable/broken output, repaint glitches, etc. \n + Do not expect a process_field() call each time somebody uses title formatting, calling code might perform its own caching of strings that you return, getting new ones only after metadb_io::dispatch_refresh() with relevant items. \n + If you can't reliably notify other components about changes of content of fields that you provide (such as when your fields provide some kind of global information and not information specific to item identified by passed metadb_handle), you should not be providing those fields in first place. You must not change returned values of your fields without dispatching appropriate notifications. \n + Use static service_factory_single_t to register your metadb_display_field_provider implementations. Do not call other people's metadb_display_field_provider services directly, they're meant to be called by backend only. \n + List of fields that you provide is expected to be fixed at run-time. The backend will enumerate your fields only once and refer to them by indexes later. \n +*/ + +class NOVTABLE metadb_display_field_provider : public service_base { +public: + //! Returns number of fields provided by this metadb_display_field_provider implementation. + virtual t_uint32 get_field_count() = 0; + //! Returns name of specified field provided by this metadb_display_field_provider implementation. Names are not case sensitive. It's strongly recommended that you keep your field names plain English / ASCII only. + virtual void get_field_name(t_uint32 index, pfc::string_base & out) = 0; + //! Evaluates the specified field. + //! @param index Index of field being processed : 0 <= index < get_field_count(). + //! @param handle Handle to item being processed. You can safely call "locked" methods on this handle to retrieve track information and such. + //! @param out Interface receiving your text output. + //! @returns Return true to indicate that the field is present so if it's enclosed in square brackets, contents of those brackets should not be skipped, false otherwise. + virtual bool process_field(t_uint32 index, metadb_handle * handle, titleformat_text_out * out) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(metadb_display_field_provider); +}; + + + + + +//! Helper implementation of file_info_filter_impl. +class file_info_filter_impl : public file_info_filter { +public: + file_info_filter_impl(const pfc::list_base_const_t & p_list,const pfc::list_base_const_t & p_new_info) { + FB2K_DYNAMIC_ASSERT(p_list.get_count() == p_new_info.get_count()); + pfc::array_t order; + order.set_size(p_list.get_count()); + order_helper::g_fill(order.get_ptr(),order.get_size()); + p_list.sort_get_permutation_t(pfc::compare_t,order.get_ptr()); + m_handles.set_count(order.get_size()); + m_infos.set_size(order.get_size()); + for(t_size n = 0; n < order.get_size(); n++) { + m_handles[n] = p_list[order[n]]; + m_infos[n] = *p_new_info[order[n]]; + } + } + + bool apply_filter(metadb_handle_ptr p_location,t_filestats p_stats,file_info & p_info) { + t_size index; + if (m_handles.bsearch_t(pfc::compare_t,p_location,index)) { + p_info = m_infos[index]; + return true; + } else { + return false; + } + } +private: + metadb_handle_list m_handles; + pfc::array_t m_infos; +}; + + +//! \since 1.1 +// typedef hasher_md5_result metadb_index_hash; +typedef t_uint64 metadb_index_hash; + + +//! \since 1.1 +class NOVTABLE metadb_index_client : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(metadb_index_client, service_base) +public: + virtual metadb_index_hash transform(const file_info & info, const playable_location & location) = 0; + + bool hashHandle(metadb_handle_ptr const & h, metadb_index_hash & out) { + metadb_info_container::ptr info; + if (!h->get_info_ref(info)) return false; + out = transform(info->info(), h->get_location()); + return true; + } + + static metadb_index_hash from_md5(hasher_md5_result const & in) {return in.xorHalve();} +}; + +//! \since 1.1 +class NOVTABLE metadb_index_manager : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(metadb_index_manager) +public: + virtual void add(metadb_index_client::ptr client, const GUID & index_id, t_filetimestamp userDataRetentionPeriod) = 0; + virtual void remove(const GUID & index_id) = 0; + virtual void set_user_data(const GUID & index_id, const metadb_index_hash & hash, const void * data, t_size dataSize) = 0; + virtual void get_user_data(const GUID & index_id, const metadb_index_hash & hash, mem_block_container & out) = 0; + + + template void get_user_data_t(const GUID & index_id, const metadb_index_hash & hash, t_array & out) { + mem_block_container_ref_impl ref(out); + get_user_data(index_id, hash, ref); + } + + t_size get_user_data_here(const GUID & index_id, const metadb_index_hash & hash, void * out, t_size outSize) { + mem_block_container_temp_impl ref(out, outSize); + get_user_data(index_id, hash, ref); + return ref.get_size(); + } + + virtual void dispatch_refresh(const GUID & index_id, const pfc::list_base_const_t & hashes) = 0; + + void dispatch_refresh(const GUID & index_id, const metadb_index_hash & hash) { + pfc::list_single_ref_t l(hash); + dispatch_refresh(index_id, l); + } + + virtual void dispatch_global_refresh() = 0; + + //! Efficiently retrieves metadb_handles of items present in the Media Library matching the specified index value. \n + //! This can be called from the app main thread only (interfaces with the library_manager API). + virtual void get_ML_handles(const GUID & index_id, const metadb_index_hash & hash, metadb_handle_list_ref out) = 0; + + //! Retrieves all known hash values for this index. + virtual void get_all_hashes(const GUID & index_id, pfc::list_base_t & out) = 0; + + //! Determines whether a no longer needed user data file for this index exists. \n + //! For use with index IDs that are not currently registered only. + virtual bool have_orphaned_data(const GUID & index_id) = 0; + + //! Deletes no longer needed index user data files. \n + //! For use with index IDs that are not currently registered only. + virtual void erase_orphaned_data(const GUID & index_id) = 0; + + //! Saves index user data file now. You normally don't need to call this; it's done automatically when saving foobar2000 configuration. \n + //! This will throw exceptions in case of a failure (out of disk space etc). + virtual void save_index_data(const GUID & index_id) = 0; +}; diff --git a/SDK/foobar2000/SDK/metadb_handle.cpp b/SDK/foobar2000/SDK/metadb_handle.cpp new file mode 100644 index 0000000..38b3c67 --- /dev/null +++ b/SDK/foobar2000/SDK/metadb_handle.cpp @@ -0,0 +1,101 @@ +#include "foobar2000.h" + + +double metadb_handle::get_length() +{ + return this->get_info_ref()->info().get_length(); +} + +t_filetimestamp metadb_handle::get_filetimestamp() +{ + return get_filestats().m_timestamp; +} + +t_filesize metadb_handle::get_filesize() +{ + return get_filestats().m_size; +} + +bool metadb_handle::format_title_legacy(titleformat_hook * p_hook,pfc::string_base & p_out,const char * p_spec,titleformat_text_filter * p_filter) +{ + service_ptr_t script; + if (static_api_ptr_t()->compile(script,p_spec)) { + return format_title(p_hook,p_out,script,p_filter); + } else { + p_out.reset(); + return false; + } +} + + + +bool metadb_handle::g_should_reload(const t_filestats & p_old_stats,const t_filestats & p_new_stats,bool p_fresh) +{ + if (p_new_stats.m_timestamp == filetimestamp_invalid) return p_fresh; + else if (p_fresh) return p_old_stats!= p_new_stats; + else return p_old_stats.m_timestamp < p_new_stats.m_timestamp; +} + +bool metadb_handle::should_reload(const t_filestats & p_new_stats, bool p_fresh) const +{ + if (!is_info_loaded_async()) return true; + else return g_should_reload(get_filestats(),p_new_stats,p_fresh); +} + + +bool metadb_handle::get_browse_info_merged(file_info & infoMerged) const { + bool rv = true; + metadb_info_container::ptr info, browse; + this->get_browse_info_ref(info, browse); + if (info.is_valid() && browse.is_valid()) { + infoMerged = info->info(); + infoMerged.merge_fallback( browse->info() ); + } else if (info.is_valid()) { + infoMerged = info->info(); + } else if (browse.is_valid()) { + infoMerged = browse->info(); + } else { + infoMerged.reset(); + rv = false; + } + return rv; +} + +namespace { + class metadb_info_container_impl : public metadb_info_container { + public: + metadb_info_container_impl() : m_stats( filestats_invalid ), m_partial() {} + file_info const & info() { + return m_info; + } + t_filestats const & stats() { + return m_stats; + } + bool isInfoPartial() { + return m_partial; + } + + file_info_impl m_info; + t_filestats m_stats; + bool m_partial; + + }; +} + +metadb_info_container::ptr metadb_handle::get_full_info_ref( abort_callback & aborter ) const { + { + metadb_info_container::ptr info; + if (this->get_info_ref( info ) ) { + if (!info->isInfoPartial()) return info; + } + } + + + input_info_reader::ptr reader; + input_entry::g_open_for_info_read( reader, NULL, this->get_path(), aborter ); + + service_ptr_t< metadb_info_container_impl > obj = new service_impl_t(); + obj->m_stats = reader->get_file_stats( aborter ); + reader->get_info( this->get_subsong_index(), obj->m_info, aborter ); + return obj; +} diff --git a/SDK/foobar2000/SDK/metadb_handle.h b/SDK/foobar2000/SDK/metadb_handle.h new file mode 100644 index 0000000..f694ab8 --- /dev/null +++ b/SDK/foobar2000/SDK/metadb_handle.h @@ -0,0 +1,249 @@ +class titleformat_hook; +class titleformat_text_filter; +class titleformat_object; + + +class metadb_info_container : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(metadb_info_container, service_base); +public: + virtual file_info const & info() = 0; + virtual t_filestats const & stats() = 0; + virtual bool isInfoPartial() = 0; +}; + +//! A metadb_handle object represents interface to reference-counted file_info cache entry for the specified location.\n +//! To obtain a metadb_handle to specific location, use metadb::handle_create(). To obtain a list of metadb_handle objects corresponding to specific path (directory, playlist, multitrack file, etc), use relevant playlist_incoming_item_filter methods (recommended), or call playlist_loader methods directly.\n +//! A metadb_handle is also the most efficient way of passing playable object locations around because it provides fast access to both location and infos, and is reference counted so duplicating it is as fast as possible.\n +//! To retrieve a path of a file from a metadb_handle, use metadb_handle::get_path() function. Note that metadb_handle is NOT just file path, some formats support multiple subsongs per physical file, which are signaled using subsong indexes. + +class NOVTABLE metadb_handle : public service_base +{ +public: + //! Retrieves location represented by this metadb_handle object. Returned reference is valid until calling context releases metadb_handle that returned it (metadb_handle_ptr is deallocated etc). + virtual const playable_location & get_location() const = 0;//never fails, returned pointer valid till the object is released + + + //! Renders information about item referenced by this metadb_handle object. + //! @param p_hook Optional callback object overriding fields and functions; set to NULL if not used. + //! @param p_out String receiving the output on success. + //! @param p_script Titleformat script to use. Use titleformat_compiler service to create one. + //! @param p_filter Optional callback object allowing input to be filtered according to context (i.e. removal of linebreak characters present in tags when rendering playlist lines). Set to NULL when not used. + //! @returns true on success, false when dummy file_info instance was used because actual info is was not (yet) known. + virtual bool format_title(titleformat_hook * p_hook,pfc::string_base & p_out,const service_ptr_t & p_script,titleformat_text_filter * p_filter) = 0; + + //! OBSOLETE, DO NOT CALL + __declspec(deprecated) virtual void metadb_lock() = 0; + //! OBSOLETE, DO NOT CALL + __declspec(deprecated) virtual void metadb_unlock() = 0; + + //! Returns last seen file stats, filestats_invalid if unknown. + virtual t_filestats get_filestats() const = 0; + + //! Queries whether cached info about item referenced by this metadb_handle object is already available. Note that this function causes the metadb to be temporarily locked; you can not use it in context that where locking is forbidden.\n + //! Note that state of cached info changes only inside main thread, so you can safely assume that it doesn't change while some block of your code inside main thread is being executed. + virtual bool is_info_loaded() const = 0; + //! Queries cached info about item referenced by this metadb_handle object. Returns true on success, false when info is not yet known. Note that this function causes the metadb to be temporarily locked; you can not use it in context that where locking is forbidden. \n + //! Note that state of cached info changes only inside main thread, so you can safely assume that it doesn't change while some block of your code inside main thread is being executed. + virtual bool get_info(file_info & p_info) const = 0; + + //! OBSOLETE, DO NOT CALL + __declspec(deprecated) virtual bool get_info_locked(const file_info * & p_info) const = 0; + + //! Queries whether cached info about item referenced by this metadb_handle object is already available.\n + //! This is intended for use in special cases when you need to immediately retrieve info sent by metadb_io hint from another thread; state of returned data can be altered by any thread, as opposed to non-async methods. + virtual bool is_info_loaded_async() const = 0; + //! Queries cached info about item referenced by this metadb_handle object. Returns true on success, false when info is not yet known. Note that this function causes the metadb to be temporarily locked; you can not use it in context that where locking is forbidden.\n + //! This is intended for use in special cases when you need to immediately retrieve info sent by metadb_io hint from another thread; state of returned data can be altered by any thread, as opposed to non-async methods. + virtual bool get_info_async(file_info & p_info) const = 0; + + //! OBSOLETE, DO NOT CALL + __declspec(deprecated) virtual bool get_info_async_locked(const file_info * & p_info) const = 0; + + //! Renders information about item referenced by this metadb_handle object, using external file_info data. + virtual void format_title_from_external_info(const file_info & p_info,titleformat_hook * p_hook,pfc::string_base & p_out,const service_ptr_t & p_script,titleformat_text_filter * p_filter) = 0; + + //! OBSOLETE, DO NOT CALL + __declspec(deprecated) virtual bool format_title_nonlocking(titleformat_hook * p_hook,pfc::string_base & p_out,const service_ptr_t & p_script,titleformat_text_filter * p_filter) = 0; + //! OBSOLETE, DO NOT CALL + __declspec(deprecated) virtual void format_title_from_external_info_nonlocking(const file_info & p_info,titleformat_hook * p_hook,pfc::string_base & p_out,const service_ptr_t & p_script,titleformat_text_filter * p_filter) = 0; + +#if FOOBAR2000_TARGET_VERSION >= 76 + //! New in 1.0 + virtual bool get_browse_info(file_info & info, t_filetimestamp & ts) const = 0; + + //! OBSOLETE, DO NOT CALL + __declspec(deprecated) virtual bool get_browse_info_locked(const file_info * & p_info, t_filetimestamp & ts) const = 0; +#endif +#if FOOBAR2000_TARGET_VERSION >= 78 + //! \since 1.3 + //! Retrieve a reference to the primary info. \n + //! You can hold the reference to the info as long as you like, call the method in any context you like with no lock semantics involved. The info held by the returned reference will remain constant even if the metadb content changes. + //! Returns true and sets outInfo to a reference to this item's primary info on success, returns false on failure (no info known at this time). + virtual bool get_info_ref(metadb_info_container::ptr & outInfo) const = 0; + + //! \since 1.3 + //! Retrieve a reference to the async info (pending info update). If async info isn't set, a reference to the primary info is returned.\n + //! You can hold the reference to the info as long as you like, call the method in any context you like with no lock semantics involved. The info held by the returned reference will remain constant even if the metadb content changes. + //! Returns true and sets outInfo to a reference to this item's async or primary info on success, returns false on failure (no info known at this time). + virtual bool get_async_info_ref(metadb_info_container::ptr & outInfo) const = 0; + + //! \since 1.3 + //! Retrieve references to the item's primary and browse infos. If no info is set, NULL pointers are returned. For most local files, browse info is not available and you get a NULL for it.\n + //! Since browse info is usually used along with the primary info (as a fallback for missing metas), you can get the two with one call for better performance. + //! You can hold the reference to the info as long as you like, call the method in any context you like with no lock semantics involved. The info held by the returned reference will remain constant even if the metadb content changes. + virtual void get_browse_info_ref(metadb_info_container::ptr & outInfo, metadb_info_container::ptr & outBrowse) const = 0; + + //! Simplified method, always returns non-null, dummy info if nothing to return + virtual metadb_info_container::ptr get_info_ref() const = 0; + //! Simplified method, always returns non-null, dummy info if nothing to return + virtual metadb_info_container::ptr get_async_info_ref() const = 0; + + //! \since 1.3 + //! Retrieve full info using available means - read actual file if not cached. \n + //! Throws exceptions on failure. + metadb_info_container::ptr get_full_info_ref( abort_callback & aborter ) const; +#endif + + //! \since 1.3 + //! Helper using get_browse_info_ref() + //! Retrieves primary info + browse info merged together. + //! Returns true on success, false if neither info is available. + //! If neither info is avaialble, output data structure is emptied. + bool get_browse_info_merged(file_info & infoMerged) const; + + + static bool g_should_reload(const t_filestats & p_old_stats,const t_filestats & p_new_stats,bool p_fresh); + bool should_reload(const t_filestats & p_new_stats,bool p_fresh) const; + + + //! Helper provided for backwards compatibility; takes formatting script as text string and calls relevant titleformat_compiler methods; returns false when the script could not be compiled.\n + //! See format_title() for descriptions of parameters.\n + //! Bottleneck warning: you should consider using precompiled titleformat script object and calling regular format_title() instead when processing large numbers of items. + bool format_title_legacy(titleformat_hook * p_hook,pfc::string_base & out,const char * p_spec,titleformat_text_filter * p_filter); + + //! Retrieves path of item described by this metadb_handle instance. Returned string is valid until calling context releases metadb_handle that returned it (metadb_handle_ptr is deallocated etc). + inline const char * get_path() const {return get_location().get_path();} + //! Retrieves subsong index of item described by this metadb_handle instance (used for multiple playable tracks within single physical file). + inline t_uint32 get_subsong_index() const {return get_location().get_subsong_index();} + + double get_length();//helper + + t_filetimestamp get_filetimestamp(); + t_filesize get_filesize(); + + FB2K_MAKE_SERVICE_INTERFACE(metadb_handle,service_base); +}; + +typedef service_ptr_t metadb_handle_ptr; + +typedef pfc::list_base_t & metadb_handle_list_ref; +typedef pfc::list_base_const_t const & metadb_handle_list_cref; + +namespace metadb_handle_list_helper { + void sort_by_format(metadb_handle_list_ref p_list,const char * spec,titleformat_hook * p_hook); + void sort_by_format_get_order(metadb_handle_list_cref p_list,t_size* order,const char * spec,titleformat_hook * p_hook); + void sort_by_format(metadb_handle_list_ref p_list,const service_ptr_t & p_script,titleformat_hook * p_hook, int direction = 1); + void sort_by_format_get_order(metadb_handle_list_cref p_list,t_size* order,const service_ptr_t & p_script,titleformat_hook * p_hook,int p_direction = 1); + + void sort_by_relative_path(metadb_handle_list_ref p_list); + void sort_by_relative_path_get_order(metadb_handle_list_cref p_list,t_size* order); + + void remove_duplicates(pfc::list_base_t & p_list); + void sort_by_pointer_remove_duplicates(pfc::list_base_t & p_list); + void sort_by_path_quick(pfc::list_base_t & p_list); + + void sort_by_pointer(pfc::list_base_t & p_list); + t_size bsearch_by_pointer(const pfc::list_base_const_t & p_list,const metadb_handle_ptr & val); + + double calc_total_duration(const pfc::list_base_const_t & p_list); + + void sort_by_path(pfc::list_base_t & p_list); + + t_filesize calc_total_size(metadb_handle_list_cref list, bool skipUnknown = false); + t_filesize calc_total_size_ex(metadb_handle_list_cref list, bool & foundUnknown); + + bool extract_single_path(metadb_handle_list_cref list, const char * &path); +}; + +template class t_alloc = pfc::alloc_fast > +class metadb_handle_list_t : public service_list_t { +private: + typedef metadb_handle_list_t t_self; + typedef list_base_const_t t_interface; +public: + inline void sort_by_format(const char * spec,titleformat_hook * p_hook) { + return metadb_handle_list_helper::sort_by_format(*this, spec, p_hook); + } + inline void sort_by_format_get_order(t_size* order,const char * spec,titleformat_hook * p_hook) const { + metadb_handle_list_helper::sort_by_format_get_order(*this, order, spec, p_hook); + } + + inline void sort_by_format(const service_ptr_t & p_script,titleformat_hook * p_hook, int direction = 1) { + metadb_handle_list_helper::sort_by_format(*this, p_script, p_hook, direction); + } + inline void sort_by_format_get_order(t_size* order,const service_ptr_t & p_script,titleformat_hook * p_hook) const { + metadb_handle_list_helper::sort_by_format_get_order(*this, order, p_script, p_hook); + } + + inline void sort_by_relative_path() { + metadb_handle_list_helper::sort_by_relative_path(*this); + } + inline void sort_by_relative_path_get_order(t_size* order) const { + metadb_handle_list_helper::sort_by_relative_path_get_order(*this,order); + } + + inline void remove_duplicates() {metadb_handle_list_helper::remove_duplicates(*this);} + inline void sort_by_pointer_remove_duplicates() {metadb_handle_list_helper::sort_by_pointer_remove_duplicates(*this);} + inline void sort_by_path_quick() {metadb_handle_list_helper::sort_by_path_quick(*this);} + + inline void sort_by_pointer() {metadb_handle_list_helper::sort_by_pointer(*this);} + inline t_size bsearch_by_pointer(const metadb_handle_ptr & val) const {return metadb_handle_list_helper::bsearch_by_pointer(*this,val);} + + inline double calc_total_duration() const {return metadb_handle_list_helper::calc_total_duration(*this);} + + inline void sort_by_path() {metadb_handle_list_helper::sort_by_path(*this);} + + const t_self & operator=(const t_self & p_source) {remove_all(); add_items(p_source);return *this;} + const t_self & operator=(const t_interface & p_source) {remove_all(); add_items(p_source);return *this;} + const t_self & operator=(t_self && p_source) {move_from(p_source); return *this; } + metadb_handle_list_t(const t_self & p_source) {add_items(p_source);} + metadb_handle_list_t(const t_interface & p_source) {add_items(p_source);} + metadb_handle_list_t() {} + + metadb_handle_list_t(t_self && p_source) {move_from(p_source);} + + t_self & operator+=(const t_interface & source) {add_items(source); return *this;} + t_self & operator+=(const metadb_handle_ptr & source) {add_item(source); return *this;} + + bool extract_single_path(const char * &path) const {return metadb_handle_list_helper::extract_single_path(*this, path);} +}; + +typedef metadb_handle_list_t<> metadb_handle_list; + +namespace metadb_handle_list_helper { + void sorted_by_pointer_extract_difference(metadb_handle_list const & p_list_1,metadb_handle_list const & p_list_2,metadb_handle_list & p_list_1_specific,metadb_handle_list & p_list_2_specific); +}; + + +inline pfc::string_base & operator<<(pfc::string_base & p_fmt,const metadb_handle_ptr & p_location) { + if (p_location.is_valid()) + return p_fmt << p_location->get_location(); + else + return p_fmt << "[invalid location]"; +} + + +class string_format_title { +public: + string_format_title(metadb_handle_ptr p_item,const char * p_script) { + p_item->format_title_legacy(NULL,m_data,p_script,NULL); + } + string_format_title(metadb_handle_ptr p_item,service_ptr_t p_script) { + p_item->format_title(NULL,m_data,p_script,NULL); + } + + const char * get_ptr() const {return m_data.get_ptr();} + operator const char * () const {return m_data.get_ptr();} +private: + pfc::string8_fastalloc m_data; +}; diff --git a/SDK/foobar2000/SDK/metadb_handle_list.cpp b/SDK/foobar2000/SDK/metadb_handle_list.cpp new file mode 100644 index 0000000..1d9164c --- /dev/null +++ b/SDK/foobar2000/SDK/metadb_handle_list.cpp @@ -0,0 +1,400 @@ +#include "foobar2000.h" +#include + +namespace { + + wchar_t * makeSortString(const char * in) { + wchar_t * out = new wchar_t[pfc::stringcvt::estimate_utf8_to_wide(in) + 1]; + out[0] = ' ';//StrCmpLogicalW bug workaround. + pfc::stringcvt::convert_utf8_to_wide_unchecked(out + 1, in); + return out; + } + + struct custom_sort_data { + wchar_t * text; + t_size index; + }; +} + +template +static int custom_sort_compare(const custom_sort_data & elem1, const custom_sort_data & elem2 ) { + int ret = direction * StrCmpLogicalW(elem1.text,elem2.text); + if (ret == 0) ret = pfc::sgn_t((t_ssize)elem1.index - (t_ssize)elem2.index); + return ret; +} + + +template +static int _cdecl _custom_sort_compare(const void * v1, const void * v2) { + return custom_sort_compare(*reinterpret_cast(v1),*reinterpret_cast(v2)); +} +void metadb_handle_list_helper::sort_by_format(metadb_handle_list_ref p_list,const char * spec,titleformat_hook * p_hook) +{ + service_ptr_t script; + if (static_api_ptr_t()->compile(script,spec)) + sort_by_format(p_list,script,p_hook); +} + +void metadb_handle_list_helper::sort_by_format_get_order(metadb_handle_list_cref p_list,t_size* order,const char * spec,titleformat_hook * p_hook) +{ + service_ptr_t script; + if (static_api_ptr_t()->compile(script,spec)) + sort_by_format_get_order(p_list,order,script,p_hook); +} + +void metadb_handle_list_helper::sort_by_format(metadb_handle_list_ref p_list,const service_ptr_t & p_script,titleformat_hook * p_hook, int direction) +{ + const t_size count = p_list.get_count(); + pfc::array_t order; order.set_size(count); + sort_by_format_get_order(p_list,order.get_ptr(),p_script,p_hook,direction); + p_list.reorder(order.get_ptr()); +} + +namespace { + + class tfhook_sort : public titleformat_hook { + public: + tfhook_sort() { + m_API->seed((unsigned)__rdtsc()); + } + bool process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag) { + return false; + } + bool process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag) { + if (stricmp_utf8_ex(p_name, p_name_length, "rand", ~0) == 0) { + t_size param_count = p_params->get_param_count(); + t_uint32 val; + if (param_count == 1) { + t_uint32 mod = (t_uint32)p_params->get_param_uint(0); + if (mod > 0) { + val = m_API->genrand(mod); + } else { + val = 0; + } + } else { + val = m_API->genrand(0xFFFFFFFF); + } + p_out->write_int(titleformat_inputtypes::unknown, val); + p_found_flag = true; + return true; + } else { + return false; + } + } + private: + static_api_ptr_t m_API; + }; + + class tfthread : public pfc::thread { + public: + tfthread(pfc::counter * walk, metadb_handle_list_cref items,custom_sort_data * out,titleformat_object::ptr script,titleformat_hook * hook) : m_walk(walk), m_items(items), m_out(out), m_script(script), m_hook(hook) {} + ~tfthread() {waitTillDone();} + + + + void threadProc() { + TRACK_CALL_TEXT("metadb_handle sort helper thread"); + + tfhook_sort myHook; + titleformat_hook_impl_splitter hookSplitter(&myHook, m_hook); + titleformat_hook * const hookPtr = m_hook ? pfc::implicit_cast(&hookSplitter) : &myHook; + + pfc::string8_fastalloc temp; temp.prealloc(512); + const t_size total = m_items.get_size(); + for(;;) { + const t_size index = (*m_walk)++; + if (index >= total) break; + m_out[index].index = index; + m_items[index]->format_title(hookPtr,temp,m_script,0); + m_out[index].text = makeSortString(temp); + } + } + private: + pfc::counter * const m_walk; + metadb_handle_list_cref m_items; + custom_sort_data * const m_out; + titleformat_object::ptr const m_script; + titleformat_hook * const m_hook; + }; +} + +void metadb_handle_list_helper::sort_by_format_get_order(metadb_handle_list_cref p_list,t_size* order,const service_ptr_t & p_script,titleformat_hook * p_hook,int p_direction) +{ +// pfc::hires_timer timer; timer.start(); + + const t_size count = p_list.get_count(); + pfc::array_t data; data.set_size(count); + + { + pfc::counter counter(0); + pfc::array_t > threads; threads.set_size(pfc::getOptimalWorkerThreadCountEx(p_list.get_count() / 128)); + PFC_ASSERT( threads.get_size() > 0 ); + for(t_size walk = 0; walk < threads.get_size(); ++walk) { + threads[walk].new_t(&counter,p_list,data.get_ptr(),p_script,p_hook); + } + for(t_size walk = 1; walk < threads.get_size(); ++walk) threads[walk]->start(); + threads[0]->threadProc(); + for(t_size walk = 1; walk < threads.get_size(); ++walk) threads[walk]->waitTillDone(); + } +// console::formatter() << "metadb_handle sort: prepared in " << pfc::format_time_ex(timer.query(),6); + + pfc::sort_t(data, p_direction > 0 ? custom_sort_compare<1> : custom_sort_compare<-1>,count); + //qsort(data.get_ptr(),count,sizeof(custom_sort_data),p_direction > 0 ? _custom_sort_compare<1> : _custom_sort_compare<-1>); + + +// console::formatter() << "metadb_handle sort: sorted in " << pfc::format_time_ex(timer.query(),6); + + for(t_size n=0;n order; order.set_size(count); + sort_by_relative_path_get_order(p_list,order.get_ptr()); + p_list.reorder(order.get_ptr()); +} + +void metadb_handle_list_helper::sort_by_relative_path_get_order(metadb_handle_list_cref p_list,t_size* order) +{ + const t_size count = p_list.get_count(); + t_size n; + pfc::array_t data; + data.set_size(count); + static_api_ptr_t api; + + pfc::string8_fastalloc temp; + temp.prealloc(512); + for(n=0;nget_relative_path(item,temp)) temp = ""; + data[n].index = n; + data[n].text = makeSortString(temp); + //data[n].subsong = item->get_subsong_index(); + } + + pfc::sort_t(data,custom_sort_compare<1>,count); + //qsort(data.get_ptr(),count,sizeof(custom_sort_data),(int (__cdecl *)(const void *elem1, const void *elem2 ))custom_sort_compare); + + for(n=0;n0) + { + bit_array_bittable mask(count); + pfc::array_t order; order.set_size(count); + order_helper::g_fill(order); + + p_list.sort_get_permutation_t(pfc::compare_t,order.get_ptr()); + + t_size n; + bool found = false; + for(n=0;n0) + { + sort_by_pointer(p_list); + bool b_found = false; + t_size n; + for(n=0;n); + p_list.sort(); +} + +t_size metadb_handle_list_helper::bsearch_by_pointer(metadb_handle_list_cref p_list,const metadb_handle_ptr & val) +{ + t_size blah; + if (p_list.bsearch_t(pfc::compare_t,val,blah)) return blah; + else return ~0; +} + + +void metadb_handle_list_helper::sorted_by_pointer_extract_difference(metadb_handle_list const & p_list_1,metadb_handle_list const & p_list_2,metadb_handle_list & p_list_1_specific,metadb_handle_list & p_list_2_specific) +{ + t_size found_1, found_2; + const t_size count_1 = p_list_1.get_count(), count_2 = p_list_2.get_count(); + t_size ptr_1, ptr_2; + + found_1 = found_2 = 0; + ptr_1 = ptr_2 = 0; + while(ptr_1 < count_1 || ptr_2 < count_2) + { + while(ptr_1 < count_1 && (ptr_2 == count_2 || p_list_1[ptr_1] < p_list_2[ptr_2])) + { + found_1++; + t_size ptr_1_new = ptr_1 + 1; + while(ptr_1_new < count_1 && p_list_1[ptr_1_new] == p_list_1[ptr_1]) ptr_1_new++; + ptr_1 = ptr_1_new; + } + while(ptr_2 < count_2 && (ptr_1 == count_1 || p_list_2[ptr_2] < p_list_1[ptr_1])) + { + found_2++; + t_size ptr_2_new = ptr_2 + 1; + while(ptr_2_new < count_2 && p_list_2[ptr_2_new] == p_list_2[ptr_2]) ptr_2_new++; + ptr_2 = ptr_2_new; + } + while(ptr_1 < count_1 && ptr_2 < count_2 && p_list_1[ptr_1] == p_list_2[ptr_2]) {ptr_1++; ptr_2++;} + } + + + + p_list_1_specific.set_count(found_1); + p_list_2_specific.set_count(found_2); + if (found_1 > 0 || found_2 > 0) + { + found_1 = found_2 = 0; + ptr_1 = ptr_2 = 0; + + while(ptr_1 < count_1 || ptr_2 < count_2) + { + while(ptr_1 < count_1 && (ptr_2 == count_2 || p_list_1[ptr_1] < p_list_2[ptr_2])) + { + p_list_1_specific[found_1++] = p_list_1[ptr_1]; + t_size ptr_1_new = ptr_1 + 1; + while(ptr_1_new < count_1 && p_list_1[ptr_1_new] == p_list_1[ptr_1]) ptr_1_new++; + ptr_1 = ptr_1_new; + } + while(ptr_2 < count_2 && (ptr_1 == count_1 || p_list_2[ptr_2] < p_list_1[ptr_1])) + { + p_list_2_specific[found_2++] = p_list_2[ptr_2]; + t_size ptr_2_new = ptr_2 + 1; + while(ptr_2_new < count_2 && p_list_2[ptr_2_new] == p_list_2[ptr_2]) ptr_2_new++; + ptr_2 = ptr_2_new; + } + while(ptr_1 < count_1 && ptr_2 < count_2 && p_list_1[ptr_1] == p_list_2[ptr_2]) {ptr_1++; ptr_2++;} + } + + } +} + +double metadb_handle_list_helper::calc_total_duration(metadb_handle_list_cref p_list) +{ + double ret = 0; + t_size n, m = p_list.get_count(); + for(n=0;nget_length(); + if (temp > 0) ret += temp; + } + return ret; +} + +void metadb_handle_list_helper::sort_by_path(metadb_handle_list_ref p_list) +{ + sort_by_format(p_list,"%path_sort%",NULL); +} + + +t_filesize metadb_handle_list_helper::calc_total_size(metadb_handle_list_cref p_list, bool skipUnknown) { + pfc::avltree_t< const char*, metadb::path_comparator > beenHere; +// metadb_handle_list list(p_list); +// list.sort_t(metadb::path_compare_metadb_handle); + + t_filesize ret = 0; + t_size n, m = p_list.get_count(); + for(n=0;nget_path(), isNew); + if (isNew) { + t_filesize t = h->get_filesize(); + if (t == filesize_invalid) { + if (!skipUnknown) return filesize_invalid; + } else { + ret += t; + } + } + } + return ret; +} + +t_filesize metadb_handle_list_helper::calc_total_size_ex(metadb_handle_list_cref p_list, bool & foundUnknown) { + foundUnknown = false; + metadb_handle_list list(p_list); + list.sort_t(metadb::path_compare_metadb_handle); + + t_filesize ret = 0; + t_size n, m = list.get_count(); + for(n=0;nget_path(),list[n]->get_path())) { + t_filesize t = list[n]->get_filesize(); + if (t == filesize_invalid) { + foundUnknown = true; + } else { + ret += t; + } + } + } + return ret; +} + +bool metadb_handle_list_helper::extract_single_path(metadb_handle_list_cref list, const char * &pathOut) { + const t_size total = list.get_count(); + if (total == 0) return false; + const char * path = list[0]->get_path(); + for(t_size walk = 1; walk < total; ++walk) { + if (metadb::path_compare(path, list[walk]->get_path()) != 0) return false; + } + pathOut = path; + return true; +} \ No newline at end of file diff --git a/SDK/foobar2000/SDK/modeless_dialog.h b/SDK/foobar2000/SDK/modeless_dialog.h new file mode 100644 index 0000000..009da21 --- /dev/null +++ b/SDK/foobar2000/SDK/modeless_dialog.h @@ -0,0 +1,17 @@ +//! Service for plugging your nonmodal dialog windows into main app loop to receive IsDialogMessage()-translated messages.\n +//! Note that all methods are valid from main app thread only.\n +//! Usage: static_api_ptr_t or modeless_dialog_manager::g_add / modeless_dialog_manager::g_remove. +class NOVTABLE modeless_dialog_manager : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(modeless_dialog_manager); +public: + //! Adds specified window to global list of windows to receive IsDialogMessage(). + virtual void add(HWND p_wnd) = 0; + //! Removes specified window from global list of windows to receive IsDialogMessage(). + virtual void remove(HWND p_wnd) = 0; + + //! Static helper; see add(). + static void g_add(HWND p_wnd) {static_api_ptr_t()->add(p_wnd);} + //! Static helper; see remove(). + static void g_remove(HWND p_wnd) {static_api_ptr_t()->remove(p_wnd);} + +}; diff --git a/SDK/foobar2000/SDK/ole_interaction.h b/SDK/foobar2000/SDK/ole_interaction.h new file mode 100644 index 0000000..96ce37f --- /dev/null +++ b/SDK/foobar2000/SDK/ole_interaction.h @@ -0,0 +1,149 @@ +class NOVTABLE playlist_dataobject_desc { +public: + virtual t_size get_entry_count() const = 0; + virtual void get_entry_name(t_size which, pfc::string_base & out) const = 0; + virtual void get_entry_content(t_size which, metadb_handle_list_ref out) const = 0; + + virtual void set_entry_count(t_size count) = 0; + virtual void set_entry_name(t_size which, const char * name) = 0; + virtual void set_entry_content(t_size which, metadb_handle_list_cref content) = 0; + + void copy(playlist_dataobject_desc const & source) { + const t_size count = source.get_entry_count(); set_entry_count(count); + metadb_handle_list content; pfc::string8 name; + for(t_size walk = 0; walk < count; ++walk) { + source.get_entry_name(walk,name); source.get_entry_content(walk,content); + set_entry_name(walk,name); set_entry_content(walk,content); + } + } +protected: + ~playlist_dataobject_desc() {} +private: + const playlist_dataobject_desc & operator=(const playlist_dataobject_desc &) {return *this;} +}; + +class NOVTABLE playlist_dataobject_desc_v2 : public playlist_dataobject_desc { +public: + virtual void get_side_data(t_size which, mem_block_container & out) const = 0; + virtual void set_side_data(t_size which, const void * data, t_size size) = 0; + + void copy(playlist_dataobject_desc_v2 const & source) { + const t_size count = source.get_entry_count(); set_entry_count(count); + metadb_handle_list content; pfc::string8 name; + mem_block_container_impl_t sideData; + for(t_size walk = 0; walk < count; ++walk) { + source.get_entry_name(walk,name); source.get_entry_content(walk,content); source.get_side_data(walk, sideData); + set_entry_name(walk,name); set_entry_content(walk,content); set_side_data(walk, sideData.get_ptr(), sideData.get_size()); + } + } + + void set_from_playlist_manager(bit_array const & mask) { + static_api_ptr_t api; + const t_size pltotal = api->get_playlist_count(); + const t_size total = mask.calc_count(true,0,pltotal); + set_entry_count(total); + t_size done = 0; + pfc::string8 name; metadb_handle_list content; + abort_callback_dummy abort; + for(t_size walk = 0; walk < pltotal; ++walk) if (mask[walk]) { + pfc::dynamic_assert( done < total ); + api->playlist_get_name(walk,name); api->playlist_get_all_items(walk,content); + set_entry_name(done,name); set_entry_content(done,content); + stream_writer_buffer_simple sideData; api->playlist_get_sideinfo(walk, &sideData, abort); + set_side_data(done,sideData.m_buffer.get_ptr(), sideData.m_buffer.get_size()); + ++done; + } + pfc::dynamic_assert( done == total ); + } + + const playlist_dataobject_desc_v2 & operator=(const playlist_dataobject_desc_v2& source) {copy(source); return *this;} +protected: + ~playlist_dataobject_desc_v2() {} +}; + +class playlist_dataobject_desc_impl : public playlist_dataobject_desc_v2 { +public: + playlist_dataobject_desc_impl() {} + playlist_dataobject_desc_impl(const playlist_dataobject_desc_v2 & source) {copy(source);} + + t_size get_entry_count() const {return m_entries.get_size();} + void get_entry_name(t_size which, pfc::string_base & out) const { + if (which < m_entries.get_size()) out = m_entries[which].m_name; + else throw pfc::exception_invalid_params(); + } + void get_entry_content(t_size which, metadb_handle_list_ref out) const { + if (which < m_entries.get_size()) out = m_entries[which].m_content; + else throw pfc::exception_invalid_params(); + } + void set_entry_count(t_size count) { + m_entries.set_size(count); + } + void set_entry_name(t_size which, const char * name) { + if (which < m_entries.get_size()) m_entries[which].m_name = name; + else throw pfc::exception_invalid_params(); + } + void set_entry_content(t_size which, metadb_handle_list_cref content) { + if (which < m_entries.get_size()) m_entries[which].m_content = content; + else throw pfc::exception_invalid_params(); + } + void get_side_data(t_size which, mem_block_container & out) const { + if (which < m_entries.get_size()) out.set(m_entries[which].m_sideData); + else throw pfc::exception_invalid_params(); + } + void set_side_data(t_size which, const void * data, t_size size) { + if (which < m_entries.get_size()) m_entries[which].m_sideData.set_data_fromptr(reinterpret_cast(data), size); + else throw pfc::exception_invalid_params(); + } +private: + struct entry { metadb_handle_list m_content; pfc::string8 m_name; pfc::array_t m_sideData; }; + pfc::array_t m_entries; +}; + +//! \since 0.9.5 +//! Provides various methods for interaction between foobar2000 and OLE IDataObjects, Windows Clipboard, drag&drop and such. +//! To instantiate, use static_api_ptr_t. +class NOVTABLE ole_interaction : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(ole_interaction) +public: + enum { + KClipboardFormatSimpleLocations, + KClipboardFormatFPL, + KClipboardFormatMultiFPL, + KClipboardFormatTotal + }; + //! Retrieves clipboard format ID for one of foobar2000's internal data formats. + //! @param which One of KClipboardFormat* constants. + virtual t_uint32 get_clipboard_format(t_uint32 which) = 0; + + //! Creates an IDataObject from a group of tracks. + virtual pfc::com_ptr_t create_dataobject(metadb_handle_list_cref source) = 0; + + //! Creates an IDataObject from one or more playlists, including playlist name info for re-creating those playlists later. + virtual pfc::com_ptr_t create_dataobject(const playlist_dataobject_desc & source) = 0; + + //! Attempts to parse an IDataObject as playlists. + virtual HRESULT parse_dataobject_playlists(pfc::com_ptr_t obj, playlist_dataobject_desc & out) = 0; + + //! For internal use only. Will succeed only if the metadb_handle list can be generated immediately, without performing potentially timeconsuming tasks such as parsing media files (for an example when the specified IDataObject contains data in one of our internal formats). + virtual HRESULT parse_dataobject_immediate(pfc::com_ptr_t obj, metadb_handle_list_ref out) = 0; + + //! Attempts to parse an IDataObject into a dropped_files_data object (list of metadb_handles if immediately available, list of file paths otherwise). + virtual HRESULT parse_dataobject(pfc::com_ptr_t obj, dropped_files_data & out) = 0; + + //! Checks whether the specified IDataObject appears to be parsable by our parse_dataobject methods. + virtual HRESULT check_dataobject(pfc::com_ptr_t obj, DWORD & dropEffect, bool & isNative) = 0; + + //! Checks whether the specified IDataObject appears to be parsable as playlists (parse_dataobject_playlists method). + virtual HRESULT check_dataobject_playlists(pfc::com_ptr_t obj) = 0; +}; + +//! \since 0.9.5.4 +class NOVTABLE ole_interaction_v2 : public ole_interaction { + FB2K_MAKE_SERVICE_INTERFACE(ole_interaction_v2, ole_interaction) +public: + //! Creates an IDataObject from one or more playlists, including playlist name info for re-creating those playlists later. + virtual pfc::com_ptr_t create_dataobject(const playlist_dataobject_desc_v2 & source) = 0; + + //! Attempts to parse an IDataObject as playlists. + virtual HRESULT parse_dataobject_playlists(pfc::com_ptr_t obj, playlist_dataobject_desc_v2 & out) = 0; +}; diff --git a/SDK/foobar2000/SDK/output.cpp b/SDK/foobar2000/SDK/output.cpp new file mode 100644 index 0000000..c9c650b --- /dev/null +++ b/SDK/foobar2000/SDK/output.cpp @@ -0,0 +1,119 @@ +#include "foobar2000.h" + +pfc::string8 output_entry::get_device_name( const GUID & deviceID ) { + pfc::string8 temp; + if (!get_device_name(deviceID, temp)) temp = "[unknown device]"; + return std::move(temp); +} + +namespace { + class output_device_enum_callback_getname : public output_device_enum_callback { + public: + output_device_enum_callback_getname( const GUID & wantID, pfc::string_base & strOut ) : m_wantID(wantID), m_got(), m_strOut(strOut) {} + void on_device(const GUID & p_guid,const char * p_name,unsigned p_name_length) { + if (!m_got && p_guid == m_wantID) { + m_strOut.set_string(p_name, p_name_length); + m_got = true; + } + } + bool m_got; + pfc::string_base & m_strOut; + const GUID m_wantID; + }; + +} + +bool output_entry::get_device_name( const GUID & deviceID, pfc::string_base & out ) { + output_device_enum_callback_getname cb(deviceID, out); + this->enum_devices(cb); + return cb.m_got; +} + +bool output_entry::g_find( const GUID & outputID, output_entry::ptr & outObj ) { + service_enum_t e; output_entry::ptr obj; + while(e.next(obj)) { + if (obj->get_guid() == outputID) { + outObj = obj; return true; + } + } + return false; +} + +output_entry::ptr output_entry::g_find( const GUID & outputID ) { + output_entry::ptr ret; + if (!g_find( outputID, ret ) ) throw exception_output_module_not_found(); + return ret; +} + + + + + +void output_impl::flush() { + m_incoming_ptr = 0; + m_incoming.set_size(0); + on_flush(); +} +void output_impl::flush_changing_track() { + m_incoming_ptr = 0; + m_incoming.set_size(0); + on_flush_changing_track(); +} +void output_impl::update(bool & p_ready) { + on_update(); + if (m_incoming_spec != m_active_spec && m_incoming_ptr < m_incoming.get_size()) { + if (get_latency_samples() == 0) { + open(m_incoming_spec); + m_active_spec = m_incoming_spec; + } else { + force_play(); + } + } + if (m_incoming_spec == m_active_spec && m_incoming_ptr < m_incoming.get_size()) { + t_size cw = can_write_samples() * m_incoming_spec.m_channels; + t_size delta = pfc::min_t(m_incoming.get_size() - m_incoming_ptr,cw); + if (delta > 0) { + write(audio_chunk_temp_impl(m_incoming.get_ptr()+m_incoming_ptr,delta / m_incoming_spec.m_channels,m_incoming_spec.m_sample_rate,m_incoming_spec.m_channels,m_incoming_spec.m_channel_config)); + m_incoming_ptr += delta; + } + } + p_ready = (m_incoming_ptr == m_incoming.get_size()); +} +double output_impl::get_latency() { + double ret = 0; + if (m_incoming_spec.is_valid()) { + ret += audio_math::samples_to_time( (m_incoming.get_size() - m_incoming_ptr) / m_incoming_spec.m_channels, m_incoming_spec.m_sample_rate ); + } + if (m_active_spec.is_valid()) { + ret += audio_math::samples_to_time( get_latency_samples() , m_active_spec.m_sample_rate ); + } + return ret; +} +void output_impl::process_samples(const audio_chunk & p_chunk) { + pfc::dynamic_assert(m_incoming_ptr == m_incoming.get_size()); + t_samplespec spec; + spec.fromchunk(p_chunk); + if (!spec.is_valid()) pfc::throw_exception_with_message< exception_io_data >("Invalid audio stream specifications"); + m_incoming_spec = spec; + t_size length = p_chunk.get_used_size(); + m_incoming.set_data_fromptr(p_chunk.get_data(),length); + m_incoming_ptr = 0; +} + + +// {EEEB07DE-C2C8-44c2-985C-C85856D96DA1} +const GUID output_id_null = +{ 0xeeeb07de, 0xc2c8, 0x44c2, { 0x98, 0x5c, 0xc8, 0x58, 0x56, 0xd9, 0x6d, 0xa1 } }; + +// {D41D2423-FBB0-4635-B233-7054F79814AB} +const GUID output_id_default = +{ 0xd41d2423, 0xfbb0, 0x4635, { 0xb2, 0x33, 0x70, 0x54, 0xf7, 0x98, 0x14, 0xab } }; + +outputCoreConfig_t outputCoreConfig_t::defaults() { + outputCoreConfig_t cfg = {}; + cfg.m_bitDepth = 16; + cfg.m_buffer_length = 1.0; + cfg.m_output = output_id_default; + // remaining fields nulled by {} + return cfg; +} diff --git a/SDK/foobar2000/SDK/output.h b/SDK/foobar2000/SDK/output.h new file mode 100644 index 0000000..0c67f61 --- /dev/null +++ b/SDK/foobar2000/SDK/output.h @@ -0,0 +1,289 @@ +#ifndef _FOOBAR2000_SDK_OUTPUT_H_ +#define _FOOBAR2000_SDK_OUTPUT_H_ + +PFC_DECLARE_EXCEPTION(exception_output_device_not_found, pfc::exception, "Audio device not found") +PFC_DECLARE_EXCEPTION(exception_output_module_not_found, exception_output_device_not_found, "Output module not found") + + +// ======================================================= +// IDEA BIN +// ======== +// Accurate timing info required! get_latency NOT safe to call from any thread while it should be +// There should be a legitimate way ( as in other than matching get_latency() against the amount of sent data ) to know when the output has finished prebuffering and started actual playback +// Outputs should be able to handle idling : idle(abort_callback&) => while(!update()) aborter.sleep(); or optimized for specific output +// ======================================================= + +//! Structure describing PCM audio data format, with basic helper functions. +struct t_pcmspec +{ + inline t_pcmspec() {reset();} + inline t_pcmspec(const t_pcmspec & p_source) {*this = p_source;} + unsigned m_sample_rate; + unsigned m_bits_per_sample; + unsigned m_channels,m_channel_config; + bool m_float; + + inline unsigned align() const {return (m_bits_per_sample / 8) * m_channels;} + + t_size time_to_bytes(double p_time) const {return (t_size)audio_math::time_to_samples(p_time,m_sample_rate) * (m_bits_per_sample / 8) * m_channels;} + double bytes_to_time(t_size p_bytes) const {return (double) (p_bytes / ((m_bits_per_sample / 8) * m_channels)) / (double) m_sample_rate;} + + inline bool operator==(/*const t_pcmspec & p_spec1,*/const t_pcmspec & p_spec2) const + { + return /*p_spec1.*/m_sample_rate == p_spec2.m_sample_rate + && /*p_spec1.*/m_bits_per_sample == p_spec2.m_bits_per_sample + && /*p_spec1.*/m_channels == p_spec2.m_channels + && /*p_spec1.*/m_channel_config == p_spec2.m_channel_config + && /*p_spec1.*/m_float == p_spec2.m_float; + } + + inline bool operator!=(/*const t_pcmspec & p_spec1,*/const t_pcmspec & p_spec2) const + { + return !(*this == p_spec2); + } + + inline void reset() {m_sample_rate = 0; m_bits_per_sample = 0; m_channels = 0; m_channel_config = 0; m_float = false;} + inline bool is_valid() const + { + return m_sample_rate >= 1000 && m_sample_rate <= 1000000 && + m_channels > 0 && m_channels <= 256 && m_channel_config != 0 && + (m_bits_per_sample == 8 || m_bits_per_sample == 16 || m_bits_per_sample == 24 || m_bits_per_sample == 32); + } +}; + +struct t_samplespec { + t_uint32 m_sample_rate; + t_uint32 m_channels,m_channel_config; + + t_size time_to_samples(double p_time) const {PFC_ASSERT(is_valid());return (t_size)audio_math::time_to_samples(p_time,m_sample_rate);} + double samples_to_time(t_size p_samples) const {PFC_ASSERT(is_valid()); return audio_math::samples_to_time(p_samples,m_sample_rate);} + + inline t_samplespec() {reset();} + inline t_samplespec(audio_chunk const & in) {fromchunk(in);} + + inline void reset() {m_sample_rate = 0; m_channels = 0; m_channel_config = 0;} + + inline bool operator==(const t_samplespec & p_spec2) const { + return m_sample_rate == p_spec2.m_sample_rate && m_channels == p_spec2.m_channels && m_channel_config == p_spec2.m_channel_config; + } + + inline bool operator!=(const t_samplespec & p_spec2) const { + return !(*this == p_spec2); + } + + inline bool is_valid() const { + return m_sample_rate > 0 && m_channels > 0 && audio_chunk::g_count_channels(m_channel_config) == m_channels; + } + + static t_samplespec g_fromchunk(const audio_chunk & p_chunk) { + t_samplespec temp; temp.fromchunk(p_chunk); return temp; + } + + void fromchunk(const audio_chunk & p_chunk) { + m_sample_rate = p_chunk.get_sample_rate(); + m_channels = p_chunk.get_channels(); + m_channel_config = p_chunk.get_channel_config(); + } +}; + +class NOVTABLE output_device_enum_callback +{ +public: + virtual void on_device(const GUID & p_guid,const char * p_name,unsigned p_name_length) = 0; +}; + +class NOVTABLE output : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(output,service_base); +public: + //! Retrieves amount of audio data queued for playback, in seconds. + virtual double get_latency() = 0; + //! Sends new samples to the device. Allowed to be called only when update() indicates that the device is ready. + virtual void process_samples(const audio_chunk & p_chunk) = 0; + //! Updates playback; queries whether the device is ready to receive new data. + //! @param p_ready On success, receives value indicating whether the device is ready for next process_samples() call. + virtual void update(bool & p_ready) = 0; + //! Pauses/unpauses playback. + virtual void pause(bool p_state) = 0; + //! Flushes queued audio data. Called after seeking. + virtual void flush() = 0; + //! Forces playback of queued data. Called when there's no more data to send, to prevent infinite waiting if output implementation starts actually playing after amount of data in internal buffer reaches some level. + virtual void force_play() = 0; + + //! Sets playback volume. + //! @p_val Volume level in dB. Value of 0 indicates full ("100%") volume, negative values indciate different attenuation levels. + virtual void volume_set(double p_val) = 0; + +}; + +class NOVTABLE output_v2 : public output { + FB2K_MAKE_SERVICE_INTERFACE(output_v2, output); +public: + virtual bool want_track_marks() {return false;} + virtual void on_track_mark() {} + virtual void enable_fading(bool state) {} + virtual void flush_changing_track() {flush();} +}; + +class NOVTABLE output_entry : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(output_entry); +public: + //! Instantiates output class. + virtual void instantiate(service_ptr_t & p_out,const GUID & p_device,double p_buffer_length,bool p_dither,t_uint32 p_bitdepth) = 0; + //! Enumerates devices supported by this output_entry implementation. + virtual void enum_devices(output_device_enum_callback & p_callback) = 0; + //! For internal use by backend. Each output_entry implementation must have its own guid. + virtual GUID get_guid() = 0; + //! For internal use by backend. Retrieves human-readable name of this output_entry implementation. + virtual const char * get_name() = 0; + + //! Pops up advanced settings dialog. This method is optional and not supported if get_config_flag() return value does not have flag_needs_advanced_config set. + //! @param p_parent Parent window for the dialog. + //! @param p_menupoint Point in screen coordinates - can be used to display a simple popup menu with options to be checked instead of a full dialog. + virtual void advanced_settings_popup(HWND p_parent,POINT p_menupoint) = 0; + + enum { + flag_needs_bitdepth_config = 1 << 0, + flag_needs_dither_config = 1 << 1, + flag_needs_advanced_config = 1 << 2, + flag_needs_device_list_prefixes = 1 << 3, + }; + + virtual t_uint32 get_config_flags() = 0; + + pfc::string8 get_device_name( const GUID & deviceID); + bool get_device_name( const GUID & deviceID, pfc::string_base & out ); + + static bool g_find( const GUID & outputID, output_entry::ptr & outObj ); + static output_entry::ptr g_find(const GUID & outputID ); +}; + +//! Helper; implements output_entry for specific output class implementation. output_entry methods are forwarded to static methods of your output class. Use output_factory_t instead of using this class directly. +template +class output_entry_impl_t : public E +{ +public: + void instantiate(service_ptr_t & p_out,const GUID & p_device,double p_buffer_length,bool p_dither,t_uint32 p_bitdepth) { + p_out = new service_impl_t(p_device,p_buffer_length,p_dither,p_bitdepth); + } + void enum_devices(output_device_enum_callback & p_callback) {T::g_enum_devices(p_callback);} + GUID get_guid() {return T::g_get_guid();} + const char * get_name() {return T::g_get_name();} + void advanced_settings_popup(HWND p_parent,POINT p_menupoint) {T::g_advanced_settings_popup(p_parent,p_menupoint);} + + t_uint32 get_config_flags() { + t_uint32 flags = 0; + if (T::g_advanced_settings_query()) flags |= output_entry::flag_needs_advanced_config; + if (T::g_needs_bitdepth_config()) flags |= output_entry::flag_needs_bitdepth_config; + if (T::g_needs_dither_config()) flags |= output_entry::flag_needs_dither_config; + if (T::g_needs_device_list_prefixes()) flags |= output_entry::flag_needs_device_list_prefixes ; + return flags; + } +}; + + +//! Use this to register your output implementation. +template +class output_factory_t : public service_factory_single_t > {}; + +class output_impl : public output_v2 { +protected: + output_impl() : m_incoming_ptr(0) {} + virtual void on_update() = 0; + //! Will never get more input than as returned by can_write_samples(). + virtual void write(const audio_chunk & p_data) = 0; + virtual t_size can_write_samples() = 0; + virtual t_size get_latency_samples() = 0; + virtual void on_flush() = 0; + virtual void on_flush_changing_track() {on_flush();} + virtual void open(t_samplespec const & p_spec) = 0; + + virtual void pause(bool p_state) = 0; + virtual void force_play() = 0; + virtual void volume_set(double p_val) = 0; +protected: + void on_need_reopen() {m_active_spec = t_samplespec();} +private: + void flush(); + void flush_changing_track(); + void update(bool & p_ready); + double get_latency(); + void process_samples(const audio_chunk & p_chunk); + + pfc::array_t m_incoming; + t_size m_incoming_ptr; + t_samplespec m_incoming_spec,m_active_spec; +}; + + +class NOVTABLE volume_callback { +public: + virtual void on_volume_scale(float v) = 0; + virtual void on_volume_arbitrary(int v) = 0; +}; + +class NOVTABLE volume_control : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(volume_control, service_base) +public: + virtual void add_callback(volume_callback * ptr) = 0; + virtual void remove_callback(volume_callback * ptr) = 0; + + enum style_t { + styleScale, + styleArbitrary + }; + + virtual style_t getStyle() = 0; + + virtual float scaleGet() = 0; + virtual void scaleSet(float v) = 0; + + virtual void arbitrarySet(int val) = 0; + virtual int arbitraryGet() = 0; + virtual int arbitraryGetMin() = 0; + virtual int arbitraryGetMax() = 0; + virtual bool arbitraryGetMute() = 0; + virtual void arbitrarySetMute(bool val) = 0; +}; + + +class NOVTABLE output_entry_v2 : public output_entry { + FB2K_MAKE_SERVICE_INTERFACE(output_entry_v2, output_entry) +public: + virtual bool get_volume_control(const GUID & id, volume_control::ptr & out) = 0; + virtual bool hasVisualisation() = 0; +}; + +#pragma pack(push, 1) +//! \since 1.3.5 +struct outputCoreConfig_t { + + static outputCoreConfig_t defaults(); + + GUID m_output; + GUID m_device; + double m_buffer_length; + uint32_t m_flags; + uint32_t m_bitDepth; + enum { flagUseDither = 1 << 0 }; +}; +#pragma pack(pop) + +//! \since 1.3.5 +//! Allows components to access foobar2000 core's output settings. +class NOVTABLE output_manager : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(output_manager); +public: + //! Instantiates an output instance with core settings. + //! @param overrideBufferLength Specify non zero to override user-configured buffer length in core settings. + //! @returns The new output instance. Throws exceptions on failure (invalid settings or other). + virtual output::ptr instantiateCoreDefault(double overrideBufferLength = 0) = 0; + virtual void getCoreConfig( void * out, size_t outSize ) = 0; + + void getCoreConfig(outputCoreConfig_t & out ) { getCoreConfig(&out, sizeof(out) ); } +}; + + +extern const GUID output_id_null; +extern const GUID output_id_default; + +#endif //_FOOBAR2000_SDK_OUTPUT_H_ diff --git a/SDK/foobar2000/SDK/packet_decoder.cpp b/SDK/foobar2000/SDK/packet_decoder.cpp new file mode 100644 index 0000000..986f7f8 --- /dev/null +++ b/SDK/foobar2000/SDK/packet_decoder.cpp @@ -0,0 +1,36 @@ +#include "foobar2000.h" + +void packet_decoder::g_open(service_ptr_t & p_out,bool p_decode,const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size,abort_callback & p_abort) +{ + service_enum_t e; + service_ptr_t ptr; + while(e.next(ptr)) { + p_abort.check(); + if (ptr->is_our_setup(p_owner,p_param1,p_param2,p_param2size)) { + ptr->open(p_out,p_decode,p_owner,p_param1,p_param2,p_param2size,p_abort); + return; + } + } + throw exception_io_data(); +} + +size_t packet_decoder::initPadding() { + size_t v = this->set_stream_property(property_bufferpadding, 0, NULL, 0); + if (v > 0) { + this->set_stream_property(property_bufferpadding, v, NULL, 0); + } + return v; +} + +void packet_decoder::setEventLogger(event_logger::ptr logger) { + this->set_stream_property(property_eventlogger, 0, logger.get_ptr(), 0); +} + +void packet_decoder::setCheckingIntegrity(bool checkingIntegrity) { + this->set_stream_property(property_checkingintegrity, checkingIntegrity ? 1 : 0, NULL, 0); +} + +void packet_decoder::setAllowDelayed( bool bAllow ) { + this->set_stream_property( property_allow_delayed_output, bAllow ? 1 : 0, NULL, 0); +} + diff --git a/SDK/foobar2000/SDK/packet_decoder.h b/SDK/foobar2000/SDK/packet_decoder.h new file mode 100644 index 0000000..38955ed --- /dev/null +++ b/SDK/foobar2000/SDK/packet_decoder.h @@ -0,0 +1,130 @@ +//! Provides interface to decode various audio data types to PCM. Use packet_decoder_factory_t template to register. + +class NOVTABLE packet_decoder : public service_base { +protected: + //! Prototype of function that must be implemented by packet_decoder implementation but is not accessible through packet_decoder interface itself. + //! Determines whether specific packet_decoder implementation supports specified decoder setup data. + static bool g_is_our_setup(const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size) {return false;} + + //! Prototype of function that must be implemented by packet_decoder implementation but is not accessible through packet_decoder interface itself. + //! Initializes packet decoder instance with specified decoder setup data. This is called only once, before any other methods. + //! @param p_decode If set to true, decode() and reset_after_seek() calls can be expected later. If set to false, those methods will not be called on this packet_decoder instance - for an example when caller is only retrieving information about the file rather than preparing to decode it. + void open(const GUID & p_owner,bool p_decode,t_size p_param1,const void * p_param2,t_size p_param2size,abort_callback & p_abort) {throw exception_io_data();} +public: + + + //! Forwards additional information about stream being decoded. \n + //! Calling: this must be called immediately after packet_decoder object is created, before any other methods are called.\n + //! Implementation: this is called after open() (which is called by implementation framework immediately after creation), and before any other methods are called. + virtual t_size set_stream_property(const GUID & p_type,t_size p_param1,const void * p_param2,t_size p_param2size) = 0; + + + //! Retrieves additional user-readable tech infos that decoder can provide. + //! @param p_info Interface receiving information about the stream being decoded. Note that it already contains partial info about the file; existing info should not be erased, decoder-provided info should be merged with it. + virtual void get_info(file_info & p_info) = 0; + + //! Returns many frames back to start decoding when seeking. + virtual unsigned get_max_frame_dependency()=0; + //! Returns much time back to start decoding when seeking (for containers where going back by specified number of frames is not trivial). + virtual double get_max_frame_dependency_time()=0; + + //! Flushes decoder after seeking. + virtual void reset_after_seek()=0; + + //! Decodes a block of audio data.\n + //! It may return empty chunk even when successful (caused by encoder+decoder delay for an example), caller must check for it and handle it appropriately. + virtual void decode(const void * p_buffer,t_size p_bytes,audio_chunk & p_chunk,abort_callback & p_abort)=0; + + //! Returns whether this packet decoder supports analyze_first_frame() function. + virtual bool analyze_first_frame_supported() = 0; + //! Optional. Some codecs need to analyze first frame of the stream to return additional info about the stream, such as encoding setup. This can be only called immediately after instantiation (and set_stream_property() if present), before any actual decoding or get_info(). Caller can determine whether this method is supported or not by calling analyze_first_frame_supported(), to avoid reading first frame when decoder won't utiilize the extra info for an example. If particular decoder can't utilize first frame info in any way (and analyze_first_frame_supported() returns false), this function should do nothing and succeed. + virtual void analyze_first_frame(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) = 0; + + //! Static helper, creates a packet_decoder instance and initializes it with specific decoder setup data. + static void g_open(service_ptr_t & p_out,bool p_decode,const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size,abort_callback & p_abort); + + static const GUID owner_MP4,owner_matroska,owner_MP3,owner_MP2,owner_MP1,owner_MP4_ALAC,owner_ADTS,owner_ADIF, owner_Ogg, owner_MP4_AMR, owner_MP4_AMR_WB, owner_MP4_AC3; + + struct matroska_setup + { + const char * codec_id; + uint32_t sample_rate,sample_rate_output; + uint32_t channels; + size_t codec_private_size; + const void * codec_private; + }; + //owner_MP4: param1 - codec ID (MP4 audio type), param2 - MP4 codec initialization data + //owner_MP3: raw MP3/MP2 file, parameters ignored + //owner_matroska: param2 = matroska_setup struct, param2size size must be equal to sizeof(matroska_setup) + + + //these are used to initialize PCM decoder + static const GUID property_samplerate,property_bitspersample,property_channels,property_byteorder,property_signed,property_channelmask, property_bufferpadding, property_eventlogger, property_checkingintegrity, property_samples_per_frame; + //property_samplerate : param1 == sample rate in hz + //property_bitspersample : param1 == bits per sample + //property_channels : param1 == channel count + //property_byteorder : if (param1) little_endian; else big_endian; + //property_signed : if (param1) signed; else unsigned; + //propery_bufferpadding : param1 == padding of each passed buffer in bytes; retval: decoder's preferred padding + //property_eventlogger : param2 = event logger ptr, NULL to disable, param2size 0 always + //property_checkingintegrity : param1 = checking integrity bool flag + //property_samples_per_frame : param1 = samples per frame + + + + //property_ogg_header : p_param1 = unused, p_param2 = ogg_packet structure, retval: 0 when more headers are wanted, 1 when done parsing headers + //property_ogg_query_sample_rate : returns sample rate, no parameters + //property_ogg_packet : p_param1 = unused, p_param2 = ogg_packet strucute + //property_ogg_qury_preskip : returns preskip samples (Opus) + static const GUID property_ogg_header, property_ogg_query_sample_rate, property_ogg_packet, property_ogg_query_preskip; + + //property_mp4_esds : p_param2 = MP4 ESDS chunk content as needed by some decoders + static const GUID property_mp4_esds; + + //property_allow_delayed_output : p_param1 = bool flag indicating whether the decoder than delay outputting audio data at will; essential for Apple AQ decoder + static const GUID property_allow_delayed_output; + + size_t initPadding(); + void setEventLogger(event_logger::ptr logger); + void setCheckingIntegrity(bool checkingIntegrity); + void setAllowDelayed( bool bAllow = true ); + + FB2K_MAKE_SERVICE_INTERFACE(packet_decoder,service_base); +}; + +class NOVTABLE packet_decoder_streamparse : public packet_decoder +{ +public: + virtual void decode_ex(const void * p_buffer,t_size p_bytes,t_size & p_bytes_processed,audio_chunk & p_chunk,abort_callback & p_abort) = 0; + virtual void analyze_first_frame_ex(const void * p_buffer,t_size p_bytes,t_size & p_bytes_processed,abort_callback & p_abort) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(packet_decoder_streamparse,packet_decoder); +}; + +class NOVTABLE packet_decoder_entry : public service_base +{ +public: + virtual bool is_our_setup(const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size) = 0; + virtual void open(service_ptr_t & p_out,bool p_decode,const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size,abort_callback & p_abort) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(packet_decoder_entry); +}; + + +template +class packet_decoder_entry_impl_t : public packet_decoder_entry +{ +public: + bool is_our_setup(const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size) { + return T::g_is_our_setup(p_owner,p_param1,p_param2,p_param2size); + } + void open(service_ptr_t & p_out,bool p_decode,const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size,abort_callback & p_abort) { + assert(is_our_setup(p_owner,p_param1,p_param2,p_param2size)); + service_ptr_t instance = new service_impl_t(); + instance->open(p_owner,p_decode,p_param1,p_param2,p_param2size,p_abort); + p_out = instance.get_ptr(); + } +}; + +template +class packet_decoder_factory_t : public service_factory_single_t > {}; diff --git a/SDK/foobar2000/SDK/play_callback.h b/SDK/foobar2000/SDK/play_callback.h new file mode 100644 index 0000000..b3b9c68 --- /dev/null +++ b/SDK/foobar2000/SDK/play_callback.h @@ -0,0 +1,156 @@ +/*! +Class receiving notifications about playback events. Note that all methods are called only from app's main thread. +Use play_callback_manager to register your dynamically created instances. Statically registered version is available too - see play_callback_static. +*/ +class NOVTABLE play_callback { +public: + //! Playback process is being initialized. on_playback_new_track() should be called soon after this when first file is successfully opened for decoding. + virtual void FB2KAPI on_playback_starting(play_control::t_track_command p_command,bool p_paused) = 0; + //! Playback advanced to new track. + virtual void FB2KAPI on_playback_new_track(metadb_handle_ptr p_track) = 0; + //! Playback stopped. + virtual void FB2KAPI on_playback_stop(play_control::t_stop_reason p_reason) = 0; + //! User has seeked to specific time. + virtual void FB2KAPI on_playback_seek(double p_time) = 0; + //! Called on pause/unpause. + virtual void FB2KAPI on_playback_pause(bool p_state) = 0; + //! Called when currently played file gets edited. + virtual void FB2KAPI on_playback_edited(metadb_handle_ptr p_track) = 0; + //! Dynamic info (VBR bitrate etc) change. + virtual void FB2KAPI on_playback_dynamic_info(const file_info & p_info) = 0; + //! Per-track dynamic info (stream track titles etc) change. Happens less often than on_playback_dynamic_info(). + virtual void FB2KAPI on_playback_dynamic_info_track(const file_info & p_info) = 0; + //! Called every second, for time display + virtual void FB2KAPI on_playback_time(double p_time) = 0; + //! User changed volume settings. Possibly called when not playing. + //! @param p_new_val new volume level in dB; 0 for full volume. + virtual void FB2KAPI on_volume_change(float p_new_val) = 0; + + enum { + flag_on_playback_starting = 1 << 0, + flag_on_playback_new_track = 1 << 1, + flag_on_playback_stop = 1 << 2, + flag_on_playback_seek = 1 << 3, + flag_on_playback_pause = 1 << 4, + flag_on_playback_edited = 1 << 5, + flag_on_playback_dynamic_info = 1 << 6, + flag_on_playback_dynamic_info_track = 1 << 7, + flag_on_playback_time = 1 << 8, + flag_on_volume_change = 1 << 9, + + flag_on_playback_all = flag_on_playback_starting | flag_on_playback_new_track | + flag_on_playback_stop | flag_on_playback_seek | + flag_on_playback_pause | flag_on_playback_edited | + flag_on_playback_dynamic_info | flag_on_playback_dynamic_info_track | flag_on_playback_time, + }; +protected: + play_callback() {} + ~play_callback() {} +}; + +//! Standard API (always present); manages registrations of dynamic play_callbacks. +//! Usage: use static_api_ptr_t. +//! Do not reimplement. +class NOVTABLE play_callback_manager : public service_base +{ +public: + //! Registers a play_callback object. + //! @param p_callback Interface to register. + //! @param p_flags Indicates which notifications are requested. + //! @param p_forward_status_on_register Set to true to have the callback immediately receive current playback status as notifications if playback is active (eg. to receive info about playback process that started before our callback was registered). + virtual void FB2KAPI register_callback(play_callback * p_callback,unsigned p_flags,bool p_forward_status_on_register) = 0; + //! Unregisters a play_callback object. + //! @p_callback Previously registered interface to unregister. + virtual void FB2KAPI unregister_callback(play_callback * p_callback) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(play_callback_manager); +}; + +//! Implementation helper. +class play_callback_impl_base : public play_callback { +public: + play_callback_impl_base(unsigned p_flags = ~0) { + static_api_ptr_t()->register_callback(this,p_flags,false); + } + ~play_callback_impl_base() { + static_api_ptr_t()->unregister_callback(this); + } + void play_callback_reregister(unsigned flags, bool refresh = false) { + static_api_ptr_t api; + api->unregister_callback(this); + api->register_callback(this,flags,refresh); + } + void on_playback_starting(play_control::t_track_command p_command,bool p_paused) {} + void on_playback_new_track(metadb_handle_ptr p_track) {} + void on_playback_stop(play_control::t_stop_reason p_reason) {} + void on_playback_seek(double p_time) {} + void on_playback_pause(bool p_state) {} + void on_playback_edited(metadb_handle_ptr p_track) {} + void on_playback_dynamic_info(const file_info & p_info) {} + void on_playback_dynamic_info_track(const file_info & p_info) {} + void on_playback_time(double p_time) {} + void on_volume_change(float p_new_val) {} + + PFC_CLASS_NOT_COPYABLE_EX(play_callback_impl_base) +}; + +//! Static (autoregistered) version of play_callback. Use play_callback_static_factory_t to register. +class play_callback_static : public service_base, public play_callback { +public: + //! Controls which methods your callback wants called; returned value should not change in run time, you should expect it to be queried only once (on startup). See play_callback::flag_* constants. + virtual unsigned get_flags() = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(play_callback_static); +}; + +template +class play_callback_static_factory_t : public service_factory_single_t {}; + + +//! Gets notified about tracks being played. Notification occurs when at least 60s of the track has been played, or the track has reached its end after at least 1/3 of it has been played through. +//! Use playback_statistics_collector_factory_t to register. +class NOVTABLE playback_statistics_collector : public service_base { +public: + virtual void on_item_played(metadb_handle_ptr p_item) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playback_statistics_collector); +}; + +template +class playback_statistics_collector_factory_t : public service_factory_single_t {}; + + + + +//! Helper providing a simplified interface for receiving playback events, in case your code does not care about the kind of playback event that has occurred; useful typically for GUI/rendering code that just refreshes some control whenever a playback state change occurs. +class playback_event_notify : private play_callback_impl_base { +public: + playback_event_notify(playback_control::t_display_level level = playback_control::display_level_all) : play_callback_impl_base(GrabCBFlags(level)) {} + + static t_uint32 GrabCBFlags(playback_control::t_display_level level) { + t_uint32 flags = flag_on_playback_starting | flag_on_playback_new_track | flag_on_playback_stop | flag_on_playback_pause | flag_on_playback_edited | flag_on_volume_change; + if (level >= playback_control::display_level_titles) flags |= flag_on_playback_dynamic_info_track; + if (level >= playback_control::display_level_all) flags |= flag_on_playback_seek | flag_on_playback_dynamic_info | flag_on_playback_time; + return flags; + } +protected: + virtual void on_playback_event() {} +private: + void on_playback_starting(play_control::t_track_command p_command,bool p_paused) {on_playback_event();} + void on_playback_new_track(metadb_handle_ptr p_track) {on_playback_event();} + void on_playback_stop(play_control::t_stop_reason p_reason) {on_playback_event();} + void on_playback_seek(double p_time) {on_playback_event();} + void on_playback_pause(bool p_state) {on_playback_event();} + void on_playback_edited(metadb_handle_ptr p_track) {on_playback_event();} + void on_playback_dynamic_info(const file_info & p_info) {on_playback_event();} + void on_playback_dynamic_info_track(const file_info & p_info) {on_playback_event();} + void on_playback_time(double p_time) {on_playback_event();} + void on_volume_change(float p_new_val) {on_playback_event();} +}; + +class playback_volume_notify : private play_callback_impl_base { +public: + playback_volume_notify() : play_callback_impl_base(flag_on_volume_change) {} + // override me + void on_volume_change(float p_new_val) {} +}; diff --git a/SDK/foobar2000/SDK/playable_location.cpp b/SDK/foobar2000/SDK/playable_location.cpp new file mode 100644 index 0000000..6ccc3eb --- /dev/null +++ b/SDK/foobar2000/SDK/playable_location.cpp @@ -0,0 +1,73 @@ +#include "foobar2000.h" + +int playable_location::g_compare(const playable_location & p_item1,const playable_location & p_item2) { + int ret = metadb::path_compare(p_item1.get_path(),p_item2.get_path()); + if (ret != 0) return ret; + return pfc::compare_t(p_item1.get_subsong(),p_item2.get_subsong()); +} + +bool playable_location::g_equals( const playable_location & p_item1, const playable_location & p_item2) { + return g_compare(p_item1, p_item2) == 0; +} + +pfc::string_base & operator<<(pfc::string_base & p_fmt,const playable_location & p_location) +{ + p_fmt << "\"" << file_path_display(p_location.get_path()) << "\""; + t_uint32 index = p_location.get_subsong_index(); + if (index != 0) p_fmt << " / index: " << p_location.get_subsong_index(); + return p_fmt; +} + + +bool playable_location::operator==(const playable_location & p_other) const { + return metadb::path_compare(get_path(),p_other.get_path()) == 0 && get_subsong() == p_other.get_subsong(); +} +bool playable_location::operator!=(const playable_location & p_other) const { + return !(*this == p_other); +} + +void playable_location::reset() { + set_path("");set_subsong(0); +} + +bool playable_location::is_empty() const { + return * get_path() == 0; +} + +bool playable_location::is_valid() const { + return !is_empty(); +} + +const char * playable_location_impl::get_path() const { + return m_path; +} + +void playable_location_impl::set_path(const char* p_path) { + m_path=p_path; +} + +t_uint32 playable_location_impl::get_subsong() const { + return m_subsong; +} + +void playable_location_impl::set_subsong(t_uint32 p_subsong) { + m_subsong=p_subsong; +} + +const playable_location_impl & playable_location_impl::operator=(const playable_location & src) { + copy(src);return *this; +} + +playable_location_impl::playable_location_impl() : m_subsong(0) {} +playable_location_impl::playable_location_impl(const char * p_path,t_uint32 p_subsong) : m_path(p_path), m_subsong(p_subsong) {} +playable_location_impl::playable_location_impl(const playable_location & src) {copy(src);} + + + +void make_playable_location::set_path(const char*) {throw pfc::exception_not_implemented();} +void make_playable_location::set_subsong(t_uint32) {throw pfc::exception_not_implemented();} + +const char * make_playable_location::get_path() const {return path;} +t_uint32 make_playable_location::get_subsong() const {return num;} + +make_playable_location::make_playable_location(const char * p_path,t_uint32 p_num) : path(p_path), num(p_num) {} diff --git a/SDK/foobar2000/SDK/playable_location.h b/SDK/foobar2000/SDK/playable_location.h new file mode 100644 index 0000000..6c5e02c --- /dev/null +++ b/SDK/foobar2000/SDK/playable_location.h @@ -0,0 +1,91 @@ +#ifndef _FOOBAR2000_PLAYABLE_LOCATION_H_ +#define _FOOBAR2000_PLAYABLE_LOCATION_H_ + +//playable_location stores location of a playable resource, currently implemented as file path and integer for indicating multiple playable "subsongs" per file +//also see: file_info.h +//for getting more info about resource referenced by a playable_location, see metadb.h + +//char* strings are all UTF-8 + +class NOVTABLE playable_location//interface (for passing around between DLLs) +{ +public: + virtual const char * get_path() const = 0; + virtual void set_path(const char*) = 0; + virtual t_uint32 get_subsong() const = 0; + virtual void set_subsong(t_uint32) = 0; + + void copy(const playable_location & p_other) { + set_path(p_other.get_path()); + set_subsong(p_other.get_subsong()); + } + + static int g_compare(const playable_location & p_item1,const playable_location & p_item2); + static bool g_equals( const playable_location & p_item1, const playable_location & p_item2); + + const playable_location & operator=(const playable_location & src) {copy(src);return *this;} + + bool operator==(const playable_location & p_other) const; + bool operator!=(const playable_location & p_other) const; + + void reset(); + + inline t_uint32 get_subsong_index() const {return get_subsong();} + inline void set_subsong_index(t_uint32 v) {set_subsong(v);} + + bool is_empty() const; + bool is_valid() const; + + + class comparator { + public: + static int compare(const playable_location & v1, const playable_location & v2) {return g_compare(v1,v2);} + }; + +protected: + playable_location() {} + ~playable_location() {} +}; + +typedef playable_location * pplayable_location; +typedef playable_location const * pcplayable_location; +typedef playable_location & rplayable_location; +typedef playable_location const & rcplayable_location; + +class playable_location_impl : public playable_location//implementation +{ +public: + virtual const char * get_path() const; + virtual void set_path(const char* p_path); + virtual t_uint32 get_subsong() const; + virtual void set_subsong(t_uint32 p_subsong); + + const playable_location_impl & operator=(const playable_location & src); + + playable_location_impl(); + playable_location_impl(const char * p_path,t_uint32 p_subsong); + playable_location_impl(const playable_location & src); +private: + pfc::string_simple m_path; + t_uint32 m_subsong; +}; + +// usage: somefunction( make_playable_location("file://c:\blah.ogg",0) ); +// only for use as a parameter to a function taking const playable_location & +class make_playable_location : public playable_location +{ + const char * path; + t_uint32 num; + + virtual void set_path(const char*); + virtual void set_subsong(t_uint32); +public: + virtual const char * get_path() const; + virtual t_uint32 get_subsong() const; + + make_playable_location(const char * p_path,t_uint32 p_num); +}; + +pfc::string_base & operator<<(pfc::string_base & p_fmt,const playable_location & p_location); + +#endif //_FOOBAR2000_PLAYABLE_LOCATION_H_ diff --git a/SDK/foobar2000/SDK/playback_control.cpp b/SDK/foobar2000/SDK/playback_control.cpp new file mode 100644 index 0000000..783aa53 --- /dev/null +++ b/SDK/foobar2000/SDK/playback_control.cpp @@ -0,0 +1,59 @@ +#include "foobar2000.h" + +static double parseFraction(const char * fraction) { + unsigned v = 0, d = 1; + while(pfc::char_is_numeric( *fraction) ) { + d *= 10; + v *= 10; + v += (unsigned) ( *fraction - '0' ); + ++fraction; + } + PFC_ASSERT( *fraction == 0 ); + return (double)v / (double)d; +} + +static double parse_time(const char * time) { + unsigned vTotal = 0, vCur = 0; + for(;;) { + char c = *time++; + if (c == 0) return (double) (vTotal + vCur); + else if (pfc::char_is_numeric( c ) ) { + vCur = vCur * 10 + (unsigned)(c-'0'); + } else if (c == ':') { + if (vCur >= 60) {PFC_ASSERT(!"Invalid input"); return 0; } + vTotal += vCur; vCur = 0; vTotal *= 60; + } else if (c == '.') { + return (double) (vTotal + vCur) + parseFraction(time); + } else { + PFC_ASSERT(!"Invalid input"); return 0; + } + } +} + +double playback_control::playback_get_length() +{ + double rv = 0; + metadb_handle_ptr ptr; + if (get_now_playing(ptr)) + { + rv = ptr->get_length(); + } + return rv; +} + +double playback_control::playback_get_length_ex() { + double rv = 0; + metadb_handle_ptr ptr; + if (get_now_playing(ptr)) + { + rv = ptr->get_length(); + if (rv <= 0) { + pfc::string8 temp; + titleformat_object::ptr script; + static_api_ptr_t()->compile_force(script, "[%length_ex%]"); + this->playback_format_title(NULL, temp, script, NULL, display_level_titles); + if (temp.length() > 0) rv = parse_time(temp); + } + } + return rv; +} diff --git a/SDK/foobar2000/SDK/playback_control.h b/SDK/foobar2000/SDK/playback_control.h new file mode 100644 index 0000000..bec6f92 --- /dev/null +++ b/SDK/foobar2000/SDK/playback_control.h @@ -0,0 +1,177 @@ +//! Provides control for various playback-related operations. +//! All methods provided by this interface work from main app thread only. Calling from another thread will do nothing or trigger an exception. If you need to trigger one of playback_control methods from another thread, see main_thread_callback. +//! Do not call playback_control methods from inside any kind of global callback (e.g. playlist callback), otherwise race conditions may occur. +//! Use static_api_ptr_t to instantiate. See static_api_ptr_t documentation for more info. +class NOVTABLE playback_control : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playback_control); +public: + + // Playback stop reason enum. + enum t_stop_reason { + stop_reason_user = 0, + stop_reason_eof, + stop_reason_starting_another, + stop_reason_shutting_down, + }; + + // Playback start mode enum. + enum t_track_command { + track_command_default = 0, + track_command_play, + //! Plays the next track from the current playlist according to the current playback order. + track_command_next, + //! Plays the previous track from the current playlist according to the current playback order. + track_command_prev, + //! For internal use only, do not use. + track_command_settrack, + //! Plays a random track from the current playlist. + track_command_rand, + + //! For internal use only, do not use. + track_command_resume, + }; + + //! Retrieves now playing item handle. + //! @returns true on success, false on failure (not playing). + virtual bool get_now_playing(metadb_handle_ptr & p_out) = 0; + //! Starts playback. If playback is already active, existing process is stopped first. + //! @param p_command Specifies what track to start playback from. See t_track_Command enum for more info. + //! @param p_paused Specifies whether playback should be started as paused. + virtual void start(t_track_command p_command = track_command_play,bool p_paused = false) = 0; + //! Stops playback. + virtual void stop() = 0; + //! Returns whether playback is active. + virtual bool is_playing() = 0; + //! Returns whether playback is active and in paused state. + virtual bool is_paused() = 0; + //! Toggles pause state if playback is active. + //! @param p_state set to true when pausing or to false when unpausing. + virtual void pause(bool p_state) = 0; + + //! Retrieves stop-after-current-track option state. + virtual bool get_stop_after_current() = 0; + //! Alters stop-after-current-track option state. + virtual void set_stop_after_current(bool p_state) = 0; + + //! Alters playback volume level. + //! @param p_value volume in dB; 0 for full volume. + virtual void set_volume(float p_value) = 0; + //! Retrieves playback volume level. + //! @returns current playback volume level, in dB; 0 for full volume. + virtual float get_volume() = 0; + //! Alters playback volume level one step up. + virtual void volume_up() = 0; + //! Alters playback volume level one step down. + virtual void volume_down() = 0; + //! Toggles playback mute state. + virtual void volume_mute_toggle() = 0; + //! Seeks in currenly played track to specified time. + //! @param p_time target time in seconds. + virtual void playback_seek(double p_time) = 0; + //! Seeks in currently played track by specified time forward or back. + //! @param p_delta time in seconds to seek by; can be positive to seek forward or negative to seek back. + virtual void playback_seek_delta(double p_delta) = 0; + //! Returns whether currently played track is seekable. If it's not, playback_seek/playback_seek_delta calls will be ignored. + virtual bool playback_can_seek() = 0; + //! Returns current playback position within currently played track, in seconds. + virtual double playback_get_position() = 0; + + //! Type used to indicate level of dynamic playback-related info displayed. Safe to use with <> opereators, e.g. level above N always includes information rendered by level N. + enum t_display_level { + //! No playback-related info + display_level_none, + //! Static info and is_playing/is_paused stats + display_level_basic, + //! display_level_basic + dynamic track titles on e.g. live streams + display_level_titles, + //! display_level_titles + timing + VBR bitrate display etc + display_level_all, + }; + + //! Renders information about currently playing item. + //! @param p_hook Optional callback object overriding fields and functions; set to NULL if not used. + //! @param p_out String receiving the output on success. + //! @param p_script Titleformat script to use. Use titleformat_compiler service to create one. + //! @param p_filter Optional callback object allowing input to be filtered according to context (i.e. removal of linebreak characters present in tags when rendering playlist lines). Set to NULL when not used. + //! @param p_level Indicates level of dynamic playback-related info displayed. See t_display_level enum for more details. + //! @returns true on success, false when no item is currently being played. + virtual bool playback_format_title(titleformat_hook * p_hook,pfc::string_base & p_out,const service_ptr_t & p_script,titleformat_text_filter * p_filter,t_display_level p_level) = 0; + + + + //! Helper; renders info about any item, including currently playing item info if the item is currently played. + bool playback_format_title_ex(metadb_handle_ptr p_item,titleformat_hook * p_hook,pfc::string_base & p_out,const service_ptr_t & p_script,titleformat_text_filter * p_filter,t_display_level p_level) { + if (p_item.is_empty()) return playback_format_title(p_hook,p_out,p_script,p_filter,p_level); + metadb_handle_ptr temp; + if (get_now_playing(temp)) { + if (temp == p_item) { + return playback_format_title(p_hook,p_out,p_script,p_filter,p_level); + } + } + p_item->format_title(p_hook,p_out,p_script,p_filter); + return true; + } + + //! Helper; retrieves length of currently playing item. + double playback_get_length(); + // Extended version: queries dynamic track info for the rare cases where that is different from static info. + double playback_get_length_ex(); + + //! Toggles stop-after-current state. + void toggle_stop_after_current() {set_stop_after_current(!get_stop_after_current());} + //! Toggles pause state. + void toggle_pause() {pause(!is_paused());} + + //! Starts playback if playback is inactive, otherwise toggles pause. + void play_or_pause() {if (is_playing()) toggle_pause(); else start();} + void play_or_unpause() { if (is_playing()) pause(false); else start();} + + void previous() { start(track_command_prev); } + void next() { start(track_command_next); } + + //deprecated + inline void play_start(t_track_command p_command = track_command_play,bool p_paused = false) {start(p_command,p_paused);} + //deprecated + inline void play_stop() {stop();} + + bool is_muted() {return get_volume() == volume_mute;} + + static const int volume_mute = -100; +}; + +class playback_control_v2 : public playback_control { + FB2K_MAKE_SERVICE_INTERFACE(playback_control_v2,playback_control); +public: + //! Returns user-specified the step dB value for volume decrement/increment. + virtual float get_volume_step() = 0; +}; + +//! \since 1.2 +class playback_control_v3 : public playback_control_v2 { + FB2K_MAKE_SERVICE_INTERFACE(playback_control_v3, playback_control_v2); +public: + //! Custom volume API - for use with specific output devices only. \n + //! Note that custom volume SHOULD NOT EVER be presented as a slider where the user can immediately go to the maximum value. \n + //! Custom volume mode dispatches on_volume_changed callbacks on change, though the passed value is meaningless; \n + //! the components should query the current value from playback_control_v3. \n + //! Note that custom volume mode makes set_volume() / get_volume() meaningless, \n + //! but volume_up() / volume_down() / volume_mute_toggle() still work like they should (increment/decrement by one unit). + //! @returns whether custom volume mode is active. + virtual bool custom_volume_is_active() = 0; + //! Retrieves the current volume value for the custom volume mode. \n + //! The volume units are arbitrary and specified by the device maker; see also: custom_volume_min(), custom_volume_max(). + virtual int custom_volume_get() = 0; + //! Sets the current volume value for the custom volume mode. \n + //! The volume units are arbitrary and specified by the device maker; see also: custom_volume_min(), custom_volume_max(). + //! CAUTION: you should NOT allow the user to easily go immediately to any value, it might blow their speakers out! + virtual void custom_volume_set(int val) = 0; + //! Returns the minimum custom volume value for the current output device. + virtual int custom_volume_min() = 0; + //! Returns the maximum custom volume value for the current output device. + virtual int custom_volume_max() = 0; + + virtual void restart() = 0; +}; + +//for compatibility with old code +typedef playback_control play_control; diff --git a/SDK/foobar2000/SDK/playback_stream_capture.h b/SDK/foobar2000/SDK/playback_stream_capture.h new file mode 100644 index 0000000..8da4b0a --- /dev/null +++ b/SDK/foobar2000/SDK/playback_stream_capture.h @@ -0,0 +1,23 @@ +//! \since 1.0 +class NOVTABLE playback_stream_capture_callback { +public: + //! Delivers a real-time chunk of audio data. \n + //! Audio is roughly synchronized with what can currently be heard. This API is provided for utility purposes such as streaming; if you want to implement a visualisation, use the visualisation_manager API instead. \n + //! Called only from the main thread. + virtual void on_chunk(const audio_chunk &) = 0; +protected: + playback_stream_capture_callback() {} + ~playback_stream_capture_callback() {} +}; + +//! \since 1.0 +class NOVTABLE playback_stream_capture : public service_base { +public: + //! Possible to call only from the main thread. + virtual void add_callback(playback_stream_capture_callback * ) = 0; + //! Possible to call only from the main thread. + virtual void remove_callback(playback_stream_capture_callback * ) = 0; + + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playback_stream_capture) +}; diff --git a/SDK/foobar2000/SDK/playlist.cpp b/SDK/foobar2000/SDK/playlist.cpp new file mode 100644 index 0000000..f8e4e13 --- /dev/null +++ b/SDK/foobar2000/SDK/playlist.cpp @@ -0,0 +1,869 @@ +#include "foobar2000.h" + +namespace { + class enum_items_callback_retrieve_item : public playlist_manager::enum_items_callback + { + metadb_handle_ptr m_item; + public: + enum_items_callback_retrieve_item() : m_item(0) {} + bool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected) + { + assert(m_item.is_empty()); + m_item = p_location; + return false; + } + inline const metadb_handle_ptr & get_item() {return m_item;} + }; + + class enum_items_callback_retrieve_selection : public playlist_manager::enum_items_callback + { + bool m_state; + public: + enum_items_callback_retrieve_selection() : m_state(false) {} + bool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected) + { + m_state = b_selected; + return false; + } + inline bool get_state() {return m_state;} + }; + + class enum_items_callback_retrieve_selection_mask : public playlist_manager::enum_items_callback + { + bit_array_var & m_out; + public: + enum_items_callback_retrieve_selection_mask(bit_array_var & p_out) : m_out(p_out) {} + bool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected) + { + m_out.set(p_index,b_selected); + return true; + } + }; + + class enum_items_callback_retrieve_all_items : public playlist_manager::enum_items_callback + { + pfc::list_base_t & m_out; + public: + enum_items_callback_retrieve_all_items(pfc::list_base_t & p_out) : m_out(p_out) {m_out.remove_all();} + bool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected) + { + m_out.add_item(p_location); + return true; + } + }; + + class enum_items_callback_retrieve_selected_items : public playlist_manager::enum_items_callback + { + pfc::list_base_t & m_out; + public: + enum_items_callback_retrieve_selected_items(pfc::list_base_t & p_out) : m_out(p_out) {m_out.remove_all();} + bool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected) + { + if (b_selected) m_out.add_item(p_location); + return true; + } + }; + + class enum_items_callback_count_selection : public playlist_manager::enum_items_callback + { + t_size m_counter,m_max; + public: + enum_items_callback_count_selection(t_size p_max) : m_max(p_max), m_counter(0) {} + bool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected) + { + if (b_selected) + { + if (++m_counter >= m_max) return false; + } + return true; + } + + inline t_size get_count() {return m_counter;} + }; + +} + +void playlist_manager::playlist_get_all_items(t_size p_playlist,pfc::list_base_t & out) +{ + playlist_get_items(p_playlist,out,bit_array_true()); +} + +void playlist_manager::playlist_get_selected_items(t_size p_playlist,pfc::list_base_t & out) +{ + playlist_enum_items(p_playlist,enum_items_callback_retrieve_selected_items(out),bit_array_true()); +} + +void playlist_manager::playlist_get_selection_mask(t_size p_playlist,bit_array_var & out) +{ + playlist_enum_items(p_playlist,enum_items_callback_retrieve_selection_mask(out),bit_array_true()); +} + +bool playlist_manager::playlist_is_item_selected(t_size p_playlist,t_size p_item) +{ + enum_items_callback_retrieve_selection callback; + playlist_enum_items(p_playlist,callback,bit_array_one(p_item)); + return callback.get_state(); +} + +metadb_handle_ptr playlist_manager::playlist_get_item_handle(t_size playlist, t_size item) { + metadb_handle_ptr temp; + if (!playlist_get_item_handle(temp, playlist, item)) throw pfc::exception_invalid_params(); + PFC_ASSERT( temp.is_valid() ); + return temp; + +} +bool playlist_manager::playlist_get_item_handle(metadb_handle_ptr & p_out,t_size p_playlist,t_size p_item) +{ + enum_items_callback_retrieve_item callback; + playlist_enum_items(p_playlist,callback,bit_array_one(p_item)); + p_out = callback.get_item(); + return p_out.is_valid(); +} + +void playlist_manager::g_make_selection_move_permutation(t_size * p_output,t_size p_count,const bit_array & p_selection,int p_delta) { + pfc::create_move_items_permutation(p_output,p_count,p_selection,p_delta); +} + +bool playlist_manager::playlist_move_selection(t_size p_playlist,int p_delta) { + if (p_delta==0) return true; + + t_size count = playlist_get_item_count(p_playlist); + + pfc::array_t order; order.set_size(count); + pfc::array_t selection; selection.set_size(count); + + playlist_get_selection_mask(p_playlist,bit_array_var_table(selection.get_ptr(),selection.get_size())); + g_make_selection_move_permutation(order.get_ptr(),count,bit_array_table(selection.get_ptr(),selection.get_size()),p_delta); + return playlist_reorder_items(p_playlist,order.get_ptr(),count); +} + +//retrieving status +t_size playlist_manager::activeplaylist_get_item_count() +{ + t_size playlist = get_active_playlist(); + if (playlist == pfc_infinite) return 0; + else return playlist_get_item_count(playlist); +} + +void playlist_manager::activeplaylist_enum_items(enum_items_callback & p_callback,const bit_array & p_mask) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) playlist_enum_items(playlist,p_callback,p_mask); +} + +t_size playlist_manager::activeplaylist_get_focus_item() +{ + t_size playlist = get_active_playlist(); + if (playlist == pfc_infinite) return pfc_infinite; + else return playlist_get_focus_item(playlist); +} + +bool playlist_manager::activeplaylist_get_name(pfc::string_base & p_out) +{ + t_size playlist = get_active_playlist(); + if (playlist == pfc_infinite) return false; + else return playlist_get_name(playlist,p_out); +} + +//modifying playlist +bool playlist_manager::activeplaylist_reorder_items(const t_size * order,t_size count) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_reorder_items(playlist,order,count); + else return false; +} + +void playlist_manager::activeplaylist_set_selection(const bit_array & affected,const bit_array & status) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) playlist_set_selection(playlist,affected,status); +} + +bool playlist_manager::activeplaylist_remove_items(const bit_array & mask) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_remove_items(playlist,mask); + else return false; +} + +bool playlist_manager::activeplaylist_replace_item(t_size p_item,const metadb_handle_ptr & p_new_item) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_replace_item(playlist,p_item,p_new_item); + else return false; +} + +void playlist_manager::activeplaylist_set_focus_item(t_size p_item) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) playlist_set_focus_item(playlist,p_item); +} + +t_size playlist_manager::activeplaylist_insert_items(t_size p_base,const pfc::list_base_const_t & data,const bit_array & p_selection) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_insert_items(playlist,p_base,data,p_selection); + else return pfc_infinite; +} + +void playlist_manager::activeplaylist_ensure_visible(t_size p_item) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) playlist_ensure_visible(playlist,p_item); +} + +bool playlist_manager::activeplaylist_rename(const char * p_name,t_size p_name_len) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_rename(playlist,p_name,p_name_len); + else return false; +} + +bool playlist_manager::activeplaylist_is_item_selected(t_size p_item) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_is_item_selected(playlist,p_item); + else return false; +} + +metadb_handle_ptr playlist_manager::activeplaylist_get_item_handle(t_size p_item) { + metadb_handle_ptr temp; + if (!activeplaylist_get_item_handle(temp, p_item)) throw pfc::exception_invalid_params(); + PFC_ASSERT( temp.is_valid() ); + return temp; +} +bool playlist_manager::activeplaylist_get_item_handle(metadb_handle_ptr & p_out,t_size p_item) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_get_item_handle(p_out,playlist,p_item); + else return false; +} + +void playlist_manager::activeplaylist_move_selection(int p_delta) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) playlist_move_selection(playlist,p_delta); +} + +void playlist_manager::activeplaylist_get_selection_mask(bit_array_var & out) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) playlist_get_selection_mask(playlist,out); +} + +void playlist_manager::activeplaylist_get_all_items(pfc::list_base_t & out) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) playlist_get_all_items(playlist,out); +} + +void playlist_manager::activeplaylist_get_selected_items(pfc::list_base_t & out) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) playlist_get_selected_items(playlist,out); +} + +bool playlist_manager::remove_playlist(t_size idx) +{ + return remove_playlists(bit_array_one(idx)); +} + +bool playlist_incoming_item_filter::process_location(const char * url,pfc::list_base_t & out,bool filter,const char * p_mask,const char * p_exclude,HWND p_parentwnd) +{ + return process_locations(pfc::list_single_ref_t(url),out,filter,p_mask,p_exclude,p_parentwnd); +} + +void playlist_manager::playlist_clear(t_size p_playlist) +{ + playlist_remove_items(p_playlist,bit_array_true()); +} + +void playlist_manager::activeplaylist_clear() +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) playlist_clear(playlist); +} + +bool playlist_manager::playlist_update_content(t_size playlist, metadb_handle_list_cref content, bool bUndoBackup) { + metadb_handle_list old; + playlist_get_all_items(playlist, old); + if (old.get_size() == 0) { + if (content.get_size() == 0) return false; + if (bUndoBackup) playlist_undo_backup(playlist); + playlist_add_items(playlist, content, bit_array_false()); + return true; + } + pfc::avltree_t itemsOld, itemsNew; + + for(t_size walk = 0; walk < old.get_size(); ++walk) itemsOld += old[walk]; + for(t_size walk = 0; walk < content.get_size(); ++walk) itemsNew += content[walk]; + bit_array_bittable removeMask(old.get_size()); + bit_array_bittable filterMask(content.get_size()); + bool gotNew = false, filterNew = false, gotRemove = false; + for(t_size walk = 0; walk < content.get_size(); ++walk) { + const bool state = !itemsOld.have_item(content[walk]); + if (state) gotNew = true; + else filterNew = true; + filterMask.set(walk, state); + } + for(t_size walk = 0; walk < old.get_size(); ++walk) { + const bool state = !itemsNew.have_item(old[walk]); + if (state) gotRemove = true; + removeMask.set(walk, state); + } + if (!gotNew && !gotRemove) return false; + if (bUndoBackup) playlist_undo_backup(playlist); + if (gotRemove) { + playlist_remove_items(playlist, removeMask); + } + if (gotNew) { + if (filterNew) { + metadb_handle_list temp(content); + temp.filter_mask(filterMask); + playlist_add_items(playlist, temp, bit_array_false()); + } else { + playlist_add_items(playlist, content, bit_array_false()); + } + } + + { + playlist_get_all_items(playlist, old); + pfc::array_t order; + if (pfc::guess_reorder_pattern >(order, old, content)) { + playlist_reorder_items(playlist, order.get_ptr(), order.get_size()); + } + } + return true; +} +bool playlist_manager::playlist_add_items(t_size playlist,const pfc::list_base_const_t & data,const bit_array & p_selection) +{ + return playlist_insert_items(playlist,pfc_infinite,data,p_selection) != pfc_infinite; +} + +bool playlist_manager::activeplaylist_add_items(const pfc::list_base_const_t & data,const bit_array & p_selection) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_add_items(playlist,data,p_selection); + else return false; +} + +bool playlist_manager::playlist_insert_items_filter(t_size p_playlist,t_size p_base,const pfc::list_base_const_t & p_data,bool p_select) +{ + metadb_handle_list temp; + static_api_ptr_t api; + if (!api->filter_items(p_data,temp)) + return false; + return playlist_insert_items(p_playlist,p_base,temp,bit_array_val(p_select)) != pfc_infinite; +} + +bool playlist_manager::activeplaylist_insert_items_filter(t_size p_base,const pfc::list_base_const_t & p_data,bool p_select) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_insert_items_filter(playlist,p_base,p_data,p_select); + else return false; +} + +bool playlist_manager::playlist_insert_locations(t_size p_playlist,t_size p_base,const pfc::list_base_const_t & p_urls,bool p_select,HWND p_parentwnd) +{ + metadb_handle_list temp; + static_api_ptr_t api; + if (!api->process_locations(p_urls,temp,true,0,0,p_parentwnd)) return false; + return playlist_insert_items(p_playlist,p_base,temp,bit_array_val(p_select)) != pfc_infinite; +} + +bool playlist_manager::activeplaylist_insert_locations(t_size p_base,const pfc::list_base_const_t & p_urls,bool p_select,HWND p_parentwnd) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_insert_locations(playlist,p_base,p_urls,p_select,p_parentwnd); + else return false; +} + +bool playlist_manager::playlist_add_items_filter(t_size p_playlist,const pfc::list_base_const_t & p_data,bool p_select) +{ + return playlist_insert_items_filter(p_playlist,pfc_infinite,p_data,p_select); +} + +bool playlist_manager::activeplaylist_add_items_filter(const pfc::list_base_const_t & p_data,bool p_select) +{ + return activeplaylist_insert_items_filter(pfc_infinite,p_data,p_select); +} + +bool playlist_manager::playlist_add_locations(t_size p_playlist,const pfc::list_base_const_t & p_urls,bool p_select,HWND p_parentwnd) +{ + return playlist_insert_locations(p_playlist,pfc_infinite,p_urls,p_select,p_parentwnd); +} +bool playlist_manager::activeplaylist_add_locations(const pfc::list_base_const_t & p_urls,bool p_select,HWND p_parentwnd) +{ + return activeplaylist_insert_locations(pfc_infinite,p_urls,p_select,p_parentwnd); +} + +void playlist_manager::reset_playing_playlist() +{ + set_playing_playlist(get_active_playlist()); +} + +void playlist_manager::playlist_clear_selection(t_size p_playlist) +{ + playlist_set_selection(p_playlist,bit_array_true(),bit_array_false()); +} + +void playlist_manager::activeplaylist_clear_selection() +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) playlist_clear_selection(playlist); +} + +void playlist_manager::activeplaylist_undo_backup() +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) playlist_undo_backup(playlist); +} + +bool playlist_manager::activeplaylist_undo_restore() +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_undo_restore(playlist); + else return false; +} + +bool playlist_manager::activeplaylist_redo_restore() +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_redo_restore(playlist); + else return false; +} + +void playlist_manager::playlist_remove_selection(t_size p_playlist,bool p_crop) +{ + bit_array_bittable table(playlist_get_item_count(p_playlist)); + playlist_get_selection_mask(p_playlist,table); + if (p_crop) playlist_remove_items(p_playlist,bit_array_not(table)); + else playlist_remove_items(p_playlist,table); +} + +void playlist_manager::activeplaylist_remove_selection(bool p_crop) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) playlist_remove_selection(playlist,p_crop); +} + +void playlist_manager::activeplaylist_item_format_title(t_size p_item,titleformat_hook * p_hook,pfc::string_base & out,const service_ptr_t & p_script,titleformat_text_filter * p_filter,play_control::t_display_level p_playback_info_level) +{ + t_size playlist = get_active_playlist(); + if (playlist == pfc_infinite) out = "NJET"; + else playlist_item_format_title(playlist,p_item,p_hook,out,p_script,p_filter,p_playback_info_level); +} + +void playlist_manager::playlist_set_selection_single(t_size p_playlist,t_size p_item,bool p_state) +{ + playlist_set_selection(p_playlist,bit_array_one(p_item),bit_array_val(p_state)); +} + +void playlist_manager::activeplaylist_set_selection_single(t_size p_item,bool p_state) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) playlist_set_selection_single(playlist,p_item,p_state); +} + +t_size playlist_manager::playlist_get_selection_count(t_size p_playlist,t_size p_max) +{ + enum_items_callback_count_selection callback(p_max); + playlist_enum_items(p_playlist,callback,bit_array_true()); + return callback.get_count(); +} + +t_size playlist_manager::activeplaylist_get_selection_count(t_size p_max) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_get_selection_count(playlist,p_max); + else return 0; +} + +bool playlist_manager::playlist_get_focus_item_handle(metadb_handle_ptr & p_out,t_size p_playlist) +{ + t_size index = playlist_get_focus_item(p_playlist); + if (index == pfc_infinite) return false; + return playlist_get_item_handle(p_out,p_playlist,index); +} + +bool playlist_manager::activeplaylist_get_focus_item_handle(metadb_handle_ptr & p_out) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_get_focus_item_handle(p_out,playlist); + else return false; +} + +t_size playlist_manager::find_playlist(const char * p_name,t_size p_name_length) +{ + t_size n, m = get_playlist_count(); + pfc::string_formatter temp; + for(n=0;n namebuffer; + namebuffer << new_playlist_text << " (" << walk << ")"; + if (find_playlist(namebuffer,pfc_infinite) == pfc_infinite) return create_playlist(namebuffer,pfc_infinite,p_index); + } +} + +bool playlist_manager::activeplaylist_sort_by_format(const char * spec,bool p_sel_only) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) return playlist_sort_by_format(playlist,spec,p_sel_only); + else return false; +} + +bool playlist_manager::highlight_playing_item() +{ + t_size playlist,item; + if (!get_playing_item_location(&playlist,&item)) return false; + set_active_playlist(playlist); + playlist_set_focus_item(playlist,item); + playlist_set_selection(playlist,bit_array_true(),bit_array_one(item)); + playlist_ensure_visible(playlist,item); + return true; +} + +void playlist_manager::playlist_get_items(t_size p_playlist,pfc::list_base_t & out,const bit_array & p_mask) +{ + playlist_enum_items(p_playlist,enum_items_callback_retrieve_all_items(out),p_mask); +} + +void playlist_manager::activeplaylist_get_items(pfc::list_base_t & out,const bit_array & p_mask) +{ + t_size playlist = get_active_playlist(); + if (playlist != pfc_infinite) playlist_get_items(playlist,out,p_mask); + else out.remove_all(); +} + +void playlist_manager::active_playlist_fix() +{ + t_size playlist = get_active_playlist(); + if (playlist == pfc_infinite) + { + t_size max = get_playlist_count(); + if (max == 0) + { + create_playlist_autoname(); + } + set_active_playlist(0); + } +} + +namespace { + class enum_items_callback_remove_list : public playlist_manager::enum_items_callback + { + const metadb_handle_list & m_data; + bit_array_var & m_table; + t_size m_found; + public: + enum_items_callback_remove_list(const metadb_handle_list & p_data,bit_array_var & p_table) : m_data(p_data), m_table(p_table), m_found(0) {} + bool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected) + { + bool found = m_data.bsearch_by_pointer(p_location) != pfc_infinite; + m_table.set(p_index,found); + if (found) m_found++; + return true; + } + + inline t_size get_found() const {return m_found;} + }; +} + +void playlist_manager::remove_items_from_all_playlists(const pfc::list_base_const_t & p_data) +{ + t_size playlist_num, playlist_max = get_playlist_count(); + if (playlist_max != pfc_infinite) + { + metadb_handle_list temp; + temp.add_items(p_data); + temp.sort_by_pointer(); + for(playlist_num = 0; playlist_num < playlist_max; playlist_num++ ) + { + t_size playlist_item_count = playlist_get_item_count(playlist_num); + if (playlist_item_count == pfc_infinite) break; + bit_array_bittable table(playlist_item_count); + enum_items_callback_remove_list callback(temp,table); + playlist_enum_items(playlist_num,callback,bit_array_true()); + if (callback.get_found()>0) + playlist_remove_items(playlist_num,table); + } + } +} + +bool playlist_manager::get_all_items(pfc::list_base_t & out) +{ + t_size n, m = get_playlist_count(); + if (m == pfc_infinite) return false; + enum_items_callback_retrieve_all_items callback(out); + for(n=0;n 0) + { + if (idx >= total) idx = total-1; + set_active_playlist(idx); + } + } + return true; + } + else return false; +} + + + +bool t_playback_queue_item::operator==(const t_playback_queue_item & p_item) const +{ + return m_handle == p_item.m_handle && m_playlist == p_item.m_playlist && m_item == p_item.m_item; +} + +bool t_playback_queue_item::operator!=(const t_playback_queue_item & p_item) const +{ + return m_handle != p_item.m_handle || m_playlist != p_item.m_playlist || m_item != p_item.m_item; +} + + + +bool playlist_manager::activeplaylist_execute_default_action(t_size p_item) { + t_size idx = get_active_playlist(); + if (idx == pfc_infinite) return false; + else return playlist_execute_default_action(idx,p_item); +} + +namespace { + class completion_notify_dfd : public completion_notify { + public: + completion_notify_dfd(const pfc::list_base_const_t & p_data,service_ptr_t p_notify) : m_data(p_data), m_notify(p_notify) {} + void on_completion(unsigned p_code) { + switch(p_code) { + case metadb_io::load_info_aborted: + m_notify->on_aborted(); + break; + default: + m_notify->on_completion(m_data); + break; + } + } + private: + metadb_handle_list m_data; + service_ptr_t m_notify; + }; +}; + +void dropped_files_data_impl::to_handles_async_ex(t_uint32 p_op_flags,HWND p_parentwnd,service_ptr_t p_notify) { + if (m_is_paths) { + static_api_ptr_t()->process_locations_async( + m_paths, + p_op_flags, + NULL, + NULL, + p_parentwnd, + p_notify); + } else { + t_uint32 flags = 0; + if (p_op_flags & playlist_incoming_item_filter_v2::op_flag_background) flags |= metadb_io_v2::op_flag_background; + if (p_op_flags & playlist_incoming_item_filter_v2::op_flag_delay_ui) flags |= metadb_io_v2::op_flag_delay_ui; + static_api_ptr_t()->load_info_async(m_handles,metadb_io::load_info_default,p_parentwnd,flags,new service_impl_t(m_handles,p_notify)); + } +} +void dropped_files_data_impl::to_handles_async(bool p_filter,HWND p_parentwnd,service_ptr_t p_notify) { + to_handles_async_ex(p_filter ? 0 : playlist_incoming_item_filter_v2::op_flag_no_filter,p_parentwnd,p_notify); +} + +bool dropped_files_data_impl::to_handles(pfc::list_base_t & p_out,bool p_filter,HWND p_parentwnd) { + if (m_is_paths) { + return static_api_ptr_t()->process_locations(m_paths,p_out,p_filter,NULL,NULL,p_parentwnd); + } else { + if (static_api_ptr_t()->load_info_multi(m_handles,metadb_io::load_info_default,p_parentwnd,true) == metadb_io::load_info_aborted) return false; + p_out = m_handles; + return true; + } +} + +void playlist_manager::playlist_activate_delta(int p_delta) { + const t_size total = get_playlist_count(); + if (total > 0) { + t_size active = get_active_playlist(); + + //clip p_delta to -(total-1)...(total-1) range + if (p_delta < 0) { + p_delta = - ( (-p_delta) % (t_ssize)total ); + } else { + p_delta = p_delta % total; + } + if (p_delta != 0) { + if (active == pfc_infinite) { + //special case when no playlist is active + if (p_delta > 0) { + active = (t_size)(p_delta - 1); + } else { + active = (total + p_delta);//p_delta is negative + } + } else { + active = (t_size) (active + total + p_delta) % total; + } + set_active_playlist(active % total); + } + } +} +namespace { + class enum_items_callback_get_selected_count : public playlist_manager::enum_items_callback { + public: + enum_items_callback_get_selected_count() : m_found() {} + t_size get_count() const {return m_found;} + bool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected) { + if (b_selected) m_found++; + return true; + } + private: + t_size m_found; + }; +} +t_size playlist_manager::playlist_get_selected_count(t_size p_playlist,bit_array const & p_mask) { + enum_items_callback_get_selected_count callback; + playlist_enum_items(p_playlist,callback,p_mask); + return callback.get_count(); +} + +namespace { + class enum_items_callback_find_item : public playlist_manager::enum_items_callback { + public: + enum_items_callback_find_item(metadb_handle_ptr p_lookingFor) : m_result(pfc_infinite), m_lookingFor(p_lookingFor) {} + t_size result() const {return m_result;} + bool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected) { + if (p_location == m_lookingFor) { + m_result = p_index; + return false; + } else { + return true; + } + } + private: + metadb_handle_ptr m_lookingFor; + t_size m_result; + }; + class enum_items_callback_find_item_selected : public playlist_manager::enum_items_callback { + public: + enum_items_callback_find_item_selected(metadb_handle_ptr p_lookingFor) : m_result(pfc_infinite), m_lookingFor(p_lookingFor) {} + t_size result() const {return m_result;} + bool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected) { + if (b_selected && p_location == m_lookingFor) { + m_result = p_index; + return false; + } else { + return true; + } + } + private: + metadb_handle_ptr m_lookingFor; + t_size m_result; + }; +} + +bool playlist_manager::playlist_find_item(t_size p_playlist,metadb_handle_ptr p_item,t_size & p_result) { + enum_items_callback_find_item callback(p_item); + playlist_enum_items(p_playlist,callback,bit_array_true()); + t_size result = callback.result(); + if (result == pfc_infinite) return false; + p_result = result; + return true; +} +bool playlist_manager::playlist_find_item_selected(t_size p_playlist,metadb_handle_ptr p_item,t_size & p_result) { + enum_items_callback_find_item_selected callback(p_item); + playlist_enum_items(p_playlist,callback,bit_array_true()); + t_size result = callback.result(); + if (result == pfc_infinite) return false; + p_result = result; + return true; +} +t_size playlist_manager::playlist_set_focus_by_handle(t_size p_playlist,metadb_handle_ptr p_item) { + t_size index; + if (!playlist_find_item(p_playlist,p_item,index)) index = pfc_infinite; + playlist_set_focus_item(p_playlist,index); + return index; +} +bool playlist_manager::activeplaylist_find_item(metadb_handle_ptr p_item,t_size & p_result) { + t_size playlist = get_active_playlist(); + if (playlist == pfc_infinite) return false; + return playlist_find_item(playlist,p_item,p_result); +} +t_size playlist_manager::activeplaylist_set_focus_by_handle(metadb_handle_ptr p_item) { + t_size playlist = get_active_playlist(); + if (playlist == pfc_infinite) return pfc_infinite; + return playlist_set_focus_by_handle(playlist,p_item); +} + +pfc::com_ptr_t playlist_incoming_item_filter::create_dataobject_ex(metadb_handle_list_cref data) { + pfc::com_ptr_t temp; temp.attach( create_dataobject(data) ); PFC_ASSERT( temp.is_valid() ); return temp; +} + +void playlist_manager_v3::recycler_restore_by_id(t_uint32 id) { + t_size which = recycler_find_by_id(id); + if (which != ~0) recycler_restore(which); +} + +t_size playlist_manager_v3::recycler_find_by_id(t_uint32 id) { + const t_size total = recycler_get_count(); + for(t_size walk = 0; walk < total; ++walk) { + if (id == recycler_get_id(walk)) return walk; + } + return ~0; +} diff --git a/SDK/foobar2000/SDK/playlist.h b/SDK/foobar2000/SDK/playlist.h new file mode 100644 index 0000000..59d62d1 --- /dev/null +++ b/SDK/foobar2000/SDK/playlist.h @@ -0,0 +1,873 @@ +//! This interface allows filtering of playlist modification operations.\n +//! Implemented by components "locking" playlists; use playlist_manager::playlist_lock_install() etc to takeover specific playlist with your instance of playlist_lock. +class NOVTABLE playlist_lock : public service_base { +public: + enum { + filter_add = 1 << 0, + filter_remove = 1 << 1, + filter_reorder = 1 << 2, + filter_replace = 1 << 3, + filter_rename = 1 << 4, + filter_remove_playlist = 1 << 5, + filter_default_action = 1 << 6, + }; + + //! Queries whether specified item insertiion operation is allowed in the locked playlist. + //! @param p_base Index from which the items are being inserted. + //! @param p_data Items being inserted. + //! @param p_selection Caller-requested selection state of items being inserted. + //! @returns True to allow the operation, false to block it. + virtual bool query_items_add(t_size p_base, const pfc::list_base_const_t & p_data,const bit_array & p_selection) = 0; + //! Queries whether specified item reorder operation is allowed in the locked playlist. + //! @param p_order Pointer to array containing permutation defining requested reorder operation. + //! @param p_count Number of items in array pointed to by p_order. This should always be equal to number of items on the locked playlist. + //! @returns True to allow the operation, false to block it. + virtual bool query_items_reorder(const t_size * p_order,t_size p_count) = 0; + //! Queries whether specified item removal operation is allowed in the locked playlist. + //! @param p_mask Specifies which items from locked playlist are being removed. + //! @param p_force If set to true, the call is made only for notification purpose and items are getting removed regardless (after e.g. they have been physically removed). + //! @returns True to allow the operation, false to block it. Note that return value is ignored if p_force is set to true. + virtual bool query_items_remove(const bit_array & p_mask,bool p_force) = 0; + //! Queries whether specified item replacement operation is allowed in the locked playlist. + //! @param p_index Index of the item being replaced. + //! @param p_old Old value of the item being replaced. + //! @param p_new New value of the item being replaced. + //! @returns True to allow the operation, false to block it. + virtual bool query_item_replace(t_size p_index,const metadb_handle_ptr & p_old,const metadb_handle_ptr & p_new)=0; + //! Queries whether renaming the locked playlist is allowed. + //! @param p_new_name Requested new name of the playlist; a UTF-8 encoded string. + //! @param p_new_name_len Length limit of the name string, in bytes (actual string may be shorter if null terminator is encountered before). Set this to infinite to use plain null-terminated strings. + //! @returns True to allow the operation, false to block it. + virtual bool query_playlist_rename(const char * p_new_name,t_size p_new_name_len) = 0; + //! Queries whether removal of the locked playlist is allowed. Note that the lock will be released when the playlist is removed. + //! @returns True to allow the operation, false to block it. + virtual bool query_playlist_remove() = 0; + //! Executes "default action" (doubleclick etc) for specified playlist item. When the playlist is not locked, default action starts playback of the item. + //! @returns True if custom default action was executed, false to fall-through to default one for non-locked playlists (start playback). + virtual bool execute_default_action(t_size p_item) = 0; + //! Notifies lock about changed index of the playlist, in result of user reordering playlists or removing other playlists. + virtual void on_playlist_index_change(t_size p_new_index) = 0; + //! Notifies lock about the locked playlist getting removed. + virtual void on_playlist_remove() = 0; + //! Retrieves human-readable name of playlist lock to display. + virtual void get_lock_name(pfc::string_base & p_out) = 0; + //! Requests user interface of component controlling the playlist lock to be shown. + virtual void show_ui() = 0; + //! Queries which actions the lock filters. The return value must not change while the lock is registered with playlist_manager. The return value is a combination of one or more filter_* constants. + virtual t_uint32 get_filter_mask() = 0; + + FB2K_MAKE_SERVICE_INTERFACE(playlist_lock,service_base); +}; + +struct t_playback_queue_item { + metadb_handle_ptr m_handle; + t_size m_playlist,m_item; + + bool operator==(const t_playback_queue_item & p_item) const; + bool operator!=(const t_playback_queue_item & p_item) const; +}; + + +//! This service provides methods for all sorts of playlist interaction.\n +//! All playlist_manager methods are valid only from main app thread.\n +//! Usage: static_api_ptr_t. +class NOVTABLE playlist_manager : public service_base +{ +public: + + //! Callback interface for playlist enumeration methods. + class NOVTABLE enum_items_callback { + public: + //! @returns True to continue enumeration, false to abort. + virtual bool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected) = 0;//return false to stop + }; + + //! Retrieves number of playlists. + virtual t_size get_playlist_count() = 0; + //! Retrieves index of active playlist; infinite if no playlist is active. + virtual t_size get_active_playlist() = 0; + //! Sets active playlist (infinite to set no active playlist). + virtual void set_active_playlist(t_size p_index) = 0; + //! Retrieves playlist from which items to be played are taken from. + virtual t_size get_playing_playlist() = 0; + //! Sets playlist from which items to be played are taken from. + virtual void set_playing_playlist(t_size p_index) = 0; + //! Removes playlists according to specified mask. See also: bit_array. + virtual bool remove_playlists(const bit_array & p_mask) = 0; + //! Creates a new playlist. + //! @param p_name Name of playlist to create; a UTF-8 encoded string. + //! @param p_name_length Length limit of playlist name string, in bytes (actual string may be shorter if null terminator is encountered before). Set this to infinite to use plain null-terminated strings. + //! @param p_index Index at which to insert new playlist; set to infinite to put it at the end of playlist list. + //! @returns Actual index of newly inserted playlist, infinite on failure (call from invalid context). + virtual t_size create_playlist(const char * p_name,t_size p_name_length,t_size p_index) = 0; + //! Reorders the playlist list according to specified permutation. + //! @returns True on success, false on failure (call from invalid context). + virtual bool reorder(const t_size * p_order,t_size p_count) = 0; + + + //! Retrieves number of items on specified playlist. + virtual t_size playlist_get_item_count(t_size p_playlist) = 0; + //! Enumerates contents of specified playlist. + virtual void playlist_enum_items(t_size p_playlist,enum_items_callback & p_callback,const bit_array & p_mask) = 0; + //! Retrieves index of focus item on specified playlist; returns infinite when no item has focus. + virtual t_size playlist_get_focus_item(t_size p_playlist) = 0; + //! Retrieves name of specified playlist. Should never fail unless the parameters are invalid. + virtual bool playlist_get_name(t_size p_playlist,pfc::string_base & p_out) = 0; + + //! Reorders items in specified playlist according to specified permutation. + virtual bool playlist_reorder_items(t_size p_playlist,const t_size * p_order,t_size p_count) = 0; + //! Selects/deselects items on specified playlist. + //! @param p_playlist Index of playlist to alter. + //! @param p_affected Mask of items to alter. + //! @param p_status Mask of selected/deselected state to apply to items specified by p_affected. + virtual void playlist_set_selection(t_size p_playlist,const bit_array & p_affected,const bit_array & p_status) = 0; + //! Removes specified items from specified playlist. Returns true on success or false on failure (playlist locked). + virtual bool playlist_remove_items(t_size p_playlist,const bit_array & mask)=0; + //! Replaces specified item on specified playlist. Returns true on success or false on failure (playlist locked). + virtual bool playlist_replace_item(t_size p_playlist,t_size p_item,const metadb_handle_ptr & p_new_item) = 0; + //! Sets index of focus item on specified playlist; use infinite to set no focus item. + virtual void playlist_set_focus_item(t_size p_playlist,t_size p_item) = 0; + //! Inserts new items into specified playlist, at specified position. + virtual t_size playlist_insert_items(t_size p_playlist,t_size p_base,const pfc::list_base_const_t & data,const bit_array & p_selection) = 0; + //! Tells playlist renderers to make sure that specified item is visible. + virtual void playlist_ensure_visible(t_size p_playlist,t_size p_item) = 0; + //! Renames specified playlist. + //! @param p_name New name of playlist; a UTF-8 encoded string. + //! @param p_name_length Length limit of playlist name string, in bytes (actual string may be shorter if null terminator is encountered before). Set this to infinite to use plain null-terminated strings. + //! @returns True on success, false on failure (playlist locked). + virtual bool playlist_rename(t_size p_index,const char * p_name,t_size p_name_length) = 0; + + + //! Creates an undo restore point for specified playlist. + virtual void playlist_undo_backup(t_size p_playlist) = 0; + //! Reverts specified playlist to last undo restore point and generates a redo restore point. + //! @returns True on success, false on failure (playlist locked or no restore point available). + virtual bool playlist_undo_restore(t_size p_playlist) = 0; + //! Reverts specified playlist to next redo restore point and generates an undo restore point. + //! @returns True on success, false on failure (playlist locked or no restore point available). + virtual bool playlist_redo_restore(t_size p_playlist) = 0; + //! Returns whether an undo restore point is available for specified playlist. + virtual bool playlist_is_undo_available(t_size p_playlist) = 0; + //! Returns whether a redo restore point is available for specified playlist. + virtual bool playlist_is_redo_available(t_size p_playlist) = 0; + + //! Renders information about specified playlist item, using specified titleformatting script parameters. + //! @param p_playlist Index of playlist containing item being processed. + //! @param p_item Index of item being processed in the playlist containing it. + //! @param p_hook Titleformatting script hook to use; see titleformat_hook documentation for more info. Set to NULL when hook functionality is not needed. + //! @param p_out String object receiving results. + //! @param p_script Compiled titleformatting script to use; see titleformat_object cocumentation for more info. + //! @param p_filter Text filter to use; see titleformat_text_filter documentation for more info. Set to NULL when text filter functionality is not needed. + //! @param p_playback_info_level Level of playback related information requested. See playback_control::t_display_level documentation for more info. + virtual void playlist_item_format_title(t_size p_playlist,t_size p_item,titleformat_hook * p_hook,pfc::string_base & p_out,const service_ptr_t & p_script,titleformat_text_filter * p_filter,playback_control::t_display_level p_playback_info_level)=0; + + + //! Retrieves playlist position of currently playing item. + //! @param p_playlist Receives index of playlist containing currently playing item on success. + //! @param p_index Receives index of currently playing item in the playlist that contains it on success. + //! @returns True on success, false on failure (not playing or currently played item has been removed from the playlist it was on when starting). + virtual bool get_playing_item_location(t_size * p_playlist,t_size * p_index) = 0; + + //! Sorts specified playlist - entire playlist or selection only - by specified title formatting pattern, or randomizes the order. + //! @param p_playlist Index of playlist to alter. + //! @param p_pattern Title formatting pattern to sort by (an UTF-8 encoded null-termindated string). Set to NULL to randomize the order of items. + //! @param p_sel_only Set to false to sort/randomize whole playlist, or to true to sort/randomize only selection on the playlist. + //! @returns True on success, false on failure (playlist locked etc). + virtual bool playlist_sort_by_format(t_size p_playlist,const char * p_pattern,bool p_sel_only) = 0; + + //! For internal use only; p_items must be sorted by metadb::path_compare; use file_operation_callback static methods instead of calling this directly. + virtual void on_files_deleted_sorted(const pfc::list_base_const_t & p_items) = 0; + //! For internal use only; p_from must be sorted by metadb::path_compare; use file_operation_callback static methods instead of calling this directly. + virtual void on_files_moved_sorted(const pfc::list_base_const_t & p_from,const pfc::list_base_const_t & p_to) = 0; + + virtual bool playlist_lock_install(t_size p_playlist,const service_ptr_t & p_lock) = 0;//returns false when invalid playlist or already locked + virtual bool playlist_lock_uninstall(t_size p_playlist,const service_ptr_t & p_lock) = 0; + virtual bool playlist_lock_is_present(t_size p_playlist) = 0; + virtual bool playlist_lock_query_name(t_size p_playlist,pfc::string_base & p_out) = 0; + virtual bool playlist_lock_show_ui(t_size p_playlist) = 0; + virtual t_uint32 playlist_lock_get_filter_mask(t_size p_playlist) = 0; + + + //! Retrieves number of available playback order modes. + virtual t_size playback_order_get_count() = 0; + //! Retrieves name of specified playback order move. + //! @param p_index Index of playback order mode to query, from 0 to playback_order_get_count() return value - 1. + //! @returns Null-terminated UTF-8 encoded string containing name of the playback order mode. Returned pointer points to statically allocated string and can be safely stored without having to free it later. + virtual const char * playback_order_get_name(t_size p_index) = 0; + //! Retrieves GUID of specified playback order mode. Used for managing playback modes without relying on names. + //! @param p_index Index of playback order mode to query, from 0 to playback_order_get_count() return value - 1. + virtual GUID playback_order_get_guid(t_size p_index) = 0; + //! Retrieves index of active playback order mode. + virtual t_size playback_order_get_active() = 0; + //! Sets index of active playback order mode. + virtual void playback_order_set_active(t_size p_index) = 0; + + virtual void queue_remove_mask(bit_array const & p_mask) = 0; + virtual void queue_add_item_playlist(t_size p_playlist,t_size p_item) = 0; + virtual void queue_add_item(metadb_handle_ptr p_item) = 0; + virtual t_size queue_get_count() = 0; + virtual void queue_get_contents(pfc::list_base_t & p_out) = 0; + //! Returns index (0-based) on success, infinite on failure (item not in queue). + virtual t_size queue_find_index(t_playback_queue_item const & p_item) = 0; + + //! Registers a playlist callback; registered object receives notifications about any modifications of any of loaded playlists. + //! @param p_callback Callback interface to register. + //! @param p_flags Flags indicating which callback methods are requested. See playlist_callback::flag_* constants for more info. The main purpose of flags parameter is working set optimization by not calling methods that do nothing. + virtual void register_callback(class playlist_callback * p_callback,unsigned p_flags) = 0; + //! Registers a playlist callback; registered object receives notifications about any modifications of active playlist. + //! @param p_callback Callback interface to register. + //! @param p_flags Flags indicating which callback methods are requested. See playlist_callback_single::flag_* constants for more info. The main purpose of flags parameter is working set optimization by not calling methods that do nothing. + virtual void register_callback(class playlist_callback_single * p_callback,unsigned p_flags) = 0; + //! Unregisters a playlist callback (playlist_callback version). + virtual void unregister_callback(class playlist_callback * p_callback) = 0; + //! Unregisters a playlist callback (playlist_callback_single version). + virtual void unregister_callback(class playlist_callback_single * p_callback) = 0; + //! Modifies flags indicating which calback methods are requested (playlist_callback version). + virtual void modify_callback(class playlist_callback * p_callback,unsigned p_flags) = 0; + //! Modifies flags indicating which calback methods are requested (playlist_callback_single version). + virtual void modify_callback(class playlist_callback_single * p_callback,unsigned p_flags) = 0; + + //! Executes default doubleclick/enter action for specified item on specified playlist (starts playing the item unless overridden by a lock to do something else). + virtual bool playlist_execute_default_action(t_size p_playlist,t_size p_item) = 0; + + + //! Helper; removes all items from the playback queue. + void queue_flush() {queue_remove_mask(bit_array_true());} + //! Helper; returns whether there are items in the playback queue. + bool queue_is_active() {return queue_get_count() > 0;} + + //! Helper; highlights currently playing item; returns true on success or false on failure (not playing or currently played item has been removed from playlist since playback started). + bool highlight_playing_item(); + //! Helper; removes single playlist of specified index. + bool remove_playlist(t_size p_playlist); + //! Helper; removes single playlist of specified index, and switches to another playlist when possible. + bool remove_playlist_switch(t_size p_playlist); + + //! Helper; returns whether specified item on specified playlist is selected or not. + bool playlist_is_item_selected(t_size p_playlist,t_size p_item); + //! Helper; retrieves metadb_handle of the specified playlist item. Returns true on success, false on failure (invalid parameters). + bool playlist_get_item_handle(metadb_handle_ptr & p_out,t_size p_playlist,t_size p_item); + //! Helper; retrieves metadb_handle of the specified playlist item; throws pfc::exception_invalid_params() on failure. + metadb_handle_ptr playlist_get_item_handle(t_size playlist, t_size item); + + //! Moves selected items up/down in the playlist by specified offset. + //! @param p_playlist Index of playlist to alter. + //! @param p_delta Offset to move items by. Set it to a negative valuye to move up, or to a positive value to move down. + //! @returns True on success, false on failure (e.g. playlist locked). + bool playlist_move_selection(t_size p_playlist,int p_delta); + //! Retrieves selection map of specific playlist, using bit_array_var interface. + void playlist_get_selection_mask(t_size p_playlist,bit_array_var & out); + void playlist_get_items(t_size p_playlist,pfc::list_base_t & out,const bit_array & p_mask); + void playlist_get_all_items(t_size p_playlist,pfc::list_base_t & out); + void playlist_get_selected_items(t_size p_playlist,pfc::list_base_t & out); + + //! Clears contents of specified playlist (removes all items from it). + void playlist_clear(t_size p_playlist); + bool playlist_add_items(t_size playlist,const pfc::list_base_const_t & data,const bit_array & p_selection); + void playlist_clear_selection(t_size p_playlist); + void playlist_remove_selection(t_size p_playlist,bool p_crop = false); + + + //! Changes contents of the specified playlist to the specified items, trying to reuse existing playlist content as much as possible (preserving selection/focus/etc). Order of items in playlist not guaranteed to be the same as in the specified item list. + //! @returns true if the playlist has been altered, false if there was nothing to update. + bool playlist_update_content(t_size playlist, metadb_handle_list_cref content, bool bUndoBackup); + + //retrieving status + t_size activeplaylist_get_item_count(); + void activeplaylist_enum_items(enum_items_callback & p_callback,const bit_array & p_mask); + t_size activeplaylist_get_focus_item();//focus may be infinite if no item is focused + bool activeplaylist_get_name(pfc::string_base & p_out); + + //modifying playlist + bool activeplaylist_reorder_items(const t_size * order,t_size count); + void activeplaylist_set_selection(const bit_array & affected,const bit_array & status); + bool activeplaylist_remove_items(const bit_array & mask); + bool activeplaylist_replace_item(t_size p_item,const metadb_handle_ptr & p_new_item); + void activeplaylist_set_focus_item(t_size p_item); + t_size activeplaylist_insert_items(t_size p_base,const pfc::list_base_const_t & data,const bit_array & p_selection); + void activeplaylist_ensure_visible(t_size p_item); + bool activeplaylist_rename(const char * p_name,t_size p_name_len); + + void activeplaylist_undo_backup(); + bool activeplaylist_undo_restore(); + bool activeplaylist_redo_restore(); + + bool activeplaylist_is_item_selected(t_size p_item); + bool activeplaylist_get_item_handle(metadb_handle_ptr & item,t_size p_item); + metadb_handle_ptr activeplaylist_get_item_handle(t_size p_item); + void activeplaylist_move_selection(int p_delta); + void activeplaylist_get_selection_mask(bit_array_var & out); + void activeplaylist_get_items(pfc::list_base_t & out,const bit_array & p_mask); + void activeplaylist_get_all_items(pfc::list_base_t & out); + void activeplaylist_get_selected_items(pfc::list_base_t & out); + void activeplaylist_clear(); + + bool activeplaylist_add_items(const pfc::list_base_const_t & data,const bit_array & p_selection); + + bool playlist_insert_items_filter(t_size p_playlist,t_size p_base,const pfc::list_base_const_t & p_data,bool p_select); + bool activeplaylist_insert_items_filter(t_size p_base,const pfc::list_base_const_t & p_data,bool p_select); + + //! \deprecated (since 0.9.3) Use playlist_incoming_item_filter_v2::process_locations_async whenever possible + bool playlist_insert_locations(t_size p_playlist,t_size p_base,const pfc::list_base_const_t & p_urls,bool p_select,HWND p_parentwnd); + //! \deprecated (since 0.9.3) Use playlist_incoming_item_filter_v2::process_locations_async whenever possible + bool activeplaylist_insert_locations(t_size p_base,const pfc::list_base_const_t & p_urls,bool p_select,HWND p_parentwnd); + + bool playlist_add_items_filter(t_size p_playlist,const pfc::list_base_const_t & p_data,bool p_select); + bool activeplaylist_add_items_filter(const pfc::list_base_const_t & p_data,bool p_select); + + bool playlist_add_locations(t_size p_playlist,const pfc::list_base_const_t & p_urls,bool p_select,HWND p_parentwnd); + bool activeplaylist_add_locations(const pfc::list_base_const_t & p_urls,bool p_select,HWND p_parentwnd); + + void reset_playing_playlist(); + + void activeplaylist_clear_selection(); + void activeplaylist_remove_selection(bool p_crop = false); + + void activeplaylist_item_format_title(t_size p_item,titleformat_hook * p_hook,pfc::string_base & out,const service_ptr_t & p_script,titleformat_text_filter * p_filter,play_control::t_display_level p_playback_info_level); + + void playlist_set_selection_single(t_size p_playlist,t_size p_item,bool p_state); + void activeplaylist_set_selection_single(t_size p_item,bool p_state); + + t_size playlist_get_selection_count(t_size p_playlist,t_size p_max); + t_size activeplaylist_get_selection_count(t_size p_max); + + bool playlist_get_focus_item_handle(metadb_handle_ptr & p_item,t_size p_playlist); + bool activeplaylist_get_focus_item_handle(metadb_handle_ptr & item); + + t_size find_playlist(const char * p_name,t_size p_name_length = ~0); + t_size find_or_create_playlist(const char * p_name,t_size p_name_length = ~0); + t_size find_or_create_playlist_unlocked(const char * p_name,t_size p_name_length = ~0); + + t_size create_playlist_autoname(t_size p_index = ~0); + + bool activeplaylist_sort_by_format(const char * spec,bool p_sel_only); + + t_uint32 activeplaylist_lock_get_filter_mask(); + bool activeplaylist_is_undo_available(); + bool activeplaylist_is_redo_available(); + + bool activeplaylist_execute_default_action(t_size p_item); + + void remove_items_from_all_playlists(const pfc::list_base_const_t & p_data); + + void active_playlist_fix(); + + bool get_all_items(pfc::list_base_t & out); + + void playlist_activate_delta(int p_delta); + void playlist_activate_next() {playlist_activate_delta(1);} + void playlist_activate_previous() {playlist_activate_delta(-1);} + + + t_size playlist_get_selected_count(t_size p_playlist,bit_array const & p_mask); + t_size activeplaylist_get_selected_count(bit_array const & p_mask) {return playlist_get_selected_count(get_active_playlist(),p_mask);} + + bool playlist_find_item(t_size p_playlist,metadb_handle_ptr p_item,t_size & p_result);//inefficient, walks entire playlist + bool playlist_find_item_selected(t_size p_playlist,metadb_handle_ptr p_item,t_size & p_result);//inefficient, walks entire playlist + t_size playlist_set_focus_by_handle(t_size p_playlist,metadb_handle_ptr p_item); + bool activeplaylist_find_item(metadb_handle_ptr p_item,t_size & p_result);//inefficient, walks entire playlist + t_size activeplaylist_set_focus_by_handle(metadb_handle_ptr p_item); + + static void g_make_selection_move_permutation(t_size * p_output,t_size p_count,const bit_array & p_selection,int p_delta); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playlist_manager); +}; + +//! Extension of the playlist_manager service that manages playlist properties. +//! Playlist properties come in two flavors: persistent and runtime. +//! Persistent properties are blocks of binary that that will be preserved when the application is exited and restarted. +//! Runtime properties are service pointers that will be lost when the application exits. +//! \since 0.9.5 +class NOVTABLE playlist_manager_v2 : public playlist_manager { +public: + //! Write a persistent playlist property. + //! \param p_playlist Index of the playlist + //! \param p_property GUID that identifies the property + //! \param p_stream stream that contains the data that will be associated with the property + //! \param p_abort abort_callback that will be used when reading from p_stream + virtual void playlist_set_property(t_size p_playlist,const GUID & p_property,stream_reader * p_stream,t_size p_size_hint,abort_callback & p_abort) = 0; + //! Read a persistent playlist property. + //! \param p_playlist Index of the playlist + //! \param p_property GUID that identifies the property + //! \param p_stream stream that will receive the stored data + //! \param p_abort abort_callback that will be used when writing to p_stream + //! \return true if the property exists, false otherwise + virtual bool playlist_get_property(t_size p_playlist,const GUID & p_property,stream_writer * p_stream,abort_callback & p_abort) = 0; + //! Test existence of a persistent playlist property. + //! \param p_playlist Index of the playlist + //! \param p_property GUID that identifies the property + //! \return true if the property exists, false otherwise + virtual bool playlist_have_property(t_size p_playlist,const GUID & p_property) = 0; + //! Remove a persistent playlist property. + //! \param p_playlist Index of the playlist + //! \param p_property GUID that identifies the property + //! \return true if the property existed, false otherwise + virtual bool playlist_remove_property(t_size p_playlist,const GUID & p_property) = 0; + + //! Write a runtime playlist property. + //! \param p_playlist Index of the playlist + //! \param p_property GUID that identifies the property + //! \param p_data service pointer that will be associated with the property + virtual void playlist_set_runtime_property(t_size p_playlist,const GUID & p_property,service_ptr_t p_data) = 0; + //! Read a runtime playlist property. + //! \param p_playlist Index of the playlist + //! \param p_property GUID that identifies the property + //! \param p_data base service pointer reference that will receive the stored servive pointer + //! \return true if the property exists, false otherwise + virtual bool playlist_get_runtime_property(t_size p_playlist,const GUID & p_property,service_ptr_t & p_data) = 0; + //! Test existence of a runtime playlist property. + //! \param p_playlist Index of the playlist + //! \param p_property GUID that identifies the property + //! \return true if the property exists, false otherwise + virtual bool playlist_have_runtime_property(t_size p_playlist,const GUID & p_property) = 0; + //! Remove a runtime playlist property. + //! \param p_playlist Index of the playlist + //! \param p_property GUID that identifies the property + //! \return true if the property existed, false otherwise + virtual bool playlist_remove_runtime_property(t_size p_playlist,const GUID & p_property) = 0; + + //! Write a persistent playlist property. + //! \param p_playlist Index of the playlist + //! \param p_property GUID that identifies the property + //! \param p_data array that contains the data that will be associated with the property + template void playlist_set_property(t_size p_playlist,const GUID & p_property,const t_array & p_data) { + PFC_STATIC_ASSERT( sizeof(p_data[0]) == 1 ); + playlist_set_property(p_playlist,p_property,&stream_reader_memblock_ref(p_data),p_data.get_size(),abort_callback_dummy()); + } + //! Read a persistent playlist property. + //! \param p_playlist Index of the playlist + //! \param p_property GUID that identifies the property + //! \param p_data array that will receive the stored data + //! \return true if the property exists, false otherwise + template bool playlist_get_property(t_size p_playlist,const GUID & p_property,t_array & p_data) { + PFC_STATIC_ASSERT( sizeof(p_data[0]) == 1 ); + typedef pfc::array_t t_temp; + t_temp temp; + if (!playlist_get_property(p_playlist,p_property,&stream_writer_buffer_append_ref_t(temp),abort_callback_dummy())) return false; + p_data = temp; + return true; + } + //! Read a runtime playlist property. + //! \param p_playlist Index of the playlist + //! \param p_property GUID that identifies the property + //! \param p_data specific service pointer reference that will receive the stored servive pointer + //! \return true if the property exists and can be converted to the type of p_data, false otherwise + template bool playlist_get_runtime_property(t_size p_playlist,const GUID & p_property,service_ptr_t<_t_interface> & p_data) { + service_ptr_t ptr; + if (!playlist_get_runtime_property(p_playlist,p_property,ptr)) return false; + return ptr->service_query_t(p_data); + } + + //! Write a persistent playlist property. + //! \param p_playlist Index of the playlist + //! \param p_property GUID that identifies the property + //! \param p_value integer that will be associated with the property + template + void playlist_set_property_int(t_size p_playlist,const GUID & p_property,_t_int p_value) { + pfc::array_t temp; temp.set_size(sizeof(_t_int)); + pfc::encode_little_endian(temp.get_ptr(),p_value); + playlist_set_property(p_playlist,p_property,temp); + } + //! Read a persistent playlist property. + //! \param p_playlist Index of the playlist + //! \param p_property GUID that identifies the property + //! \param p_value integer reference that will receive the stored data + //! \return true if the property exists and if the data is compatible with p_value, false otherwise + template + bool playlist_get_property_int(t_size p_playlist,const GUID & p_property,_t_int & p_value) { + pfc::array_t temp; + if (!playlist_get_property(p_playlist,p_property,temp)) return false; + if (temp.get_size() != sizeof(_t_int)) return false; + pfc::decode_little_endian(p_value,temp.get_ptr()); + return true; + } + + FB2K_MAKE_SERVICE_INTERFACE(playlist_manager_v2,playlist_manager) +}; + +//! \since 0.9.5 +class NOVTABLE playlist_manager_v3 : public playlist_manager_v2 { + FB2K_MAKE_SERVICE_INTERFACE(playlist_manager_v3,playlist_manager_v2) +public: + virtual t_size recycler_get_count() = 0; + virtual void recycler_get_content(t_size which, metadb_handle_list_ref out) = 0; + virtual void recycler_get_name(t_size which, pfc::string_base & out) = 0; + virtual t_uint32 recycler_get_id(t_size which) = 0; + virtual void recycler_purge(const bit_array & mask) = 0; + virtual void recycler_restore(t_size which) = 0; + + void recycler_restore_by_id(t_uint32 id); + t_size recycler_find_by_id(t_uint32 id); +}; + +//! \since 0.9.5.4 +class NOVTABLE playlist_manager_v4 : public playlist_manager_v3 { + FB2K_MAKE_SERVICE_INTERFACE(playlist_manager_v4, playlist_manager_v3) +public: + virtual void playlist_get_sideinfo(t_size which, stream_writer * stream, abort_callback & abort) = 0; + virtual t_size create_playlist_ex(const char * p_name,t_size p_name_length,t_size p_index, metadb_handle_list_cref content, stream_reader * sideInfo, abort_callback & abort) = 0; +}; + +class NOVTABLE playlist_callback +{ +public: + virtual void on_items_added(t_size p_playlist,t_size p_start, const pfc::list_base_const_t & p_data,const bit_array & p_selection)=0;//inside any of these methods, you can call playlist APIs to get exact info about what happened (but only methods that read playlist state, not those that modify it) + virtual void on_items_reordered(t_size p_playlist,const t_size * p_order,t_size p_count)=0;//changes selection too; doesnt actually change set of items that are selected or item having focus, just changes their order + virtual void on_items_removing(t_size p_playlist,const bit_array & p_mask,t_size p_old_count,t_size p_new_count)=0;//called before actually removing them + virtual void on_items_removed(t_size p_playlist,const bit_array & p_mask,t_size p_old_count,t_size p_new_count)=0; + virtual void on_items_selection_change(t_size p_playlist,const bit_array & p_affected,const bit_array & p_state) = 0; + virtual void on_item_focus_change(t_size p_playlist,t_size p_from,t_size p_to)=0;//focus may be -1 when no item has focus; reminder: focus may also change on other callbacks + + virtual void on_items_modified(t_size p_playlist,const bit_array & p_mask)=0; + virtual void on_items_modified_fromplayback(t_size p_playlist,const bit_array & p_mask,play_control::t_display_level p_level)=0; + + struct t_on_items_replaced_entry + { + t_size m_index; + metadb_handle_ptr m_old,m_new; + }; + + virtual void on_items_replaced(t_size p_playlist,const bit_array & p_mask,const pfc::list_base_const_t & p_data)=0; + + virtual void on_item_ensure_visible(t_size p_playlist,t_size p_idx)=0; + + virtual void on_playlist_activate(t_size p_old,t_size p_new) = 0; + virtual void on_playlist_created(t_size p_index,const char * p_name,t_size p_name_len) = 0; + virtual void on_playlists_reorder(const t_size * p_order,t_size p_count) = 0; + virtual void on_playlists_removing(const bit_array & p_mask,t_size p_old_count,t_size p_new_count) = 0; + virtual void on_playlists_removed(const bit_array & p_mask,t_size p_old_count,t_size p_new_count) = 0; + virtual void on_playlist_renamed(t_size p_index,const char * p_new_name,t_size p_new_name_len) = 0; + + virtual void on_default_format_changed() = 0; + virtual void on_playback_order_changed(t_size p_new_index) = 0; + virtual void on_playlist_locked(t_size p_playlist,bool p_locked) = 0; + + enum { + flag_on_items_added = 1 << 0, + flag_on_items_reordered = 1 << 1, + flag_on_items_removing = 1 << 2, + flag_on_items_removed = 1 << 3, + flag_on_items_selection_change = 1 << 4, + flag_on_item_focus_change = 1 << 5, + flag_on_items_modified = 1 << 6, + flag_on_items_modified_fromplayback = 1 << 7, + flag_on_items_replaced = 1 << 8, + flag_on_item_ensure_visible = 1 << 9, + flag_on_playlist_activate = 1 << 10, + flag_on_playlist_created = 1 << 11, + flag_on_playlists_reorder = 1 << 12, + flag_on_playlists_removing = 1 << 13, + flag_on_playlists_removed = 1 << 14, + flag_on_playlist_renamed = 1 << 15, + flag_on_default_format_changed = 1 << 16, + flag_on_playback_order_changed = 1 << 17, + flag_on_playlist_locked = 1 << 18, + + flag_all = ~0, + flag_item_ops = flag_on_items_added | flag_on_items_reordered | flag_on_items_removing | flag_on_items_removed | flag_on_items_selection_change | flag_on_item_focus_change | flag_on_items_modified | flag_on_items_modified_fromplayback | flag_on_items_replaced | flag_on_item_ensure_visible, + flag_playlist_ops = flag_on_playlist_activate | flag_on_playlist_created | flag_on_playlists_reorder | flag_on_playlists_removing | flag_on_playlists_removed | flag_on_playlist_renamed | flag_on_playlist_locked, + }; +protected: + playlist_callback() {} + ~playlist_callback() {} +}; + +class NOVTABLE playlist_callback_static : public service_base, public playlist_callback +{ +public: + virtual unsigned get_flags() = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playlist_callback_static); +}; + +class NOVTABLE playlist_callback_single +{ +public: + virtual void on_items_added(t_size p_base, const pfc::list_base_const_t & p_data,const bit_array & p_selection)=0;//inside any of these methods, you can call playlist APIs to get exact info about what happened (but only methods that read playlist state, not those that modify it) + virtual void on_items_reordered(const t_size * p_order,t_size p_count)=0;//changes selection too; doesnt actually change set of items that are selected or item having focus, just changes their order + virtual void on_items_removing(const bit_array & p_mask,t_size p_old_count,t_size p_new_count)=0;//called before actually removing them + virtual void on_items_removed(const bit_array & p_mask,t_size p_old_count,t_size p_new_count)=0; + virtual void on_items_selection_change(const bit_array & p_affected,const bit_array & p_state) = 0; + virtual void on_item_focus_change(t_size p_from,t_size p_to)=0;//focus may be -1 when no item has focus; reminder: focus may also change on other callbacks + virtual void on_items_modified(const bit_array & p_mask)=0; + virtual void on_items_modified_fromplayback(const bit_array & p_mask,play_control::t_display_level p_level)=0; + virtual void on_items_replaced(const bit_array & p_mask,const pfc::list_base_const_t & p_data)=0; + virtual void on_item_ensure_visible(t_size p_idx)=0; + + virtual void on_playlist_switch() = 0; + virtual void on_playlist_renamed(const char * p_new_name,t_size p_new_name_len) = 0; + virtual void on_playlist_locked(bool p_locked) = 0; + + virtual void on_default_format_changed() = 0; + virtual void on_playback_order_changed(t_size p_new_index) = 0; + + enum { + flag_on_items_added = 1 << 0, + flag_on_items_reordered = 1 << 1, + flag_on_items_removing = 1 << 2, + flag_on_items_removed = 1 << 3, + flag_on_items_selection_change = 1 << 4, + flag_on_item_focus_change = 1 << 5, + flag_on_items_modified = 1 << 6, + flag_on_items_modified_fromplayback = 1 << 7, + flag_on_items_replaced = 1 << 8, + flag_on_item_ensure_visible = 1 << 9, + flag_on_playlist_switch = 1 << 10, + flag_on_playlist_renamed = 1 << 11, + flag_on_playlist_locked = 1 << 12, + flag_on_default_format_changed = 1 << 13, + flag_on_playback_order_changed = 1 << 14, + flag_all = ~0, + }; +protected: + playlist_callback_single() {} + ~playlist_callback_single() {} +}; + +//! playlist_callback implementation helper - registers itself on creation / unregisters on destruction. Must not be instantiated statically! +class playlist_callback_impl_base : public playlist_callback { +public: + playlist_callback_impl_base(t_uint32 p_flags = 0) { + static_api_ptr_t()->register_callback(this,p_flags); + } + ~playlist_callback_impl_base() { + static_api_ptr_t()->unregister_callback(this); + } + void set_callback_flags(t_uint32 p_flags) { + static_api_ptr_t()->modify_callback(this,p_flags); + } + //dummy implementations - avoid possible pure virtual function calls! + void on_items_added(t_size p_playlist,t_size p_start, const pfc::list_base_const_t & p_data,const bit_array & p_selection) {} + void on_items_reordered(t_size p_playlist,const t_size * p_order,t_size p_count) {} + void on_items_removing(t_size p_playlist,const bit_array & p_mask,t_size p_old_count,t_size p_new_count) {} + void on_items_removed(t_size p_playlist,const bit_array & p_mask,t_size p_old_count,t_size p_new_count) {} + void on_items_selection_change(t_size p_playlist,const bit_array & p_affected,const bit_array & p_state) {} + void on_item_focus_change(t_size p_playlist,t_size p_from,t_size p_to) {} + + void on_items_modified(t_size p_playlist,const bit_array & p_mask) {} + void on_items_modified_fromplayback(t_size p_playlist,const bit_array & p_mask,play_control::t_display_level p_level) {} + + void on_items_replaced(t_size p_playlist,const bit_array & p_mask,const pfc::list_base_const_t & p_data) {} + + void on_item_ensure_visible(t_size p_playlist,t_size p_idx) {} + + void on_playlist_activate(t_size p_old,t_size p_new) {} + void on_playlist_created(t_size p_index,const char * p_name,t_size p_name_len) {} + void on_playlists_reorder(const t_size * p_order,t_size p_count) {} + void on_playlists_removing(const bit_array & p_mask,t_size p_old_count,t_size p_new_count) {} + void on_playlists_removed(const bit_array & p_mask,t_size p_old_count,t_size p_new_count) {} + void on_playlist_renamed(t_size p_index,const char * p_new_name,t_size p_new_name_len) {} + + void on_default_format_changed() {} + void on_playback_order_changed(t_size p_new_index) {} + void on_playlist_locked(t_size p_playlist,bool p_locked) {} +}; + +//! playlist_callback_single implementation helper - registers itself on creation / unregisters on destruction. Must not be instantiated statically! +class playlist_callback_single_impl_base : public playlist_callback_single { +protected: + playlist_callback_single_impl_base(t_uint32 p_flags = 0) { + static_api_ptr_t()->register_callback(this,p_flags); + } + void set_callback_flags(t_uint32 p_flags) { + static_api_ptr_t()->modify_callback(this,p_flags); + } + ~playlist_callback_single_impl_base() { + static_api_ptr_t()->unregister_callback(this); + } + + //dummy implementations - avoid possible pure virtual function calls! + void on_items_added(t_size p_base, const pfc::list_base_const_t & p_data,const bit_array & p_selection) {} + void on_items_reordered(const t_size * p_order,t_size p_count) {} + void on_items_removing(const bit_array & p_mask,t_size p_old_count,t_size p_new_count) {} + void on_items_removed(const bit_array & p_mask,t_size p_old_count,t_size p_new_count) {} + void on_items_selection_change(const bit_array & p_affected,const bit_array & p_state) {} + void on_item_focus_change(t_size p_from,t_size p_to) {} + void on_items_modified(const bit_array & p_mask) {} + void on_items_modified_fromplayback(const bit_array & p_mask,play_control::t_display_level p_level) {} + void on_items_replaced(const bit_array & p_mask,const pfc::list_base_const_t & p_data) {} + void on_item_ensure_visible(t_size p_idx) {} + + void on_playlist_switch() {} + void on_playlist_renamed(const char * p_new_name,t_size p_new_name_len) {} + void on_playlist_locked(bool p_locked) {} + + void on_default_format_changed() {} + void on_playback_order_changed(t_size p_new_index) {} + + PFC_CLASS_NOT_COPYABLE(playlist_callback_single_impl_base,playlist_callback_single_impl_base); +}; + +class playlist_callback_single_static : public service_base, public playlist_callback_single +{ +public: + virtual unsigned get_flags() = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playlist_callback_single_static); +}; + + +//! Class used for async processing of IDataObject. Content of IDataObject can be dumped into dropped_files_data without any time-consuming operations - won't block calling app when used inside drag&drop handler - and actual time-consuming processing (listing directories and reading infos) can be done later.\n +//! \deprecated In 0.9.3 and up, instead of going thru dropped_files_data, you can use playlist_incoming_item_filter_v2::process_dropped_files_async(). +class NOVTABLE dropped_files_data { +public: + virtual void set_paths(pfc::string_list_const const & p_paths) = 0; + virtual void set_handles(const pfc::list_base_const_t & p_handles) = 0; +protected: + dropped_files_data() {} + ~dropped_files_data() {} +}; + + +class NOVTABLE playlist_incoming_item_filter : public service_base { +public: + //! Pre-sorts incoming items according to user-configured settings, removes duplicates. \n + //! @param in Items to process. + //! @param out Receives processed item list. \n + //! NOTE: because of an implementation bug in pre-0.9.5, the output list should be emptied before calling filter_items(), otherwise the results will be inconsistent/unpredictable. + //! @returns True when there's one or more item in the output list, false when the output list is empty. + virtual bool filter_items(metadb_handle_list_cref in,metadb_handle_list_ref out) = 0; + + //! Converts one or more paths to a list of metadb_handles; displays a progress dialog.\n + //! Note that this function creates modal dialog and does not return until the operation has completed. + //! @returns True on success, false on user abort. + //! \deprecated Use playlist_incoming_item_filter_v2::process_locations_async() when possible. + virtual bool process_locations(const pfc::list_base_const_t & p_urls,pfc::list_base_t & p_out,bool p_filter,const char * p_restrict_mask_override, const char * p_exclude_mask_override,HWND p_parentwnd) = 0; + + //! Converts an IDataObject to a list of metadb_handles. + //! Using this function is strongly disrecommended as it implies blocking the drag&drop source app (as well as our app).\n + //! @returns True on success, false on user abort or unknown data format. + //! \deprecated Use playlist_incoming_item_filter_v2::process_dropped_files_async() when possible. + virtual bool process_dropped_files(interface IDataObject * pDataObject,pfc::list_base_t & p_out,bool p_filter,HWND p_parentwnd) = 0; + + //! Checks whether IDataObject contains one of known data formats that can be translated to a list of metadb_handles. + virtual bool process_dropped_files_check(interface IDataObject * pDataObject) = 0; + + //! Checks whether IDataObject contains our own private data format (drag&drop within the app etc). + virtual bool process_dropped_files_check_if_native(interface IDataObject * pDataObject) = 0; + + //! Creates an IDataObject from specified metadb_handle list. The caller is responsible for releasing the returned object. It is recommended that you use create_dataobject_ex() to get an autopointer that ensures proper deletion. + virtual interface IDataObject * create_dataobject(const pfc::list_base_const_t & p_data) = 0; + + //! Checks whether IDataObject contains one of known data formats that can be translated to a list of metadb_handles.\n + //! This function also returns drop effects to use (see: IDropTarget::DragEnter(), IDropTarget::DragOver() ). In certain cases, drag effects are necessary for drag&drop to work at all (such as dragging links from IE).\n + virtual bool process_dropped_files_check_ex(interface IDataObject * pDataObject, DWORD * p_effect) = 0; + + //! Dumps IDataObject content to specified dropped_files_data object, without any time-consuming processing.\n + //! Using this function instead of process_dropped_files() and processing dropped_files_data outside drop handler allows you to avoid blocking drop source app when processing large directories etc.\n + //! Note: since 0.9.3, it is recommended to use playlist_incoming_item_filter_v2::process_dropped_files_async() instead. + //! @returns True on success, false when IDataObject does not contain any of known data formats. + virtual bool process_dropped_files_delayed(dropped_files_data & p_out,interface IDataObject * pDataObject) = 0; + + //! Helper - calls process_locations() with a single URL. See process_locations() for more info. + bool process_location(const char * url,pfc::list_base_t & out,bool filter,const char * p_mask,const char * p_exclude,HWND p_parentwnd); + //! Helper - returns a pfc::com_ptr_t<> rather than a raw pointer. + pfc::com_ptr_t create_dataobject_ex(metadb_handle_list_cref data); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playlist_incoming_item_filter); +}; + +//! For use with playlist_incoming_item_filter_v2::process_locations_async(). +//! \since 0.9.3 +class NOVTABLE process_locations_notify : public service_base { +public: + virtual void on_completion(const pfc::list_base_const_t & p_items) = 0; + virtual void on_aborted() = 0; + + FB2K_MAKE_SERVICE_INTERFACE(process_locations_notify,service_base); +}; + +typedef service_ptr_t process_locations_notify_ptr; + +//! \since 0.9.3 +class NOVTABLE playlist_incoming_item_filter_v2 : public playlist_incoming_item_filter { +public: + enum { + //! Set this to disable presorting (according to user settings) and duplicate removal in output list. Should be unset in most cases. + op_flag_no_filter = 1 << 0, + //! Set this flag to make the progress dialog not steal focus on creation. + op_flag_background = 1 << 1, + //! Set this flag to delay the progress dialog becoming visible, so it does not appear at all during short operations. Also implies op_flag_background effect. + op_flag_delay_ui = 1 << 2, + }; + + //! Converts one or more paths to a list of metadb_handles. The function returns immediately; specified callback object receives results when the operation has completed. + //! @param p_urls List of paths to process. + //! @param p_op_flags Can be null, or one or more of op_flag_* enum values combined, altering behaviors of the operation. + //! @param p_restrict_mask_override Override of "restrict incoming items to" setting. Pass NULL to use the value from preferences. + //! @param p_exclude_mask_override Override of "exclude file types" setting. Pass NULL to use value from preferences. + //! @param p_parentwnd Parent window for spawned progress dialogs. + //! @param p_notify Callback receiving notifications about success/abort of the operation as well as output item list. + virtual void process_locations_async(const pfc::list_base_const_t & p_urls,t_uint32 p_op_flags,const char * p_restrict_mask_override, const char * p_exclude_mask_override,HWND p_parentwnd,process_locations_notify_ptr p_notify) = 0; + + //! Converts an IDataObject to a list of metadb_handles. The function returns immediately; specified callback object receives results when the operation has completed. + //! @param p_dataobject IDataObject to process. + //! @param p_op_flags Can be null, or one or more of op_flag_* enum values combined, altering behaviors of the operation. + //! @param p_parentwnd Parent window for spawned progress dialogs. + //! @param p_notify Callback receiving notifications about success/abort of the operation as well as output item list. + virtual void process_dropped_files_async(interface IDataObject * p_dataobject,t_uint32 p_op_flags,HWND p_parentwnd,process_locations_notify_ptr p_notify) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(playlist_incoming_item_filter_v2,playlist_incoming_item_filter); +}; + +//! \since 0.9.5 +class playlist_incoming_item_filter_v3 : public playlist_incoming_item_filter_v2 { +public: + virtual bool auto_playlist_name(metadb_handle_list_cref data,pfc::string_base & out) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(playlist_incoming_item_filter_v3,playlist_incoming_item_filter_v2) +}; + +//! Implementation of dropped_files_data. +class dropped_files_data_impl : public dropped_files_data { +public: + dropped_files_data_impl() : m_is_paths(false) {} + void set_paths(pfc::string_list_const const & p_paths) { + m_is_paths = true; + m_paths = p_paths; + } + void set_handles(const pfc::list_base_const_t & p_handles) { + m_is_paths = false; + m_handles = p_handles; + } + + void to_handles_async(bool p_filter,HWND p_parentwnd,service_ptr_t p_notify); + //! @param p_op_flags Can be null, or one or more of playlist_incoming_item_filter_v2::op_flag_* enum values combined, altering behaviors of the operation. + void to_handles_async_ex(t_uint32 p_op_flags,HWND p_parentwnd,service_ptr_t p_notify); + bool to_handles(pfc::list_base_t & p_out,bool p_filter,HWND p_parentwnd); +private: + pfc::string_list_impl m_paths; + metadb_handle_list m_handles; + bool m_is_paths; +}; + + +class NOVTABLE playback_queue_callback : public service_base +{ +public: + enum t_change_origin { + changed_user_added, + changed_user_removed, + changed_playback_advance, + }; + virtual void on_changed(t_change_origin p_origin) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playback_queue_callback); +}; + + +class playlist_lock_change_notify : private playlist_callback_single_impl_base { +public: + playlist_lock_change_notify() : playlist_callback_single_impl_base(flag_on_playlist_switch|flag_on_playlist_locked) {} +protected: + virtual void on_lock_state_change() {} + bool is_playlist_command_available(t_uint32 what) const { + static_api_ptr_t api; + const t_size active = api->get_active_playlist(); + if (active == ~0) return false; + return (api->playlist_lock_get_filter_mask(active) & what) == 0; + } +private: + void on_playlist_switch() {on_lock_state_change();} + void on_playlist_locked(bool p_locked) {on_lock_state_change();} +}; diff --git a/SDK/foobar2000/SDK/playlist_loader.cpp b/SDK/foobar2000/SDK/playlist_loader.cpp new file mode 100644 index 0000000..a6b723a --- /dev/null +++ b/SDK/foobar2000/SDK/playlist_loader.cpp @@ -0,0 +1,316 @@ +#include "foobar2000.h" + +#if FOOBAR2000_TARGET_VERSION >= 76 +static void process_path_internal(const char * p_path,const service_ptr_t & p_reader,playlist_loader_callback::ptr callback, abort_callback & abort,playlist_loader_callback::t_entry_type type,const t_filestats & p_stats); + +namespace { + class archive_callback_impl : public archive_callback { + public: + archive_callback_impl(playlist_loader_callback::ptr p_callback, abort_callback & p_abort) : m_callback(p_callback), m_abort(p_abort) {} + bool on_entry(archive * owner,const char * p_path,const t_filestats & p_stats,const service_ptr_t & p_reader) + { + process_path_internal(p_path,p_reader,m_callback,m_abort,playlist_loader_callback::entry_directory_enumerated,p_stats); + return !m_abort.is_aborting(); + } + bool is_aborting() const {return m_abort.is_aborting();} + abort_callback_event get_abort_event() const {return m_abort.get_abort_event();} + private: + const playlist_loader_callback::ptr m_callback; + abort_callback & m_abort; + }; +} + +bool playlist_loader::g_try_load_playlist(file::ptr fileHint,const char * p_path,playlist_loader_callback::ptr p_callback, abort_callback & p_abort) { + pfc::string8 filepath; + + filesystem::g_get_canonical_path(p_path,filepath); + + pfc::string_extension extension(filepath); + + service_ptr_t l_file = fileHint; + + if (l_file.is_empty()) { + filesystem::ptr fs; + if (filesystem::g_get_interface(fs,filepath)) { + if (fs->supports_content_types()) { + fs->open(l_file,filepath,filesystem::open_mode_read,p_abort); + } + } + } + + { + service_enum_t e; + + if (l_file.is_valid()) { + pfc::string8 content_type; + if (l_file->get_content_type(content_type)) { + service_ptr_t l; + e.reset(); while(e.next(l)) { + if (l->is_our_content_type(content_type)) { + try { + TRACK_CODE("playlist_loader::open",l->open(filepath,l_file,p_callback, p_abort)); + return true; + } catch(exception_io_unsupported_format) { + l_file->reopen(p_abort); + } + } + } + } + } + + if (extension.length()>0) { + playlist_loader::ptr l; + e.reset(); while(e.next(l)) { + if (stricmp_utf8(l->get_extension(),extension) == 0) { + if (l_file.is_empty()) filesystem::g_open_read(l_file,filepath,p_abort); + try { + TRACK_CODE("playlist_loader::open",l->open(filepath,l_file,p_callback,p_abort)); + return true; + } catch(exception_io_unsupported_format) { + l_file->reopen(p_abort); + } + } + } + } + } + + return false; +} + +void playlist_loader::g_load_playlist_filehint(file::ptr fileHint,const char * p_path,playlist_loader_callback::ptr p_callback, abort_callback & p_abort) { + if (!g_try_load_playlist(fileHint, p_path, p_callback, p_abort)) throw exception_io_unsupported_format(); +} + +void playlist_loader::g_load_playlist(const char * p_path,playlist_loader_callback::ptr callback, abort_callback & abort) { + g_load_playlist_filehint(NULL,p_path,callback,abort); +} + +static void index_tracks_helper(const char * p_path,const service_ptr_t & p_reader,const t_filestats & p_stats,playlist_loader_callback::t_entry_type p_type,playlist_loader_callback::ptr p_callback, abort_callback & p_abort,bool & p_got_input) +{ + TRACK_CALL_TEXT("index_tracks_helper"); + if (p_reader.is_empty() && filesystem::g_is_remote_safe(p_path)) + { + TRACK_CALL_TEXT("remote"); + metadb_handle_ptr handle; + p_callback->handle_create(handle,make_playable_location(p_path,0)); + p_got_input = true; + p_callback->on_entry(handle,p_type,p_stats,true); + } else { + TRACK_CALL_TEXT("hintable"); + service_ptr_t instance; + input_entry::g_open_for_info_read(instance,p_reader,p_path,p_abort); + + t_filestats stats = instance->get_file_stats(p_abort); + + t_uint32 subsong,subsong_count = instance->get_subsong_count(); + bool bInfoGetError = false; + for(subsong=0;subsongget_subsong(subsong); + p_callback->handle_create(handle,make_playable_location(p_path,index)); + + p_got_input = true; + if (! bInfoGetError && p_callback->want_info(handle,p_type,stats,true) ) + { + file_info_impl info; + try { + TRACK_CODE("get_info",instance->get_info(index,info,p_abort)); + } catch(...) { + bInfoGetError = true; + } + p_callback->on_entry_info(handle,p_type,stats,info,true); + } + else + { + p_callback->on_entry(handle,p_type,stats,true); + } + } + } +} + +static void track_indexer__g_get_tracks_wrap(const char * p_path,const service_ptr_t & p_reader,const t_filestats & p_stats,playlist_loader_callback::t_entry_type p_type,playlist_loader_callback::ptr p_callback, abort_callback & p_abort) { + bool got_input = false; + bool fail = false; + try { + index_tracks_helper(p_path,p_reader,p_stats,p_type,p_callback,p_abort, got_input); + } catch(exception_aborted) { + throw; + } catch(exception_io_unsupported_format) { + fail = true; + } catch(std::exception const & e) { + fail = true; + console::formatter() << "could not enumerate tracks (" << e << ") on:\n" << file_path_display(p_path); + } + if (fail) { + if (!got_input && !p_abort.is_aborting()) { + if (p_type == playlist_loader_callback::entry_user_requested) + { + metadb_handle_ptr handle; + p_callback->handle_create(handle,make_playable_location(p_path,0)); + p_callback->on_entry(handle,p_type,p_stats,true); + } + } + } +} + +namespace { + // SPECIAL HACK + // filesystem service does not present file hidden attrib but we want to weed files/folders out + // so check separately on all native paths (inefficient but meh) + class directory_callback_impl2 : public directory_callback_impl + { + public: + bool on_entry(filesystem * owner,abort_callback & p_abort,const char * url,bool is_subdirectory,const t_filestats & p_stats) { + p_abort.check(); + + if (!m_addHidden) { + const char * n = url; + if (_extract_native_path_ptr(n)) { + DWORD att = uGetFileAttributes(n); + if (att == ~0 || (att & FILE_ATTRIBUTE_HIDDEN) != 0) return true; + } + } + + return directory_callback_impl::on_entry(owner, p_abort, url, is_subdirectory, p_stats); + } + + directory_callback_impl2(bool p_recur) : directory_callback_impl(p_recur), m_addHidden(queryAddHidden()) {} + private: + static bool queryAddHidden() { + // {2F9F4956-363F-4045-9531-603B1BF39BA8} + static const GUID guid_cfg_addhidden = + { 0x2f9f4956, 0x363f, 0x4045, { 0x95, 0x31, 0x60, 0x3b, 0x1b, 0xf3, 0x9b, 0xa8 } }; + + advconfig_entry_checkbox::ptr ptr; + if (advconfig_entry::g_find_t(ptr, guid_cfg_addhidden)) { + return ptr->get_state(); + } + return false; + } + const bool m_addHidden; + }; +} + + +static void process_path_internal(const char * p_path,const service_ptr_t & p_reader,playlist_loader_callback::ptr callback, abort_callback & abort,playlist_loader_callback::t_entry_type type,const t_filestats & p_stats) +{ + //p_path must be canonical + + abort.check(); + + callback->on_progress(p_path); + + + { + if (p_reader.is_empty() && type != playlist_loader_callback::entry_directory_enumerated) { + directory_callback_impl2 directory_results(true); + try { + filesystem::g_list_directory(p_path,directory_results,abort); + for(t_size n=0;n e; + service_ptr_t f; + while(e.next(f)) { + abort.check(); + service_ptr_t arch; + if (f->service_query_t(arch)) { + if (p_reader.is_valid()) p_reader->reopen(abort); + + try { + TRACK_CODE("archive::archive_list",arch->archive_list(p_path,p_reader,archive_results,true)); + return; + } catch(exception_aborted) {throw;} + catch(...) {} + } + } + } + } + + + + { + service_ptr_t ptr; + if (link_resolver::g_find(ptr,p_path)) + { + if (p_reader.is_valid()) p_reader->reopen(abort); + + pfc::string8 temp; + try { + TRACK_CODE("link_resolver::resolve",ptr->resolve(p_reader,p_path,temp,abort)); + + track_indexer__g_get_tracks_wrap(temp,0,filestats_invalid,playlist_loader_callback::entry_from_playlist,callback, abort); + return;//success + } catch(exception_aborted) {throw;} + catch(...) {} + } + } + + if (callback->is_path_wanted(p_path,type)) { + track_indexer__g_get_tracks_wrap(p_path,p_reader,p_stats,type,callback, abort); + } +} + +void playlist_loader::g_process_path(const char * p_filename,playlist_loader_callback::ptr callback, abort_callback & abort,playlist_loader_callback::t_entry_type type) +{ + TRACK_CALL_TEXT("playlist_loader::g_process_path"); + + file_path_canonical filename(p_filename); + + process_path_internal(filename,0,callback,abort, type,filestats_invalid); +} + +void playlist_loader::g_save_playlist(const char * p_filename,const pfc::list_base_const_t & data,abort_callback & p_abort) +{ + TRACK_CALL_TEXT("playlist_loader::g_save_playlist"); + pfc::string8 filename; + filesystem::g_get_canonical_path(p_filename,filename); + try { + service_ptr_t r; + filesystem::g_open(r,filename,filesystem::open_mode_write_new,p_abort); + + pfc::string_extension ext(filename); + + service_enum_t e; + service_ptr_t l; + if (e.first(l)) do { + if (l->can_write() && !stricmp_utf8(ext,l->get_extension())) { + try { + TRACK_CODE("playlist_loader::write",l->write(filename,r,data,p_abort)); + return; + } catch(exception_io_data) {} + } + } while(e.next(l)); + throw exception_io_data(); + } catch(...) { + try {filesystem::g_remove(filename,p_abort);} catch(...) {} + throw; + } +} + + +bool playlist_loader::g_process_path_ex(const char * filename,playlist_loader_callback::ptr callback, abort_callback & abort,playlist_loader_callback::t_entry_type type) +{ + if (g_try_load_playlist(NULL, filename, callback, abort)) return true; + //not a playlist format + g_process_path(filename,callback,abort,type); + return false; +} + +#endif \ No newline at end of file diff --git a/SDK/foobar2000/SDK/playlist_loader.h b/SDK/foobar2000/SDK/playlist_loader.h new file mode 100644 index 0000000..de1de4b --- /dev/null +++ b/SDK/foobar2000/SDK/playlist_loader.h @@ -0,0 +1,132 @@ +#if FOOBAR2000_TARGET_VERSION >= 76 +//! Callback interface receiving item locations from playlist loader. \n +//! Typically, you call one of standard services such as playlist_incoming_item_filter instead of implementing this interface and calling playlist_loader methods directly. +class NOVTABLE playlist_loader_callback : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(playlist_loader_callback, service_base) +public: + //! Enumeration type representing origin of item passed to playlist_loader_callback. + enum t_entry_type { + //! User-requested (such as directly dropped to window or picked in openfiledialog). + entry_user_requested, + //! From directory content enumeration. + entry_directory_enumerated, + //! Referenced by playlist file. + entry_from_playlist, + }; + //! Indicates specified path being processed; provided for updating GUI. Note that optimally GUI should not be updated every time this is called because that could introduce a bottleneck. + virtual void on_progress(const char * p_path) = 0; + + //! Receives an item from one of playlist_loader functions. + //! @param p_item Item location, in form of metadb_handle pointer. + //! @param p_type Origin of this item - see t_entry_type for more info. + //! @param p_stats File stats of this item; set to filestats_invalid if not available. + //! @param p_fresh Fresh flag; indicates whether stats are directly from filesystem (true) or as stored earlier in a playlist file (false). + virtual void on_entry(const metadb_handle_ptr & p_item,t_entry_type p_type,const t_filestats & p_stats,bool p_fresh) = 0; + //! Queries whether file_info for specified item is requested. In typical scenario, if want_info() returns false, on_entry() will be called with same parameters; otherwise caller will attempt to read info from the item and call on_entry_info() with same parameters and file_info read from the item. + //! @param p_item Item location, in form of metadb_handle pointer. + //! @param p_type Origin of this item - see t_entry_type for more info. + //! @param p_stats File stats of this item; set to filestats_invalid if not available. + //! @param p_fresh Fresh flag; indicates whether stats are directly from filesystem (true) or as stored earlier in a playlist file (false). + virtual bool want_info(const metadb_handle_ptr & p_item,t_entry_type p_type,const t_filestats & p_stats,bool p_fresh) = 0; + //! Receives an item from one of playlist_loader functions; including file_info data. Except for file_info to be typically used as hint for metadb backend, behavior of this method is same as on_entry(). + //! @param p_item Item location, in form of metadb_handle pointer. + //! @param p_type Origin of this item - see t_entry_type for more info. + //! @param p_stats File stats of this item; set to filestats_invalid if not available. + //! @param p_info Information about the item, read from the file directly (if p_fresh is set to true) or from e.g. playlist file (if p_fresh is set to false). + //! @param p_fresh Fresh flag; indicates whether stats are directly from filesystem (true) or as stored earlier in a playlist file (false). + virtual void on_entry_info(const metadb_handle_ptr & p_item,t_entry_type p_type,const t_filestats & p_stats,const file_info & p_info,bool p_fresh) = 0; + + //! Same as metadb::handle_create(); provided here to avoid repeated metadb instantiation bottleneck since calling code will need this function often. + virtual void handle_create(metadb_handle_ptr & p_out,const playable_location & p_location) = 0; + + //! Returns whether further on_entry() calls for this file are wanted. Typically always returns true, can be used to optimize cases when directories are searched for files matching specific pattern only so unwanted files aren't parsed unnecessarily. + //! @param path Canonical path to the media file being processed. + virtual bool is_path_wanted(const char * path, t_entry_type type) = 0; + + virtual bool want_browse_info(const metadb_handle_ptr & p_item,t_entry_type p_type,t_filetimestamp ts) = 0; + virtual void on_browse_info(const metadb_handle_ptr & p_item,t_entry_type p_type,const file_info & info, t_filetimestamp ts) = 0; +}; + +//! \since 1.3 +//! Extended version of playlist_loader_callback, allowing caller to pass pre-made metadb_info_container \n +class NOVTABLE playlist_loader_callback_v2 : public playlist_loader_callback { + FB2K_MAKE_SERVICE_INTERFACE(playlist_loader_callback_v2, playlist_loader_callback) +public: + virtual void on_entry_info_v2(const metadb_handle_ptr & p_item,t_entry_type p_type,metadb_info_container::ptr info,bool p_fresh) = 0; + virtual void on_browse_info_v2(const metadb_handle_ptr & p_item,t_entry_type p_type,metadb_info_container::ptr info) = 0; +private: +}; + + +//! Service handling playlist file operations. There are multiple implementations handling different playlist formats; you can add new implementations to allow new custom playlist file formats to be read or written.\n +//! Also provides static helper functions for turning a filesystem path into a list of playable item locations. \n +//! Note that you should typically call playlist_incoming_item_filter methods instead of calling playlist_loader methods directly to get a list of playable items from a specified path; this way you get a core-implemented threading and abortable dialog displaying progress.\n +//! To register your own implementation, use playlist_loader_factory_t template.\n +//! To call existing implementations, use static helper methods of playlist_loader class. +class NOVTABLE playlist_loader : public service_base { +public: + //! Parses specified playlist file into list of playable locations. Throws exception_io or derivatives on failure, exception_aborted on abort. If specified file is not a recognized playlist file, exception_io_unsupported_format is thrown. + //! @param p_path Path of playlist file to parse. Used for relative path handling purposes (p_file parameter is used for actual file access). + //! @param p_file File interface to use for reading. Read/write pointer must be set to beginning by caller before calling. + //! @param p_callback Callback object receiving enumerated playable item locations. + virtual void open(const char * p_path, const service_ptr_t & p_file,playlist_loader_callback::ptr p_callback, abort_callback & p_abort) = 0; + //! Writes a playlist file containing specific item list to specified file. Will fail (pfc::exception_not_implemented) if specified playlist_loader is read-only (can_write() returns false). + //! @param p_path Path of playlist file to write. Used for relative path handling purposes (p_file parameter is used for actual file access). + //! @param p_file File interface to use for writing. Caller should ensure that the file is empty (0 bytes long) before calling. + //! @param p_data List of items to save to playlist file. + //! @param p_abort abort_callback object signaling user aborting the operation. Note that aborting a save playlist operation will most likely leave user with corrupted/incomplete file. + virtual void write(const char * p_path, const service_ptr_t & p_file,metadb_handle_list_cref p_data,abort_callback & p_abort) = 0; + //! Returns extension of file format handled by this playlist_loader implementation (a UTF-8 encoded null-terminated string). + virtual const char * get_extension() = 0; + //! Returns whether this playlist_loader implementation supports writing. If can_write() returns false, all write() calls will fail. + virtual bool can_write() = 0; + //! Returns whether specified content type is one of playlist types supported by this playlist_loader implementation or not. + //! @param p_content_type Content type to query, a UTF-8 encoded null-terminated string. + virtual bool is_our_content_type(const char* p_content_type) = 0; + //! Returns whether playlist format extension supported by this implementation should be listed on file types associations page. + virtual bool is_associatable() = 0; + + //! Attempts to load a playlist file from specified filesystem path. Throws exception_io or derivatives on failure, exception_aborted on abort. If specified file is not a recognized playlist file, exception_io_unsupported_format is thrown. \n + //! Equivalent to g_load_playlist_filehint(NULL,p_path,p_callback). + //! @param p_path Filesystem path to load playlist from, a UTF-8 encoded null-terminated string. + //! @param p_callback Callback object receiving enumerated playable item locations as well as signaling user aborting the operation. + static void g_load_playlist(const char * p_path,playlist_loader_callback::ptr p_callback, abort_callback & p_abort); + + //! Attempts to load a playlist file from specified filesystem path. Throws exception_io or derivatives on failure, exception_aborted on abort. If specified file is not a recognized playlist file, exception_io_unsupported_format is thrown. + //! @param p_path Filesystem path to load playlist from, a UTF-8 encoded null-terminated string. + //! @param p_callback Callback object receiving enumerated playable item locations as well as signaling user aborting the operation. + //! @param fileHint File object to read from, can be NULL if not available. + static void g_load_playlist_filehint(file::ptr fileHint,const char * p_path,playlist_loader_callback::ptr p_callback, abort_callback & p_abort); + + //! Attempts to load a playlist file from specified filesystem path. Throws exception_io or derivatives on failure, exception_aborted on abort. If specified file is not a recognized playlist file, returns false; returns true upon successful playlist load. + //! @param p_path Filesystem path to load playlist from, a UTF-8 encoded null-terminated string. + //! @param p_callback Callback object receiving enumerated playable item locations as well as signaling user aborting the operation. + //! @param fileHint File object to read from, can be NULL if not available. + static bool g_try_load_playlist(file::ptr fileHint,const char * p_path,playlist_loader_callback::ptr p_callback, abort_callback & p_abort); + + //! Saves specified list of locations into a playlist file. Throws exception_io or derivatives on failure, exception_aborted on abort. + //! @param p_path Filesystem path to save playlist to, a UTF-8 encoded null-terminated string. + //! @param p_data List of items to save to playlist file. + //! @param p_abort abort_callback object signaling user aborting the operation. Note that aborting a save playlist operation will most likely leave user with corrupted/incomplete file. + static void g_save_playlist(const char * p_path,metadb_handle_list_cref p_data,abort_callback & p_abort); + + //! Processes specified path to generate list of playable items. Includes recursive directory/archive enumeration. \n + //! Does not touch playlist files encountered - use g_process_path_ex() if specified path is possibly a playlist file; playlist files found inside directories or archives are ignored regardless.\n + //! Warning: caller must handle exceptions which will occur in case of I/O failure. + //! @param p_path Filesystem path to process; a UTF-8 encoded null-terminated string. + //! @param p_callback Callback object receiving enumerated playable item locations as well as signaling user aborting the operation. + //! @param p_type Origin of p_path string. Reserved for internal use in recursive calls, should be left at default value; it controls various internal behaviors. + static void g_process_path(const char * p_path,playlist_loader_callback::ptr p_callback, abort_callback & p_abort,playlist_loader_callback::t_entry_type p_type = playlist_loader_callback::entry_user_requested); + + //! Calls attempts to process specified path as a playlist; if that fails (i.e. not a playlist), calls g_process_path with same parameters. See g_process_path for parameter descriptions. \n + //! Warning: caller must handle exceptions which will occur in case of I/O failure or playlist parsing failure. + //! @returns True if specified path was processed as a playlist file, false otherwise (relevant in some scenarios where output is sorted after loading, playlist file contents should not be sorted). + static bool g_process_path_ex(const char * p_path,playlist_loader_callback::ptr p_callback, abort_callback & p_abort,playlist_loader_callback::t_entry_type p_type = playlist_loader_callback::entry_user_requested); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playlist_loader); +}; + +template +class playlist_loader_factory_t : public service_factory_single_t {}; + +#endif \ No newline at end of file diff --git a/SDK/foobar2000/SDK/popup_message.cpp b/SDK/foobar2000/SDK/popup_message.cpp new file mode 100644 index 0000000..bbbd278 --- /dev/null +++ b/SDK/foobar2000/SDK/popup_message.cpp @@ -0,0 +1,39 @@ +#include "foobar2000.h" + +void popup_message::g_show_ex(const char * p_msg,unsigned p_msg_length,const char * p_title,unsigned p_title_length,t_icon p_icon) +{ + // Do not force instantiate, not all platforms have this + service_enum_t< popup_message > e; + service_ptr_t< popup_message > m; + if (e.first( m ) ) { + m->show_ex( p_msg, p_msg_length, p_title, p_title_length, p_icon ); + } +} + + +void popup_message::g_complain(const char * what) { + g_show(what, "Information", icon_error); +} + +void popup_message::g_complain(const char * p_whatFailed, const std::exception & p_exception) { + g_complain(p_whatFailed,p_exception.what()); +} +void popup_message::g_complain(const char * p_whatFailed, const char * msg) { + g_complain( PFC_string_formatter() << p_whatFailed << ": " << msg ); +} + +void popup_message_v2::g_show(HWND parent, const char * msg, const char * title) { + service_enum_t< popup_message_v2 > e; + service_ptr_t< popup_message_v2 > m; + if (e.first( m )) { + m->show(parent, msg, title); + } else { + popup_message::g_show( msg, title ); + } +} +void popup_message_v2::g_complain(HWND parent, const char * whatFailed, const char * msg) { + g_show(parent, PFC_string_formatter() << whatFailed << ": " << msg); +} +void popup_message_v2::g_complain(HWND parent, const char * whatFailed, const std::exception & e) { + g_complain(parent, whatFailed, e.what()); +} diff --git a/SDK/foobar2000/SDK/popup_message.h b/SDK/foobar2000/SDK/popup_message.h new file mode 100644 index 0000000..b1622b0 --- /dev/null +++ b/SDK/foobar2000/SDK/popup_message.h @@ -0,0 +1,47 @@ + +//! This interface allows you to show generic nonmodal noninteractive dialog with a text message. This should be used instead of MessageBox where possible.\n +//! Usage: use popup_message::g_show / popup_message::g_show_ex static helpers, or static_api_ptr_t.\n +//! Note that all strings are UTF-8. + +class NOVTABLE popup_message : public service_base { +public: + enum t_icon {icon_information, icon_error, icon_query}; + //! Activates the popup dialog; returns immediately (the dialog remains visible). + //! @param p_msg Message to show (UTF-8 encoded string). + //! @param p_msg_length Length limit of message string to show, in bytes (actual string may be shorter if null terminator is encountered before). Set this to infinite to use plain null-terminated strings. + //! @param p_title Title of dialog to show (UTF-8 encoded string). + //! @param p_title_length Length limit of the title string, in bytes (actual string may be shorter if null terminator is encountered before). Set this to infinite to use plain null-terminated strings. + //! @param p_icon Icon of the dialog - can be set to icon_information, icon_error or icon_query. + virtual void show_ex(const char * p_msg,unsigned p_msg_length,const char * p_title,unsigned p_title_length,t_icon p_icon = icon_information) = 0; + + //! Activates the popup dialog; returns immediately (the dialog remains visible); helper function built around show_ex(), takes null terminated strings with no length limit parameters. + //! @param p_msg Message to show (UTF-8 encoded string). + //! @param p_title Title of dialog to show (UTF-8 encoded string). + //! @param p_icon Icon of the dialog - can be set to icon_information, icon_error or icon_query. + inline void show(const char * p_msg,const char * p_title,t_icon p_icon = icon_information) {show_ex(p_msg,~0,p_title,~0,p_icon);} + + //! Static helper function instantiating the service and activating the message dialog. See show_ex() for description of parameters. + static void g_show_ex(const char * p_msg,unsigned p_msg_length,const char * p_title,unsigned p_title_length,t_icon p_icon = icon_information); + //! Static helper function instantiating the service and activating the message dialog. See show() for description of parameters. + static inline void g_show(const char * p_msg,const char * p_title,t_icon p_icon = icon_information) {g_show_ex(p_msg,~0,p_title,~0,p_icon);} + + static void g_complain(const char * what); + static void g_complain(const char * p_whatFailed, const std::exception & p_exception); + static void g_complain(const char * p_whatFailed, const char * msg); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(popup_message); +}; + +#define EXCEPTION_TO_POPUP_MESSAGE(CODE,LABEL) try { CODE; } catch(std::exception const & e) {popup_message::g_complain(LABEL,e);} + +//! \since 1.1 +class NOVTABLE popup_message_v2 : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(popup_message_v2); +public: + virtual void show(HWND parent, const char * msg, t_size msg_length, const char * title, t_size title_length) = 0; + void show(HWND parent, const char * msg, const char * title) {show(parent, msg, ~0, title, ~0);} + + static void g_show(HWND parent, const char * msg, const char * title = "Information"); + static void g_complain(HWND parent, const char * whatFailed, const char * msg); + static void g_complain(HWND parent, const char * whatFailed, const std::exception & e); +}; diff --git a/SDK/foobar2000/SDK/preferences_page.cpp b/SDK/foobar2000/SDK/preferences_page.cpp new file mode 100644 index 0000000..01da1f7 --- /dev/null +++ b/SDK/foobar2000/SDK/preferences_page.cpp @@ -0,0 +1,10 @@ +#include "foobar2000.h" + +void preferences_page::get_help_url_helper(pfc::string_base & out, const char * category, const GUID & id, const char * name) { + out.reset(); + out << "http://help.foobar2000.org/" << core_version_info::g_get_version_string() << "/" << category << "/" << pfc::print_guid(id) << "/" << name; +} +bool preferences_page::get_help_url(pfc::string_base & p_out) { + get_help_url_helper(p_out,"preferences",get_guid(), get_name()); + return true; +} diff --git a/SDK/foobar2000/SDK/preferences_page.h b/SDK/foobar2000/SDK/preferences_page.h new file mode 100644 index 0000000..7632680 --- /dev/null +++ b/SDK/foobar2000/SDK/preferences_page.h @@ -0,0 +1,136 @@ +//! Implementing this service will generate a page in preferences dialog. Use preferences_page_factory_t template to register. \n +//! In 1.0 and newer you should always derive from preferences_page_v3 rather than from preferences_page directly. +class NOVTABLE preferences_page : public service_base { +public: + //! Obsolete. + virtual HWND create(HWND p_parent) = 0; + //! Retrieves name of the prefernces page to be displayed in preferences tree (static string). + virtual const char * get_name() = 0; + //! Retrieves GUID of the page. + virtual GUID get_guid() = 0; + //! Retrieves GUID of parent page/branch of this page. See preferences_page::guid_* constants for list of standard parent GUIDs. Can also be a GUID of another page or a branch (see: preferences_branch). + virtual GUID get_parent_guid() = 0; + //! Obsolete. + virtual bool reset_query() = 0; + //! Obsolete. + virtual void reset() = 0; + //! Retrieves help URL. Without overriding it, it will redirect to foobar2000 wiki. + virtual bool get_help_url(pfc::string_base & p_out); + + static void get_help_url_helper(pfc::string_base & out, const char * category, const GUID & id, const char * name); + + static const GUID guid_root, guid_hidden, guid_tools,guid_core,guid_display,guid_playback,guid_visualisations,guid_input,guid_tag_writing,guid_media_library, guid_tagging; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(preferences_page); +}; + +class NOVTABLE preferences_page_v2 : public preferences_page { +public: + //! Allows custom sorting order of preferences pages. Return lower value for higher priority (lower resulting index in the list). When sorting priority of two items matches, alphabetic sorting is used. Return 0 to use default alphabetic sorting without overriding priority. + virtual double get_sort_priority() {return 0;} + + FB2K_MAKE_SERVICE_INTERFACE(preferences_page_v2,preferences_page); +}; + +template +class preferences_page_factory_t : public service_factory_single_t {}; + +//! Creates a preferences branch - an empty page that only serves as a parent for other pages and is hidden when no child pages exist. Instead of implementing this, simply use preferences_branch_factory class to declare a preferences branch with specified parameters. +class NOVTABLE preferences_branch : public service_base { +public: + //! Retrieves name of the preferences branch. + virtual const char * get_name() = 0; + //! Retrieves GUID of the preferences branch. Use this GUID as parent GUID for pages/branches nested in this branch. + virtual GUID get_guid() = 0; + //! Retrieves GUID of parent page/branch of this branch. See preferences_page::guid_* constants for list of standard parent GUIDs. Can also be a GUID of another branch or a page. + virtual GUID get_parent_guid() = 0; + + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(preferences_branch); +}; + +class preferences_branch_v2 : public preferences_branch { +public: + //! Allows custom sorting order of preferences pages. Return lower value for higher priority (lower resulting index in the list). When sorting priority of two items matches, alphabetic sorting is used. Return 0 to use default alphabetic sorting without overriding priority. + virtual double get_sort_priority() {return 0;} + + FB2K_MAKE_SERVICE_INTERFACE(preferences_branch_v2,preferences_branch); +}; + +class preferences_branch_impl : public preferences_branch_v2 { +public: + preferences_branch_impl(const GUID & p_guid,const GUID & p_parent,const char * p_name,double p_sort_priority = 0) : m_guid(p_guid), m_parent(p_parent), m_name(p_name), m_sort_priority(p_sort_priority) {} + const char * get_name() {return m_name;} + GUID get_guid() {return m_guid;} + GUID get_parent_guid() {return m_parent;} + double get_sort_priority() {return m_sort_priority;} +private: + const GUID m_guid,m_parent; + const pfc::string8 m_name; + const double m_sort_priority; +}; + +typedef service_factory_single_t _preferences_branch_factory; + +//! Instantiating this class declares a preferences branch with specified parameters.\n +//! Usage: static preferences_branch_factory g_mybranch(mybranchguid,parentbranchguid,"name of my preferences branch goes here"); +class preferences_branch_factory : public _preferences_branch_factory { +public: + preferences_branch_factory(const GUID & p_guid,const GUID & p_parent,const char * p_name,double p_sort_priority = 0) : _preferences_branch_factory(p_guid,p_parent,p_name,p_sort_priority) {} +}; + + + + +class preferences_state { +public: + enum { + changed = 1, + needs_restart = 2, + needs_restart_playback = 4, + resettable = 8, + + //! \since 1.1 + //! Indicates that the dialog is currently busy and cannot be applied or cancelled. Do not use without a good reason! \n + //! This flag was introduced in 1.1. It will not be respected in earlier foobar2000 versions. It is recommended not to use this flag unless you are absolutely sure that you need it and take appropriate precautions. \n + //! Note that this has no power to entirely prevent your preferences page from being destroyed/cancelled as a result of app shutdown if the user dismisses the warnings, but you won't be getting an "apply" call while this is set. + busy = 16, + }; +}; + +class preferences_page_callback : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(preferences_page_callback, service_base) +public: + virtual void on_state_changed() = 0; +}; + +//! \since 1.0 +//! Implements a preferences page instance. \n +//! Instantiated through preferences_page_v3::instantiate(). \n +//! Note that the window will be destroyed by the caller before the last reference to the preferences_page_instance is released. \n +//! WARNING: misguided use of modal dialogs - or ANY windows APIs that might spawn such dialogs - may result in conditions when the owner dialog (along with your page) is destroyed somewhere inside your message handler, also releasing references to your object. \n +//! It is recommended to use window_service_impl_t<> from ATLHelpers to instantiate preferences_page_instances, or preferences_page_impl<> framework for your preferences_page code to cleanly workaround such cases. +class preferences_page_instance : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(preferences_page_instance, service_base) +public: + //! @returns a combination of preferences_state constants. + virtual t_uint32 get_state() = 0; + //! @returns the window handle. + virtual HWND get_wnd() = 0; + //! Applies preferences changes. + virtual void apply() = 0; + //! Resets this page's content to the default values. Does not apply any changes - lets user preview the changes before hitting "apply". + virtual void reset() = 0; +}; + +//! \since 1.0 +//! Implements a preferences page. +class preferences_page_v3 : public preferences_page_v2 { + FB2K_MAKE_SERVICE_INTERFACE(preferences_page_v3, preferences_page_v2) +public: + virtual preferences_page_instance::ptr instantiate(HWND parent, preferences_page_callback::ptr callback) = 0; +private: + HWND create(HWND p_parent) {throw pfc::exception_not_implemented();} //stub + bool reset_query() {return false;} //stub - the new apply-friendly reset should be used instead. + void reset() {} //stub +}; diff --git a/SDK/foobar2000/SDK/progress_meter.h b/SDK/foobar2000/SDK/progress_meter.h new file mode 100644 index 0000000..f1a4639 --- /dev/null +++ b/SDK/foobar2000/SDK/progress_meter.h @@ -0,0 +1,18 @@ +//! Interface for setting current operation progress state to be visible on Windows 7 taskbar. Use static_api_ptr_t()->acquire() to instantiate. +class NOVTABLE progress_meter_instance : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(progress_meter_instance, service_base); +public: + //! Sets the current progress state. + //! @param value Progress state, in 0..1 range. + virtual void set_progress(float value) = 0; + //! Toggles paused state. + virtual void set_pause(bool isPaused) = 0; +}; + +//! Entrypoint interface for instantiating progress_meter_instance objects. +class NOVTABLE progress_meter : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(progress_meter); +public: + //! Creates a progress_meter_instance object. + virtual progress_meter_instance::ptr acquire() = 0; +}; diff --git a/SDK/foobar2000/SDK/replaygain.cpp b/SDK/foobar2000/SDK/replaygain.cpp new file mode 100644 index 0000000..1e918cc --- /dev/null +++ b/SDK/foobar2000/SDK/replaygain.cpp @@ -0,0 +1,220 @@ +#include "foobar2000.h" + +void t_replaygain_config::reset() +{ + m_source_mode = source_mode_none; + m_processing_mode = processing_mode_none; + m_preamp_without_rg = 0; + m_preamp_with_rg = 0; +} + +audio_sample t_replaygain_config::query_scale(const file_info & info) const +{ + return query_scale(info.get_replaygain()); +} + +audio_sample t_replaygain_config::query_scale(const replaygain_info & info) const { + const audio_sample peak_margin = 1.0;//used to be 0.999 but it must not trigger on lossless + + audio_sample peak = peak_margin; + audio_sample gain = 0; + + bool have_rg_gain = false, have_rg_peak = false; + + if (m_source_mode == source_mode_track || m_source_mode == source_mode_album) + { + float gain_select = replaygain_info::gain_invalid, peak_select = replaygain_info::peak_invalid; + if (m_source_mode == source_mode_track) + { + if (info.is_track_gain_present()) {gain = info.m_track_gain; have_rg_gain = true; } + else if (info.is_album_gain_present()) {gain = info.m_album_gain; have_rg_gain = true; } + if (info.is_track_peak_present()) {peak = info.m_track_peak; have_rg_peak = true; } + else if (info.is_album_peak_present()) {peak = info.m_album_peak; have_rg_peak = true; } + } + else + { + if (info.is_album_gain_present()) {gain = info.m_album_gain; have_rg_gain = true; } + else if (info.is_track_gain_present()) {gain = info.m_track_gain; have_rg_gain = true; } + if (info.is_album_peak_present()) {peak = info.m_album_peak; have_rg_peak = true; } + else if (info.is_track_peak_present()) {peak = info.m_track_peak; have_rg_peak = true; } + } + } + + gain += have_rg_gain ? m_preamp_with_rg : m_preamp_without_rg; + + audio_sample scale = 1.0; + + if (m_processing_mode == processing_mode_gain || m_processing_mode == processing_mode_gain_and_peak) + { + scale *= audio_math::gain_to_scale(gain); + } + + if (m_processing_mode == processing_mode_peak || m_processing_mode == processing_mode_gain_and_peak) + { + if (scale * peak > peak_margin) + scale = (audio_sample)(peak_margin / peak); + } + + return scale; +} + +audio_sample t_replaygain_config::query_scale(const metadb_handle_ptr & p_object) const +{ + return query_scale(p_object->get_async_info_ref()->info()); +} + +audio_sample replaygain_manager::core_settings_query_scale(const file_info & p_info) +{ + t_replaygain_config temp; + get_core_settings(temp); + return temp.query_scale(p_info); +} + +audio_sample replaygain_manager::core_settings_query_scale(const metadb_handle_ptr & info) +{ + t_replaygain_config temp; + get_core_settings(temp); + return temp.query_scale(info); +} + +//enum t_source_mode {source_mode_none,source_mode_track,source_mode_album}; +//enum t_processing_mode {processing_mode_none,processing_mode_gain,processing_mode_gain_and_peak,processing_mode_peak}; +namespace { +class format_dbdelta +{ +public: + format_dbdelta(double p_val); + operator const char*() const {return m_buffer;} +private: + pfc::string_fixed_t<128> m_buffer; +}; +static const char * querysign(int val) { + return val<0 ? "-" : val>0 ? "+" : "\xc2\xb1"; +} + +format_dbdelta::format_dbdelta(double p_val) { + int val = (int)(p_val * 10); + m_buffer << querysign(val) << (abs(val)/10) << "." << (abs(val)%10) << "dB"; +} +} +void t_replaygain_config::format_name(pfc::string_base & p_out) const +{ + switch(m_processing_mode) + { + case processing_mode_none: + p_out = "None."; + break; + case processing_mode_gain: + switch(m_source_mode) + { + case source_mode_none: + if (m_preamp_without_rg == 0) p_out = "None."; + else p_out = PFC_string_formatter() << "Preamp : " << format_dbdelta(m_preamp_without_rg); + break; + case source_mode_track: + { + pfc::string_formatter fmt; + fmt << "Apply track gain"; + if (m_preamp_without_rg != 0 || m_preamp_with_rg != 0) fmt << ", with preamp"; + fmt << "."; + p_out = fmt; + } + break; + case source_mode_album: + { + pfc::string_formatter fmt; + fmt << "Apply album gain"; + if (m_preamp_without_rg != 0 || m_preamp_with_rg != 0) fmt << ", with preamp"; + fmt << "."; + p_out = fmt; + } + break; + }; + break; + case processing_mode_gain_and_peak: + switch(m_source_mode) + { + case source_mode_none: + if (m_preamp_without_rg >= 0) p_out = "None."; + else p_out = PFC_string_formatter() << "Preamp : " << format_dbdelta(m_preamp_without_rg); + break; + case source_mode_track: + { + pfc::string_formatter fmt; + fmt << "Apply track gain"; + if (m_preamp_without_rg != 0 || m_preamp_with_rg != 0) fmt << ", with preamp"; + fmt << ", prevent clipping according to track peak."; + p_out = fmt; + } + break; + case source_mode_album: + { + pfc::string_formatter fmt; + fmt << "Apply album gain"; + if (m_preamp_without_rg != 0 || m_preamp_with_rg != 0) fmt << ", with preamp"; + fmt << ", prevent clipping according to album peak."; + p_out = fmt; + } + break; + }; + break; + case processing_mode_peak: + switch(m_source_mode) + { + case source_mode_none: + p_out = "None."; + break; + case source_mode_track: + p_out = "Prevent clipping according to track peak."; + break; + case source_mode_album: + p_out = "Prevent clipping according to album peak."; + break; + }; + break; + } +} + +bool t_replaygain_config::is_active() const +{ + switch(m_processing_mode) + { + case processing_mode_none: + return false; + case processing_mode_gain: + switch(m_source_mode) + { + case source_mode_none: + return m_preamp_without_rg != 0; + case source_mode_track: + return true; + case source_mode_album: + return true; + }; + return false; + case processing_mode_gain_and_peak: + switch(m_source_mode) + { + case source_mode_none: + return m_preamp_without_rg < 0; + case source_mode_track: + return true; + case source_mode_album: + return true; + }; + return false; + case processing_mode_peak: + switch(m_source_mode) + { + case source_mode_none: + return false; + case source_mode_track: + return true; + case source_mode_album: + return true; + }; + return false; + default: + return false; + } +} diff --git a/SDK/foobar2000/SDK/replaygain.h b/SDK/foobar2000/SDK/replaygain.h new file mode 100644 index 0000000..65251be --- /dev/null +++ b/SDK/foobar2000/SDK/replaygain.h @@ -0,0 +1,74 @@ +//! Structure storing ReplayGain configuration: album/track source data modes, gain/peak processing modes and preamp values. +struct t_replaygain_config +{ + enum /*t_source_mode*/ { + source_mode_none, + source_mode_track, + source_mode_album, + // New in 1.3.8 + // SPECIAL MODE valid only for playback settings; if set, track gain will be used for random & shuffle-tracks modes, album for shuffle albums & ordered playback. + source_mode_byPlaybackOrder + }; + enum /*t_processing_mode*/ {processing_mode_none,processing_mode_gain,processing_mode_gain_and_peak,processing_mode_peak}; + typedef t_uint32 t_source_mode; typedef t_uint32 t_processing_mode; + + t_replaygain_config() {reset();} + t_replaygain_config(t_source_mode p_source_mode,t_processing_mode p_processing_mode,float p_preamp_without_rg, float p_preamp_with_rg) + : m_source_mode(p_source_mode), m_processing_mode(p_processing_mode), m_preamp_without_rg(p_preamp_without_rg), m_preamp_with_rg(p_preamp_with_rg) {} + + + t_source_mode m_source_mode; + t_processing_mode m_processing_mode; + float m_preamp_without_rg, m_preamp_with_rg;//preamp values in dB + + void reset(); + audio_sample query_scale(const file_info & info) const; + audio_sample query_scale(const metadb_handle_ptr & info) const; + audio_sample query_scale(const replaygain_info & info) const; + + void format_name(pfc::string_base & p_out) const; + bool is_active() const; + + static bool equals(const t_replaygain_config & v1, const t_replaygain_config & v2) { + return v1.m_source_mode == v2.m_source_mode && v1.m_processing_mode == v2.m_processing_mode && v1.m_preamp_without_rg == v2.m_preamp_without_rg && v1.m_preamp_with_rg == v2.m_preamp_with_rg; + } + bool operator==(const t_replaygain_config & other) const {return equals(*this, other);} + bool operator!=(const t_replaygain_config & other) const {return !equals(*this, other);} +}; + +FB2K_STREAM_READER_OVERLOAD(t_replaygain_config) { + return stream >> value.m_source_mode >> value.m_processing_mode >> value.m_preamp_with_rg >> value.m_preamp_without_rg; +} +FB2K_STREAM_WRITER_OVERLOAD(t_replaygain_config) { + return stream << value.m_source_mode << value.m_processing_mode << value.m_preamp_with_rg << value.m_preamp_without_rg; +} + +//! Core service providing methods to retrieve/alter playback ReplayGain settings, as well as use ReplayGain configuration dialog. +class NOVTABLE replaygain_manager : public service_base { +public: + //! Retrieves playback ReplayGain settings. + virtual void get_core_settings(t_replaygain_config & p_out) = 0; + + //! Creates embedded version of ReplayGain settings dialog. Note that embedded dialog sends WM_COMMAND with id/BN_CLICKED to parent window when user makes changes to settings. + virtual HWND configure_embedded(const t_replaygain_config & p_initdata,HWND p_parent,unsigned p_id,bool p_from_modal) = 0; + //! Retrieves settings from embedded version of ReplayGain settings dialog. + virtual void configure_embedded_retrieve(HWND wnd,t_replaygain_config & p_data) = 0; + + //! Shows popup/modal version of ReplayGain settings dialog. Returns true when user changed the settings, false when user cancelled the operation. Title parameter can be null to use default one. + virtual bool configure_popup(t_replaygain_config & p_data,HWND p_parent,const char * p_title) = 0; + + //! Alters playback ReplayGain settings. + virtual void set_core_settings(const t_replaygain_config & p_config) = 0; + + //! New in 1.0 + virtual void configure_embedded_set(HWND wnd, t_replaygain_config const & p_data) = 0; + //! New in 1.0 + virtual void get_core_defaults(t_replaygain_config & out) = 0; + + //! Helper; queries scale value for specified item according to core playback settings. + audio_sample core_settings_query_scale(const file_info & p_info); + //! Helper; queries scale value for specified item according to core playback settings. + audio_sample core_settings_query_scale(const metadb_handle_ptr & info); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(replaygain_manager); +}; diff --git a/SDK/foobar2000/SDK/replaygain_info.cpp b/SDK/foobar2000/SDK/replaygain_info.cpp new file mode 100644 index 0000000..8986a6b --- /dev/null +++ b/SDK/foobar2000/SDK/replaygain_info.cpp @@ -0,0 +1,142 @@ +#include "foobar2000.h" + +#ifdef _MSC_VER +#define RG_FPU() fpu_control_roundnearest bah; +#else +#define RG_FPU() +#endif + +bool replaygain_info::g_format_gain(float p_value,char p_buffer[text_buffer_size]) +{ + RG_FPU(); + if (p_value == gain_invalid) + { + p_buffer[0] = 0; + return false; + } + else + { + pfc::float_to_string(p_buffer,text_buffer_size - 4,p_value,2,true); + strcat(p_buffer," dB"); + return true; + } +} + +bool replaygain_info::g_format_peak(float p_value,char p_buffer[text_buffer_size]) +{ + RG_FPU(); + if (p_value == peak_invalid) + { + p_buffer[0] = 0; + return false; + } + else + { + pfc::float_to_string(p_buffer,text_buffer_size,p_value,6,false); + return true; + } +} + +void replaygain_info::reset() +{ + m_album_gain = gain_invalid; + m_track_gain = gain_invalid; + m_album_peak = peak_invalid; + m_track_peak = peak_invalid; +} + +static const char meta_album_gain[] = "replaygain_album_gain", meta_album_peak[] = "replaygain_album_peak", meta_track_gain[] = "replaygain_track_gain", meta_track_peak[] = "replaygain_track_peak"; + +bool replaygain_info::g_is_meta_replaygain(const char * p_name,t_size p_name_len) +{ + return + stricmp_utf8_ex(p_name,p_name_len,meta_album_gain,~0) == 0 || + stricmp_utf8_ex(p_name,p_name_len,meta_album_peak,~0) == 0 || + stricmp_utf8_ex(p_name,p_name_len,meta_track_gain,~0) == 0 || + stricmp_utf8_ex(p_name,p_name_len,meta_track_peak,~0) == 0; +} + +bool replaygain_info::set_from_meta_ex(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len) +{ + RG_FPU(); + if (stricmp_utf8_ex(p_name,p_name_len,meta_album_gain,~0) == 0) + { + m_album_gain = (float)pfc::string_to_float(p_value,p_value_len); + return true; + } + else if (stricmp_utf8_ex(p_name,p_name_len,meta_album_peak,~0) == 0) + { + m_album_peak = (float)pfc::string_to_float(p_value,p_value_len); + if (m_album_peak < 0) m_album_peak = 0; + return true; + } + else if (stricmp_utf8_ex(p_name,p_name_len,meta_track_gain,~0) == 0) + { + m_track_gain = (float)pfc::string_to_float(p_value,p_value_len); + return true; + } + else if (stricmp_utf8_ex(p_name,p_name_len,meta_track_peak,~0) == 0) + { + m_track_peak = (float)pfc::string_to_float(p_value,p_value_len); + if (m_track_peak < 0) m_track_peak = 0; + return true; + } + else return false; +} + + +t_size replaygain_info::get_value_count() +{ + t_size ret = 0; + if (is_album_gain_present()) ret++; + if (is_album_peak_present()) ret++; + if (is_track_gain_present()) ret++; + if (is_track_peak_present()) ret++; + return ret; +} + +void replaygain_info::set_album_gain_text(const char * p_text,t_size p_text_len) +{ + RG_FPU(); + if (p_text != 0 && p_text_len > 0 && *p_text != 0) + m_album_gain = (float)pfc::string_to_float(p_text,p_text_len); + else + remove_album_gain(); +} + +void replaygain_info::set_track_gain_text(const char * p_text,t_size p_text_len) +{ + RG_FPU(); + if (p_text != 0 && p_text_len > 0 && *p_text != 0) + m_track_gain = (float)pfc::string_to_float(p_text,p_text_len); + else + remove_track_gain(); +} + +void replaygain_info::set_album_peak_text(const char * p_text,t_size p_text_len) +{ + RG_FPU(); + if (p_text != 0 && p_text_len > 0 && *p_text != 0) + m_album_peak = (float)pfc::string_to_float(p_text,p_text_len); + else + remove_album_peak(); +} + +void replaygain_info::set_track_peak_text(const char * p_text,t_size p_text_len) +{ + RG_FPU(); + if (p_text != 0 && p_text_len > 0 && *p_text != 0) + m_track_peak = (float)pfc::string_to_float(p_text,p_text_len); + else + remove_track_peak(); +} + +replaygain_info replaygain_info::g_merge(replaygain_info r1,replaygain_info r2) +{ + replaygain_info ret = r1; + if (!ret.is_album_gain_present()) ret.m_album_gain = r2.m_album_gain; + if (!ret.is_album_peak_present()) ret.m_album_peak = r2.m_album_peak; + if (!ret.is_track_gain_present()) ret.m_track_gain = r2.m_track_gain; + if (!ret.is_track_peak_present()) ret.m_track_peak = r2.m_track_peak; + return ret; +} diff --git a/SDK/foobar2000/SDK/replaygain_scanner.h b/SDK/foobar2000/SDK/replaygain_scanner.h new file mode 100644 index 0000000..2d8e98f --- /dev/null +++ b/SDK/foobar2000/SDK/replaygain_scanner.h @@ -0,0 +1,41 @@ +//! Container of ReplayGain scan results from one or more tracks. +class replaygain_result : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(replaygain_result, service_base); +public: + //! Retrieves the gain value, in dB. + virtual float get_gain() = 0; + //! Retrieves the peak value, normalized to 0..1 range (audio_sample value). + virtual float get_peak() = 0; + //! Merges ReplayGain scan results from different tracks. Merge results from all tracks in an album to get album gain/peak values. \n + //! This function returns a newly created replaygain_result object. Existing replaygain_result objects remain unaltered. + virtual replaygain_result::ptr merge(replaygain_result::ptr other) = 0; + + replaygain_info make_track_info() { + replaygain_info ret = replaygain_info_invalid; ret.m_track_gain = this->get_gain(); ret.m_track_peak = this->get_peak(); return ret; + } +}; + +//! Instance of a ReplayGain scanner. \n +//! Use static_api_ptr_t()->instantiate() to create a replaygain_scanner object; see replaygain_scanner_entry for more info. \n +//! Typical use: call process_chunk() with each chunk read from your track, call finalize() to obtain results for this track and reset replaygain_scanner's state for scanning another track; to obtain album gain/peak values, merge results (replaygain_result::merge) from all tracks. \n +class replaygain_scanner : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(replaygain_scanner, service_base); +public: + //! Processes a PCM chunk. \n + //! May throw exception_io_data if the chunk contains something that can't be processed properly. + virtual void process_chunk(const audio_chunk & chunk) = 0; + //! Finalizes the scanning process; resets scanner's internal state and returns results for the track we've just scanned. \n + //! After calling finalize(), scanner's state becomes the same as after instantiation; you can continue with processing another track without creating a new scanner object. + virtual replaygain_result::ptr finalize() = 0; +}; + + +//! Entrypoint class for instantiating replaygain_scanner objects. Use static_api_ptr_t()->instantiate() to create replaygain_scanner instances. \n +//! This service is OPTIONAL; it's available from foobar2000 0.9.5.3 up but only if the ReplayGain Scanner component is installed. \n +//! It is recommended that you use replaygain_scanner like this: try { myInstance = static_api_ptr_t()->instantiate(); } catch(exception_service_not_found) { /* too old foobar2000 version or no foo_rgscan installed - complain/fail/etc */ } +class replaygain_scanner_entry : public service_base { + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(replaygain_scanner_entry); +public: + //! Instantiates a replaygain_scanner object. + virtual replaygain_scanner::ptr instantiate() = 0; +}; diff --git a/SDK/foobar2000/SDK/resampler.h b/SDK/foobar2000/SDK/resampler.h new file mode 100644 index 0000000..f73d77d --- /dev/null +++ b/SDK/foobar2000/SDK/resampler.h @@ -0,0 +1,25 @@ +class NOVTABLE resampler_entry : public dsp_entry +{ +public: + virtual bool is_conversion_supported(unsigned p_srate_from,unsigned p_srate_to) = 0; + virtual bool create_preset(dsp_preset & p_out,unsigned p_target_srate,float p_qualityscale) = 0;//p_qualityscale is 0...1 + virtual float get_priority() = 0;//value is 0...1, where high-quality (SSRC etc) has 1 + + static bool g_get_interface(service_ptr_t & p_out,unsigned p_srate_from,unsigned p_srate_to); + static bool g_create(service_ptr_t & p_out,unsigned p_srate_from,unsigned p_srate_to,float p_qualityscale); + static bool g_create_preset(dsp_preset & p_out,unsigned p_srate_from,unsigned p_srate_to,float p_qualityscale); + + FB2K_MAKE_SERVICE_INTERFACE(resampler_entry,dsp_entry); +}; + +template +class resampler_entry_impl_t : public dsp_entry_impl_t +{ +public: + bool is_conversion_supported(unsigned p_srate_from,unsigned p_srate_to) {return T::g_is_conversion_supported(p_srate_from,p_srate_to);} + bool create_preset(dsp_preset & p_out,unsigned p_target_srate,float p_qualityscale) {return T::g_create_preset(p_out,p_target_srate,p_qualityscale);} + float get_priority() {return T::g_get_priority();} +}; + +template +class resampler_factory_t : public service_factory_single_t > {}; diff --git a/SDK/foobar2000/SDK/search_tools.cpp b/SDK/foobar2000/SDK/search_tools.cpp new file mode 100644 index 0000000..d5fc210 --- /dev/null +++ b/SDK/foobar2000/SDK/search_tools.cpp @@ -0,0 +1,7 @@ +#include "foobar2000.h" + +void search_filter_manager::show_manual() { + pfc::string8 temp; + get_manual(temp); + popup_message::g_show(temp,"Search Expression Reference"); +} diff --git a/SDK/foobar2000/SDK/search_tools.h b/SDK/foobar2000/SDK/search_tools.h new file mode 100644 index 0000000..404dc16 --- /dev/null +++ b/SDK/foobar2000/SDK/search_tools.h @@ -0,0 +1,71 @@ +//! Instance of a search filter object. New in 0.9.5. \n +//! This object contains a preprocessed search query; used to perform filtering similar to Media Library Search or Album List's "filter" box. \n +//! Use search_filter_manager API to instantiate search_filter objects. +class search_filter : public service_base { +public: +protected: + //! For backwards compatibility with older (0.9.5 alpha) revisions of this API. Do not call. + virtual bool test_locked(const metadb_handle_ptr & p_item,const file_info * p_info) = 0; +public: + + //! Use this to run this filter on a group of items. + //! @param data Items to test. + //! @param out Pointer to a buffer (size at least equal to number of items in the source list) receiving the results. + virtual void test_multi(metadb_handle_list_cref data, bool * out) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(search_filter,service_base); +}; + +//! New in 0.9.5.3. You can obtain a search_filter_v2 pointer by using service_query() on a search_filter pointer, or from search_filter_manager_v2::create_ex(). +class search_filter_v2 : public search_filter { +public: + virtual bool get_sort_pattern(titleformat_object::ptr & out, int & direction) = 0; + + //! Abortable version of test_multi(). If the abort_callback object becomes signaled while the operation is being performed, contents of the output buffer are undefined and the operation will fail with exception_aborted. + virtual void test_multi_ex(metadb_handle_list_cref data, bool * out, abort_callback & abort) = 0; + + //! Helper; removes non-matching items from the list. + void test_multi_here(metadb_handle_list & ref, abort_callback & abort); + + FB2K_MAKE_SERVICE_INTERFACE(search_filter_v2, search_filter) +}; + +//! New in 0.9.5.4. You can obtain a search_filter_v2 pointer by using service_query() on a search_filter/search_filter_v2 pointer. +class search_filter_v3 : public search_filter_v2 { +public: + //! Returns whether the sort pattern returned by get_sort_pattern() was set by the user explicitly using "SORT BY" syntax or whether it was determined implicitly from some other part of the query. It's recommended to use this to determine whether to create a force-sorted autoplaylist or not. + virtual bool is_sort_explicit() = 0; + + FB2K_MAKE_SERVICE_INTERFACE(search_filter_v3, search_filter_v2) +}; + +//! Entrypoint class to instantiate search_filter objects. New in 0.9.5. +class search_filter_manager : public service_base { +public: + //! Creates a search_filter object. Throws an exception on failure (such as an error in the query). It's recommended that you relay the exception message to the user if this function fails. + virtual search_filter::ptr create(const char * p_query) = 0; + + //! Retrieves the search expression manual string. See also: show_manual(). + virtual void get_manual(pfc::string_base & p_out) = 0; + + void show_manual(); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(search_filter_manager); +}; + +//! New in 0.9.5.3. +class search_filter_manager_v2 : public search_filter_manager { +public: + enum { + KFlagAllowSort = 1 << 0, + KFlagSuppressNotify = 1 << 1, + }; + //! Creates a search_filter object. Throws an exception on failure (such as an error in the query). It's recommended that you relay the exception message to the user if this function fails. + //! @param changeNotify A completion_notify callback object that will get called each time the query's behavior changes as a result of some external event (such as system time change). The caller must refresh query results each time this callback is triggered. The status parameter of its on_completion() parameter is unused and always set to zero. + virtual search_filter_v2::ptr create_ex(const char * query, completion_notify::ptr changeNotify, t_uint32 flags) = 0; + + //! Opens the search query syntax reference document, typically an external HTML in user's default web browser. + virtual void show_manual() = 0; + + FB2K_MAKE_SERVICE_INTERFACE(search_filter_manager_v2, search_filter_manager); +}; diff --git a/SDK/foobar2000/SDK/service.cpp b/SDK/foobar2000/SDK/service.cpp new file mode 100644 index 0000000..2301f6f --- /dev/null +++ b/SDK/foobar2000/SDK/service.cpp @@ -0,0 +1,59 @@ +#include "foobar2000.h" +#include "component.h" + +foobar2000_api * g_foobar2000_api = NULL; + +service_class_ref service_factory_base::enum_find_class(const GUID & p_guid) +{ + PFC_ASSERT(core_api::are_services_available() && g_foobar2000_api); + return g_foobar2000_api->service_enum_find_class(p_guid); +} + +bool service_factory_base::enum_create(service_ptr_t & p_out,service_class_ref p_class,t_size p_index) +{ + PFC_ASSERT(core_api::are_services_available() && g_foobar2000_api); + return g_foobar2000_api->service_enum_create(p_out,p_class,p_index); +} + +t_size service_factory_base::enum_get_count(service_class_ref p_class) +{ + PFC_ASSERT(core_api::are_services_available() && g_foobar2000_api); + return g_foobar2000_api->service_enum_get_count(p_class); +} + +service_factory_base * service_factory_base::__internal__list = NULL; + + + + + +namespace { + class main_thread_callback_release_object : public main_thread_callback { + public: + main_thread_callback_release_object(service_ptr obj) : m_object(obj) {} + void callback_run() { + try { m_object.release(); } catch(...) {} + } + private: + service_ptr m_object; + }; +} +namespace service_impl_helper { + void release_object_delayed(service_ptr obj) { + static_api_ptr_t()->add_callback(new service_impl_t(obj)); + } +}; + + +void _standard_api_create_internal(service_ptr & out, const GUID & classID) { + service_class_ref c = service_factory_base::enum_find_class(classID); + switch(service_factory_base::enum_get_count(c)) { + case 0: + throw exception_service_not_found(); + case 1: + PFC_ASSERT_SUCCESS( service_factory_base::enum_create(out, c, 0) ); + break; + default: + throw exception_service_duplicated(); + } +} diff --git a/SDK/foobar2000/SDK/service.h b/SDK/foobar2000/SDK/service.h new file mode 100644 index 0000000..cd52d95 --- /dev/null +++ b/SDK/foobar2000/SDK/service.h @@ -0,0 +1,770 @@ +#ifndef _foobar2000_sdk_service_h_included_ +#define _foobar2000_sdk_service_h_included_ + +typedef const void* service_class_ref; + +PFC_DECLARE_EXCEPTION(exception_service_not_found,pfc::exception,"Service not found"); +PFC_DECLARE_EXCEPTION(exception_service_extension_not_found,pfc::exception,"Service extension not found"); +PFC_DECLARE_EXCEPTION(exception_service_duplicated,pfc::exception,"Service duplicated"); + +#ifdef _MSC_VER +#define FOOGUIDDECL __declspec(selectany) +#else +#define FOOGUIDDECL +#endif + + +#define DECLARE_GUID(NAME,A,S,D,F,G,H,J,K,L,Z,X) FOOGUIDDECL const GUID NAME = {A,S,D,{F,G,H,J,K,L,Z,X}}; +#define DECLARE_CLASS_GUID(NAME,A,S,D,F,G,H,J,K,L,Z,X) FOOGUIDDECL const GUID NAME::class_guid = {A,S,D,{F,G,H,J,K,L,Z,X}}; + +//! Special hack to ensure errors when someone tries to ->service_add_ref()/->service_release() on a service_ptr_t +template class service_obscure_refcounting : public T { +private: + int service_add_ref() throw(); + int service_release() throw(); +}; + +//! Converts a service interface pointer to a pointer that obscures service counter functionality. +template static inline service_obscure_refcounting* service_obscure_refcounting_cast(T * p_source) throw() {return static_cast*>(p_source);} + +//Must be templated instead of taking service_base* because of multiple inheritance issues. +template static void service_release_safe(T * p_ptr) throw() { + if (p_ptr != NULL) PFC_ASSERT_NO_EXCEPTION( p_ptr->service_release() ); +} + +//Must be templated instead of taking service_base* because of multiple inheritance issues. +template static void service_add_ref_safe(T * p_ptr) throw() { + if (p_ptr != NULL) PFC_ASSERT_NO_EXCEPTION( p_ptr->service_add_ref() ); +} + +class service_base; + +template +class service_ptr_base_t { +public: + inline T* get_ptr() const throw() {return m_ptr;} +protected: + T * m_ptr; +}; + +// forward declaration +template class service_nnptr_t; + +//! Autopointer class to be used with all services. Manages reference counter calls behind-the-scenes. +template +class service_ptr_t : public service_ptr_base_t { +private: + typedef service_ptr_t t_self; + + template void _init(t_source * in) throw() { + this->m_ptr = in; + if (this->m_ptr) this->m_ptr->service_add_ref(); + } + template void _init(t_source && in) throw() { + this->m_ptr = in.detach(); + } +public: + service_ptr_t() throw() {this->m_ptr = NULL;} + service_ptr_t(T * p_ptr) throw() {_init(p_ptr);} + service_ptr_t(const t_self & p_source) throw() {_init(p_source.get_ptr());} + service_ptr_t(t_self && p_source) throw() {_init(std::move(p_source));} + template service_ptr_t(t_source * p_ptr) throw() {_init(p_ptr);} + template service_ptr_t(const service_ptr_base_t & p_source) throw() {_init(p_source.get_ptr());} + template service_ptr_t(const service_nnptr_t & p_source) throw() { this->m_ptr = p_source.get_ptr(); this->m_ptr->service_add_ref(); } + template service_ptr_t(service_ptr_t && p_source) throw() { _init(std::move(p_source)); } + + ~service_ptr_t() throw() {service_release_safe(this->m_ptr);} + + template + void copy(t_source * p_ptr) throw() { + service_add_ref_safe(p_ptr); + service_release_safe(this->m_ptr); + this->m_ptr = pfc::safe_ptr_cast(p_ptr); + } + + template + void copy(const service_ptr_base_t & p_source) throw() {copy(p_source.get_ptr());} + + template + void copy(service_ptr_t && p_source) throw() {attach(p_source.detach());} + + + inline const t_self & operator=(const t_self & p_source) throw() {copy(p_source); return *this;} + inline const t_self & operator=(t_self && p_source) throw() {copy(std::move(p_source)); return *this;} + inline const t_self & operator=(T * p_ptr) throw() {copy(p_ptr); return *this;} + + template inline t_self & operator=(const service_ptr_base_t & p_source) throw() {copy(p_source); return *this;} + template inline t_self & operator=(service_ptr_t && p_source) throw() {copy(std::move(p_source)); return *this;} + template inline t_self & operator=(t_source * p_ptr) throw() {copy(p_ptr); return *this;} + + template inline t_self & operator=(const service_nnptr_t & p_ptr) throw() { + service_release_safe(this->m_ptr); + t_source * ptr = p_ptr.get_ptr(); + ptr->service_add_ref(); + this->m_ptr = ptr; + return *this; + } + + + inline void release() throw() { + service_release_safe(this->m_ptr); + this->m_ptr = NULL; + } + + + inline service_obscure_refcounting* operator->() const throw() {PFC_ASSERT(this->m_ptr != NULL);return service_obscure_refcounting_cast(this->m_ptr);} + + inline T* get_ptr() const throw() {return this->m_ptr;} + + inline bool is_valid() const throw() {return this->m_ptr != NULL;} + inline bool is_empty() const throw() {return this->m_ptr == NULL;} + + inline bool operator==(const service_ptr_base_t & p_item) const throw() {return this->m_ptr == p_item.get_ptr();} + inline bool operator!=(const service_ptr_base_t & p_item) const throw() {return this->m_ptr != p_item.get_ptr();} + + inline bool operator>(const service_ptr_base_t & p_item) const throw() {return this->m_ptr > p_item.get_ptr();} + inline bool operator<(const service_ptr_base_t & p_item) const throw() {return this->m_ptr < p_item.get_ptr();} + + inline bool operator==(T * p_item) const throw() {return this->m_ptr == p_item;} + inline bool operator!=(T * p_item) const throw() {return this->m_ptr != p_item;} + + inline bool operator>(T * p_item) const throw() {return this->m_ptr > p_item;} + inline bool operator<(T * p_item) const throw() {return this->m_ptr < p_item;} + + template + inline t_self & operator<<(service_ptr_t & p_source) throw() {attach(p_source.detach());return *this;} + template + inline t_self & operator>>(service_ptr_t & p_dest) throw() {p_dest.attach(detach());return *this;} + + + inline T* _duplicate_ptr() const throw() {//should not be used ! temporary ! + service_add_ref_safe(this->m_ptr); + return this->m_ptr; + } + + inline T* detach() throw() { + return pfc::replace_null_t(this->m_ptr); + } + + template + inline void attach(t_source * p_ptr) throw() { + service_release_safe(this->m_ptr); + this->m_ptr = pfc::safe_ptr_cast(p_ptr); + } + + T & operator*() const throw() {return *this->m_ptr;} + + service_ptr_t & _as_base_ptr() { + PFC_ASSERT( _as_base_ptr_check() ); + return *reinterpret_cast*>(this); + } + static bool _as_base_ptr_check() { + return static_cast((T*)NULL) == reinterpret_cast((T*)NULL); + } + + //! Forced cast operator - obtains a valid service pointer to the expected class or crashes the app if such pointer cannot be obtained. + template + void operator ^= ( otherPtr_t other ) { + PFC_ASSERT( other.is_valid() ); + if (!other->cast(*this)) uBugCheck(); + } + + //! Conditional cast operator - attempts to obtain a vaild service pointer to the expected class; returns true on success, false on failure. + template + bool operator &= ( otherPtr_t other ) { + PFC_ASSERT( other.is_valid() ); + return other->cast(*this); + } + +}; + +//! Autopointer class to be used with all services. Manages reference counter calls behind-the-scenes. \n +//! This assumes that the pointers are valid all the time (can't point to null). Mainly intended to be used for scenarios where null pointers are not valid and relevant code should crash ASAP if somebody passes invalid pointers around. \n +//! You want to use service_ptr_t<> rather than service_nnptr_t<> most of the time. +template +class service_nnptr_t : public service_ptr_base_t { +private: + typedef service_nnptr_t t_self; + + template void _init(t_source * in) { + this->m_ptr = in; + this->m_ptr->service_add_ref(); + } + service_nnptr_t() throw() {pfc::crash();} +public: + service_nnptr_t(T * p_ptr) throw() {_init(p_ptr);} + service_nnptr_t(const t_self & p_source) throw() {_init(p_source.get_ptr());} + template service_nnptr_t(t_source * p_ptr) throw() {_init(p_ptr);} + template service_nnptr_t(const service_ptr_base_t & p_source) throw() {_init(p_source.get_ptr());} + + template service_nnptr_t(service_ptr_t && p_source) throw() {this->m_ptr = p_source.detach();} + + ~service_nnptr_t() throw() {this->m_ptr->service_release();} + + template + void copy(t_source * p_ptr) throw() { + p_ptr->service_add_ref(); + this->m_ptr->service_release(); + this->m_ptr = pfc::safe_ptr_cast(p_ptr); + } + + template + void copy(const service_ptr_base_t & p_source) throw() {copy(p_source.get_ptr());} + + + inline const t_self & operator=(const t_self & p_source) throw() {copy(p_source); return *this;} + inline const t_self & operator=(T * p_ptr) throw() {copy(p_ptr); return *this;} + + template inline t_self & operator=(const service_ptr_base_t & p_source) throw() {copy(p_source); return *this;} + template inline t_self & operator=(t_source * p_ptr) throw() {copy(p_ptr); return *this;} + template inline t_self & operator=(service_ptr_t && p_source) throw() {this->m_ptr->service_release(); this->m_ptr = p_source.detach();} + + + inline service_obscure_refcounting* operator->() const throw() {PFC_ASSERT(this->m_ptr != NULL);return service_obscure_refcounting_cast(this->m_ptr);} + + inline T* get_ptr() const throw() {return this->m_ptr;} + + inline bool is_valid() const throw() {return true;} + inline bool is_empty() const throw() {return false;} + + inline bool operator==(const service_ptr_base_t & p_item) const throw() {return this->m_ptr == p_item.get_ptr();} + inline bool operator!=(const service_ptr_base_t & p_item) const throw() {return this->m_ptr != p_item.get_ptr();} + + inline bool operator>(const service_ptr_base_t & p_item) const throw() {return this->m_ptr > p_item.get_ptr();} + inline bool operator<(const service_ptr_base_t & p_item) const throw() {return this->m_ptr < p_item.get_ptr();} + + inline bool operator==(T * p_item) const throw() {return this->m_ptr == p_item;} + inline bool operator!=(T * p_item) const throw() {return this->m_ptr != p_item;} + + inline bool operator>(T * p_item) const throw() {return this->m_ptr > p_item;} + inline bool operator<(T * p_item) const throw() {return this->m_ptr < p_item;} + + inline T* _duplicate_ptr() const throw() {//should not be used ! temporary ! + service_add_ref_safe(this->m_ptr); + return this->m_ptr; + } + + T & operator*() const throw() {return *this->m_ptr;} + + service_ptr_t & _as_base_ptr() { + PFC_ASSERT( _as_base_ptr_check() ); + return *reinterpret_cast*>(this); + } + static bool _as_base_ptr_check() { + return static_cast((T*)NULL) == reinterpret_cast((T*)NULL); + } +}; + +namespace pfc { + class traits_service_ptr : public traits_default { + public: + enum { realloc_safe = true, constructor_may_fail = false}; + }; + + template class traits_t > : public traits_service_ptr {}; + template class traits_t > : public traits_service_ptr {}; +} + + +template class t_alloc = pfc::alloc_fast> +class service_list_t : public pfc::list_t, t_alloc > +{ +}; + +//! Helper macro for use when defining a service class. Generates standard features of a service, without ability to register using service_factory / enumerate using service_enum_t. \n +//! This is used for declaring services that are meant to be instantiated by means other than service_enum_t (or non-entrypoint services), or extensions of services (including extension of entrypoint services). \n +//! Sample non-entrypoint declaration: class myclass : public service_base {...; FB2K_MAKE_SERVICE_INTERFACE(myclass, service_base); }; \n +//! Sample extension declaration: class myclass : public myotherclass {...; FB2K_MAKE_SERVICE_INTERFACE(myclass, myotherclass); }; \n +//! This macro is intended for use ONLY WITH INTERFACE CLASSES, not with implementation classes. +#define FB2K_MAKE_SERVICE_INTERFACE(THISCLASS,PARENTCLASS) \ + public: \ + typedef THISCLASS t_interface; \ + typedef PARENTCLASS t_interface_parent; \ + \ + static const GUID class_guid; \ + \ + virtual bool service_query(service_ptr_t & p_out,const GUID & p_guid) { \ + if (p_guid == class_guid) {p_out = this; return true;} \ + else return PARENTCLASS::service_query(p_out,p_guid); \ + } \ + typedef service_ptr_t ptr; \ + typedef service_nnptr_t nnptr; \ + typedef ptr ref; \ + typedef nnptr nnref; \ + protected: \ + THISCLASS() {} \ + ~THISCLASS() {} \ + private: \ + const THISCLASS & operator=(const THISCLASS &) {throw pfc::exception_not_implemented();} \ + THISCLASS(const THISCLASS &) {throw pfc::exception_not_implemented();} \ + private: \ + void __private__service_declaration_selftest() { \ + pfc::assert_same_type(); /*parentclass must be an interface*/ \ + __validate_service_class_helper(); /*service_base must be reachable by walking t_interface_parent*/ \ + pfc::implicit_cast(this); /*this class must derive from service_base, directly or indirectly, and be implictly castable to it*/ \ + } + +//! Helper macro for use when defining an entrypoint service class. Generates standard features of a service, including ability to register using service_factory and enumerate using service_enum. \n +//! Sample declaration: class myclass : public service_base {...; FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(myclass); }; \n +//! Note that entrypoint service classes must directly derive from service_base, and not from another service class. +//! This macro is intended for use ONLY WITH INTERFACE CLASSES, not with implementation classes. +#define FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(THISCLASS) \ + public: \ + typedef THISCLASS t_interface_entrypoint; \ + FB2K_MAKE_SERVICE_INTERFACE(THISCLASS,service_base) + + +#define FB2K_DECLARE_SERVICE_BEGIN(THISCLASS,BASECLASS) \ + class NOVTABLE THISCLASS : public BASECLASS { \ + FB2K_MAKE_SERVICE_INTERFACE(THISCLASS,BASECLASS); \ + public: + +#define FB2K_DECLARE_SERVICE_END() \ + }; + +#define FB2K_DECLARE_SERVICE_ENTRYPOINT_BEGIN(THISCLASS) \ + class NOVTABLE THISCLASS : public service_base { \ + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(THISCLASS) \ + public: + + +//! Base class for all service classes.\n +//! Provides interfaces for reference counter and querying for different interfaces supported by the object.\n +class NOVTABLE service_base +{ +public: + //! Decrements reference count; deletes the object if reference count reaches zero. This is normally not called directly but managed by service_ptr_t<> template. + //! @returns New reference count. For debug purposes only, in certain conditions return values may be unreliable. + virtual int service_release() throw() = 0; + //! Increments reference count. This is normally not called directly but managed by service_ptr_t<> template. + //! @returns New reference count. For debug purposes only, in certain conditions return values may be unreliable. + virtual int service_add_ref() throw() = 0; + //! Queries whether the object supports specific interface and retrieves a pointer to that interface. This is normally not called directly but managed by service_query_t<> function template. + //! Typical implementation checks the parameter against GUIDs of interfaces supported by this object, if the GUID is one of supported interfaces, p_out is set to service_base pointer that can be static_cast<>'ed to queried interface and the method returns true; otherwise the method returns false. + virtual bool service_query(service_ptr_t & p_out,const GUID & p_guid) {return false;} + + //! Queries whether the object supports specific interface and retrieves a pointer to that interface. + //! @param p_out Receives pointer to queried interface on success. + //! returns true on success, false on failure (interface not supported by the object). + template + bool service_query_t(service_ptr_t & p_out) + { + pfc::assert_same_type(); + return service_query( *reinterpret_cast*>(&p_out),T::class_guid); + } + //! New shortened version, same as service_query_t. + template + bool cast( outPtr_t & outPtr ) { return service_query_t( outPtr ); } + + typedef service_base t_interface; + +protected: + service_base() {} + ~service_base() {} +private: + service_base(const service_base&) {throw pfc::exception_not_implemented();} + const service_base & operator=(const service_base&) {throw pfc::exception_not_implemented();} +}; + +typedef service_ptr_t service_ptr; +typedef service_nnptr_t service_nnptr; + +template +inline void __validate_service_class_helper() { + __validate_service_class_helper(); +} + +template<> +inline void __validate_service_class_helper() {} + + +#include "service_impl.h" + +class NOVTABLE service_factory_base { +protected: + inline service_factory_base(const GUID & p_guid, service_factory_base * & factoryList) : m_guid(p_guid) {PFC_ASSERT(!core_api::are_services_available());__internal__next=factoryList;factoryList=this;} + inline ~service_factory_base() {PFC_ASSERT(!core_api::are_services_available());} +public: + inline const GUID & get_class_guid() const {return m_guid;} + + static service_class_ref enum_find_class(const GUID & p_guid); + static bool enum_create(service_ptr_t & p_out,service_class_ref p_class,t_size p_index); + static t_size enum_get_count(service_class_ref p_class); + + inline static bool is_service_present(const GUID & g) {return enum_get_count(enum_find_class(g))>0;} + + //! Throws std::bad_alloc or another exception on failure. + virtual void instance_create(service_ptr_t & p_out) = 0; + + //! FOR INTERNAL USE ONLY + static service_factory_base *__internal__list; + //! FOR INTERNAL USE ONLY + service_factory_base * __internal__next; +private: + const GUID & m_guid; +}; + +template +class service_factory_traits { +public: + static service_factory_base * & factory_list() {return service_factory_base::__internal__list;} +}; + +template +class service_factory_base_t : public service_factory_base { +public: + service_factory_base_t() : service_factory_base(B::class_guid, service_factory_traits::factory_list()) { + pfc::assert_same_type(); + } +}; + +template static void _validate_service_ptr(service_ptr_t const & ptr) { + PFC_ASSERT( ptr.is_valid() ); + service_ptr_t test; + PFC_ASSERT( ptr->service_query_t(test) ); +} + +#ifdef _DEBUG +#define FB2K_ASSERT_VALID_SERVICE_PTR(ptr) _validate_service_ptr(ptr) +#else +#define FB2K_ASSERT_VALID_SERVICE_PTR(ptr) +#endif + +template static bool service_enum_create_t(service_ptr_t & p_out,t_size p_index) { + pfc::assert_same_type(); + service_ptr_t ptr; + if (service_factory_base::enum_create(ptr,service_factory_base::enum_find_class(T::class_guid),p_index)) { + p_out = static_cast(ptr.get_ptr()); + return true; + } else { + p_out.release(); + return false; + } +} + +template static service_class_ref _service_find_class() { + pfc::assert_same_type(); + return service_factory_base::enum_find_class(T::class_guid); +} + +template +static bool _service_instantiate_helper(service_ptr_t & out, service_class_ref servClass, t_size index) { + /*if (out._as_base_ptr_check()) { + const bool state = service_factory_base::enum_create(out._as_base_ptr(), servClass, index); + if (state) { FB2K_ASSERT_VALID_SERVICE_PTR(out); } + return state; + } else */{ + service_ptr temp; + const bool state = service_factory_base::enum_create(temp, servClass, index); + if (state) { + out.attach( static_cast( temp.detach() ) ); + FB2K_ASSERT_VALID_SERVICE_PTR( out ); + } + return state; + } +} + +template class service_class_helper_t { +public: + service_class_helper_t() : m_class(service_factory_base::enum_find_class(T::class_guid)) { + pfc::assert_same_type(); + } + t_size get_count() const { + return service_factory_base::enum_get_count(m_class); + } + + bool create(service_ptr_t & p_out,t_size p_index) const { + return _service_instantiate_helper(p_out, m_class, p_index); + } + + service_ptr_t create(t_size p_index) const { + service_ptr_t temp; + if (!create(temp,p_index)) uBugCheck(); + return temp; + } + service_class_ref get_class() const {return m_class;} +private: + service_class_ref m_class; +}; + +void _standard_api_create_internal(service_ptr & out, const GUID & classID); + +template inline void standard_api_create_t(service_ptr_t & p_out) { + if (pfc::is_same_type::value) { + _standard_api_create_internal(p_out._as_base_ptr(), T::class_guid); + FB2K_ASSERT_VALID_SERVICE_PTR(p_out); + } else { + service_ptr_t temp; + standard_api_create_t(temp); + if (!temp->service_query_t(p_out)) throw exception_service_extension_not_found(); + } +} + +template inline void standard_api_create_t(T* & p_out) { + p_out = NULL; + standard_api_create_t( *reinterpret_cast< service_ptr_t * >( & p_out ) ); +} + +template inline service_ptr_t standard_api_create_t() { + service_ptr_t temp; + standard_api_create_t(temp); + return temp; +} + +template +inline bool static_api_test_t() { + typedef typename T::t_interface_entrypoint EP; + service_class_helper_t helper; + if (helper.get_count() != 1) return false; + if (!pfc::is_same_type::value) { + service_ptr_t t; + if (!helper.create(0)->service_query_t(t)) return false; + } + return true; +} + +#define FB2K_API_AVAILABLE(API) static_api_test_t() + +//! Helper template used to easily access core services. \n +//! Usage: static_api_ptr_t api; api->dosomething(); +//! Can be used at any point of code, WITH EXCEPTION of static objects that are initialized during the DLL loading process before the service system is initialized; such as static static_api_ptr_t objects or having static_api_ptr_t instances as members of statically created objects. +//! Throws exception_service_not_found if service could not be reached (which can be ignored for core APIs that are always present unless there is some kind of bug in the code). +template +class static_api_ptr_t { +private: + typedef static_api_ptr_t t_self; +public: + static_api_ptr_t() { + standard_api_create_t(m_ptr); + } + service_obscure_refcounting* operator->() const {return service_obscure_refcounting_cast(m_ptr);} + t_interface * get_ptr() const {return m_ptr;} + ~static_api_ptr_t() {m_ptr->service_release();} + + static_api_ptr_t(const t_self & in) { + m_ptr = in.m_ptr; m_ptr->service_add_ref(); + } + const t_self & operator=(const t_self & in) {return *this;} //obsolete, each instance should carry the same pointer +private: + t_interface * m_ptr; +}; + +//! Helper; simulates array with instance of each available implementation of given service class. +template class service_instance_array_t { +public: + typedef service_ptr_t t_ptr; + service_instance_array_t() { + service_class_helper_t helper; + const t_size count = helper.get_count(); + m_data.set_size(count); + for(t_size n=0;n m_data; +}; + +template +class service_enum_t { +public: + service_enum_t() : m_index(0) { + pfc::assert_same_type(); + } + void reset() {m_index = 0;} + + template + bool first(service_ptr_t & p_out) { + reset(); + return next(p_out); + } + + template + bool next(service_ptr_t & p_out) { + pfc::assert_same_type(); + if (pfc::is_same_type::value) { + return __next(reinterpret_cast&>(p_out)); + } else { + service_ptr_t temp; + while(__next(temp)) { + if (temp->service_query_t(p_out)) return true; + } + return false; + } + } + +private: + bool __next(service_ptr_t & p_out) { + return m_helper.create(p_out,m_index++); + } + unsigned m_index; + service_class_helper_t m_helper; +}; + + + +template +class service_factory_t : public service_factory_base_t { +public: + void instance_create(service_ptr_t & p_out) { + p_out = pfc::implicit_cast(pfc::implicit_cast(pfc::implicit_cast( new service_impl_t ))); + } +}; + + +template +class service_factory_single_t : public service_factory_base_t { + service_impl_single_t g_instance; +public: + TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(service_factory_single_t,g_instance) + + void instance_create(service_ptr_t & p_out) { + p_out = pfc::implicit_cast(pfc::implicit_cast(pfc::implicit_cast(&g_instance))); + } + + inline T& get_static_instance() {return g_instance;} + inline const T& get_static_instance() const {return g_instance;} +}; + +template +class service_factory_single_ref_t : public service_factory_base_t +{ +private: + T & instance; +public: + service_factory_single_ref_t(T& param) : instance(param) {} + + void instance_create(service_ptr_t & p_out) { + p_out = pfc::implicit_cast(pfc::implicit_cast(pfc::implicit_cast(&instance))); + } + + inline T& get_static_instance() {return instance;} +}; + + +template +class service_factory_single_transparent_t : public service_factory_base_t, public service_impl_single_t +{ +public: + TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(service_factory_single_transparent_t,service_impl_single_t) + + void instance_create(service_ptr_t & p_out) { + p_out = pfc::implicit_cast(pfc::implicit_cast(pfc::implicit_cast(this))); + } + + inline T& get_static_instance() {return *(T*)this;} +}; + + + + + + + + + + + + + + + +template +static bool service_by_guid_fallback(service_ptr_t & out, const GUID & id) { + service_enum_t e; + service_ptr_t ptr; + while(e.next(ptr)) { + if (ptr->get_guid() == id) {out = ptr; return true;} + } + return false; +} + +template +class service_by_guid_data { +public: + service_by_guid_data() : m_servClass(), m_inited() {} + + bool ready() const {return m_inited;} + + // Caller must ensure initialize call before create() as well as thread safety of initialize() calls. The rest of this class is thread safe (only reads member data). + void initialize() { + if (m_inited) return; + pfc::assert_same_type< what, typename what::t_interface_entrypoint >(); + m_servClass = service_factory_base::enum_find_class(what::class_guid); + const t_size servCount = service_factory_base::enum_get_count(m_servClass); + for(t_size walk = 0; walk < servCount; ++walk) { + service_ptr_t temp; + if (_service_instantiate_helper(temp, m_servClass, walk)) { + m_order.set(temp->get_guid(), walk); + } + } + m_inited = true; + } + + bool create(service_ptr_t & out, const GUID & theID) const { + PFC_ASSERT(m_inited); + t_size index; + if (!m_order.query(theID,index)) return false; + return _service_instantiate_helper(out, m_servClass, index); + } + service_ptr_t create(const GUID & theID) const { + service_ptr_t temp; if (!crete(temp,theID)) throw exception_service_not_found(); return temp; + } + +private: + volatile bool m_inited; + pfc::map_t m_order; + service_class_ref m_servClass; +}; + +template +class _service_by_guid_data_container { +public: + static service_by_guid_data data; +}; +template service_by_guid_data _service_by_guid_data_container::data; + + +template +static void service_by_guid_init() { + service_by_guid_data & data = _service_by_guid_data_container::data; + data.initialize(); +} +template +static bool service_by_guid(service_ptr_t & out, const GUID & theID) { + pfc::assert_same_type< what, typename what::t_interface_entrypoint >(); + service_by_guid_data & data = _service_by_guid_data_container::data; + if (data.ready()) { + //fall-thru + } else if (core_api::is_main_thread()) { + data.initialize(); + } else { +#ifdef _DEBUG + FB2K_DebugLog() << "Warning: service_by_guid() used in non-main thread without initialization, using fallback"; +#endif + return service_by_guid_fallback(out,theID); + } + return data.create(out,theID); +} +template +static service_ptr_t service_by_guid(const GUID & theID) { + service_ptr_t temp; + if (!service_by_guid(temp,theID)) throw exception_service_not_found(); + return temp; +} + +#define FB2K_FOR_EACH_SERVICE(type, call) {service_enum_t e; service_ptr_t ptr; while(e.next(ptr)) {ptr->call;} } + + + +class comparator_service_guid { +public: + template static int compare(const what & v1, const what & v2) { return pfc::compare_t(v1->get_guid(), v2->get_guid()); } +}; + + +#endif //_foobar2000_sdk_service_h_included_ diff --git a/SDK/foobar2000/SDK/service_impl.h b/SDK/foobar2000/SDK/service_impl.h new file mode 100644 index 0000000..33a193d --- /dev/null +++ b/SDK/foobar2000/SDK/service_impl.h @@ -0,0 +1,57 @@ +//! Template implementing reference-counting features of service_base. Intended for dynamic instantiation: "new service_impl_t(param1,param2);"; should not be instantiated otherwise (no local/static/member objects) because it does a "delete this;" when reference count reaches zero.\n +//! Note that some constructor parameters such as NULL will need explicit typecasts to ensure correctly guessed types for constructor function template (null string needs to be (const char*)NULL rather than just NULL, etc). +template +class service_impl_t : public T +{ +public: + int service_release() throw() { + int ret = (int) --m_counter; + if (ret == 0) { + PFC_ASSERT_NO_EXCEPTION( delete this ); + } + return ret; + } + int service_add_ref() throw() {return (int) ++m_counter;} + + TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(service_impl_t,T) +private: + pfc::refcounter m_counter; +}; + +//! Alternate version of service_impl_t<> - calls this->service_shutdown() instead of delete this. \n +//! For special cases where selfdestruct on zero refcount is undesired. +template +class service_impl_explicitshutdown_t : public class_t { +public: + int service_release() throw() { + int ret = --m_counter; + if (ret == 0) { + this->service_shutdown(); + } else { + return ret; + } + } + int service_add_ref() throw() {return ++m_counter;} + + TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(service_impl_explicitshutdown_t,class_t) +private: + pfc::refcounter m_counter; +}; + +//! Template implementing dummy version of reference-counting features of service_base. Intended for static/local/member instantiation: "static service_impl_single_t myvar(params);". Because reference counting features are disabled (dummy reference counter), code instantiating it is responsible for deleting it as well as ensuring that no references are active when the object gets deleted.\n +//! Note that some constructor parameters such as NULL will need explicit typecasts to ensure correctly guessed types for constructor function template (null string needs to be (const char*)NULL rather than just NULL, etc). +template +class service_impl_single_t : public T +{ +public: + int service_release() throw() {return 1;} + int service_add_ref() throw() {return 1;} + + TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(service_impl_single_t,T) +}; + + +namespace service_impl_helper { + void release_object_delayed(service_ptr obj); +}; + diff --git a/SDK/foobar2000/SDK/shortcut_actions.h b/SDK/foobar2000/SDK/shortcut_actions.h new file mode 100644 index 0000000..5c671dd --- /dev/null +++ b/SDK/foobar2000/SDK/shortcut_actions.h @@ -0,0 +1 @@ +#error DEPRECATED diff --git a/SDK/foobar2000/SDK/stdafx.cpp b/SDK/foobar2000/SDK/stdafx.cpp new file mode 100644 index 0000000..145fc30 --- /dev/null +++ b/SDK/foobar2000/SDK/stdafx.cpp @@ -0,0 +1,2 @@ +//cpp used to generate precompiled header +#include "foobar2000.h" \ No newline at end of file diff --git a/SDK/foobar2000/SDK/system_time_keeper.h b/SDK/foobar2000/SDK/system_time_keeper.h new file mode 100644 index 0000000..87ab7ca --- /dev/null +++ b/SDK/foobar2000/SDK/system_time_keeper.h @@ -0,0 +1,47 @@ +namespace system_time_periods { + static const t_filetimestamp second = filetimestamp_1second_increment; + static const t_filetimestamp minute = second * 60; + static const t_filetimestamp hour = minute * 60; + static const t_filetimestamp day = hour * 24; + static const t_filetimestamp week = day * 7; +}; +class system_time_callback { +public: + virtual void on_time_changed(t_filetimestamp newVal) = 0; +}; +//! \since 0.9.6 +class system_time_keeper : public service_base { +public: + //! The callback object receives an on_changed() call with the current time inside the register_callback() call. + virtual void register_callback(system_time_callback * callback, t_filetimestamp resolution) = 0; + + virtual void unregister_callback(system_time_callback * callback) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(system_time_keeper) +}; + +class system_time_callback_impl : public system_time_callback { +public: + system_time_callback_impl() : m_registered() {} + ~system_time_callback_impl() {stop_timer();} + + void stop_timer() { + if (m_registered) { + static_api_ptr_t()->unregister_callback(this); + m_registered = false; + } + } + //! You get a on_changed() call inside the initialize_timer() call. + void initialize_timer(t_filetimestamp period) { + stop_timer(); + static_api_ptr_t()->register_callback(this, period); + m_registered = true; + } + + void on_time_changed(t_filetimestamp newVal) {} + + PFC_CLASS_NOT_COPYABLE_EX(system_time_callback_impl) +private: + bool m_registered; +}; + diff --git a/SDK/foobar2000/SDK/tag_processor.cpp b/SDK/foobar2000/SDK/tag_processor.cpp new file mode 100644 index 0000000..6136975 --- /dev/null +++ b/SDK/foobar2000/SDK/tag_processor.cpp @@ -0,0 +1,172 @@ +#include "foobar2000.h" + +void tag_processor_trailing::write_id3v1(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort) +{ + write(p_file,p_info,flag_id3v1,p_abort); +} + +void tag_processor_trailing::write_apev2(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort) +{ + write(p_file,p_info,flag_apev2,p_abort); +} + +void tag_processor_trailing::write_apev2_id3v1(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort) +{ + write(p_file,p_info,flag_id3v1|flag_apev2,p_abort); +} + + + + +enum { + g_flag_id3v1 = 1<<0, + g_flag_id3v2 = 1<<1, + g_flag_apev2 = 1<<2 +}; + +static void tagtype_list_append(pfc::string_base & p_out,const char * p_name) +{ + if (!p_out.is_empty()) p_out += "|"; + p_out += p_name; +} + +static void g_write_tags_ex(tag_write_callback & p_callback,unsigned p_flags,const service_ptr_t & p_file,const file_info * p_info,abort_callback & p_abort) { + PFC_ASSERT( p_flags == 0 || p_info != 0 ); + + + if (p_flags & (g_flag_id3v1 | g_flag_apev2)) { + switch(p_flags & (g_flag_id3v1 | g_flag_apev2)) { + case g_flag_id3v1 | g_flag_apev2: + static_api_ptr_t()->write_apev2_id3v1(p_file,*p_info,p_abort); + break; + case g_flag_id3v1: + static_api_ptr_t()->write_id3v1(p_file,*p_info,p_abort); + break; + case g_flag_apev2: + static_api_ptr_t()->write_apev2(p_file,*p_info,p_abort); + break; + default: + throw exception_io_data(); + } + } else { + static_api_ptr_t()->remove(p_file,p_abort); + } + + if (p_flags & g_flag_id3v2) + { + static_api_ptr_t()->write_ex(p_callback,p_file,*p_info,p_abort); + } + else + { + t_uint64 dummy; + tag_processor_id3v2::g_remove_ex(p_callback,p_file,dummy,p_abort); + } +} + +static void g_write_tags(unsigned p_flags,const service_ptr_t & p_file,const file_info * p_info,abort_callback & p_abort) { + tag_write_callback_dummy cb; + g_write_tags_ex(cb,p_flags,p_file,p_info,p_abort); +} + + +void tag_processor::write_multi(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort,bool p_write_id3v1,bool p_write_id3v2,bool p_write_apev2) { + unsigned flags = 0; + if (p_write_id3v1) flags |= g_flag_id3v1; + if (p_write_id3v2) flags |= g_flag_id3v2; + if (p_write_apev2) flags |= g_flag_apev2; + g_write_tags(flags,p_file,&p_info,p_abort); +} + +void tag_processor::write_multi_ex(tag_write_callback & p_callback,const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort,bool p_write_id3v1,bool p_write_id3v2,bool p_write_apev2) { + unsigned flags = 0; + if (p_write_id3v1) flags |= g_flag_id3v1; + if (p_write_id3v2) flags |= g_flag_id3v2; + if (p_write_apev2) flags |= g_flag_apev2; + g_write_tags_ex(p_callback,flags,p_file,&p_info,p_abort); +} + +void tag_processor::write_id3v1(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort) { + g_write_tags(g_flag_id3v1,p_file,&p_info,p_abort); +} + +void tag_processor::write_apev2(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort) { + g_write_tags(g_flag_apev2,p_file,&p_info,p_abort); +} + +void tag_processor::write_apev2_id3v1(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort) { + g_write_tags(g_flag_apev2|g_flag_id3v1,p_file,&p_info,p_abort); +} + +void tag_processor::write_id3v2(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort) { + g_write_tags(g_flag_id3v2,p_file,&p_info,p_abort); +} + +void tag_processor::write_id3v2_id3v1(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort) { + g_write_tags(g_flag_id3v2|g_flag_id3v1,p_file,&p_info,p_abort); +} + +void tag_processor::remove_trailing(const service_ptr_t & p_file,abort_callback & p_abort) { + return static_api_ptr_t()->remove(p_file,p_abort); +} + +bool tag_processor::remove_id3v2(const service_ptr_t & p_file,abort_callback & p_abort) { + t_uint64 dummy = 0; + tag_processor_id3v2::g_remove(p_file,dummy,p_abort); + return dummy > 0; +} + +void tag_processor::remove_id3v2_trailing(const service_ptr_t & p_file,abort_callback & p_abort) { + remove_id3v2(p_file,p_abort); + remove_trailing(p_file,p_abort); +} + +void tag_processor::read_trailing(const service_ptr_t & p_file,file_info & p_info,abort_callback & p_abort) { + static_api_ptr_t()->read(p_file,p_info,p_abort); +} + +void tag_processor::read_trailing_ex(const service_ptr_t & p_file,file_info & p_info,t_uint64 & p_tagoffset,abort_callback & p_abort) { + static_api_ptr_t()->read_ex(p_file,p_info,p_tagoffset,p_abort); +} + +void tag_processor::read_id3v2(const service_ptr_t & p_file,file_info & p_info,abort_callback & p_abort) { + static_api_ptr_t()->read(p_file,p_info,p_abort); +} + +void tag_processor::read_id3v2_trailing(const service_ptr_t & p_file,file_info & p_info,abort_callback & p_abort) +{ + file_info_impl id3v2, trailing; + bool have_id3v2 = true, have_trailing = true; + try { + read_id3v2(p_file,id3v2,p_abort); + } catch(exception_io_data) { + have_id3v2 = false; + } + if (!have_id3v2 || !p_file->is_remote()) try { + read_trailing(p_file,trailing,p_abort); + } catch(exception_io_data) { + have_trailing = false; + } + + if (!have_id3v2 && !have_trailing) throw exception_tag_not_found(); + + if (have_id3v2) { + p_info._set_tag(id3v2); + if (have_trailing) p_info._add_tag(trailing); + } else { + p_info._set_tag(trailing); + } +} + +void tag_processor::skip_id3v2(const service_ptr_t & p_file,t_uint64 & p_size_skipped,abort_callback & p_abort) { + tag_processor_id3v2::g_skip(p_file,p_size_skipped,p_abort); +} + +bool tag_processor::is_id3v1_sufficient(const file_info & p_info) +{ + return static_api_ptr_t()->is_id3v1_sufficient(p_info); +} + +void tag_processor::truncate_to_id3v1(file_info & p_info) +{ + static_api_ptr_t()->truncate_to_id3v1(p_info); +} \ No newline at end of file diff --git a/SDK/foobar2000/SDK/tag_processor.h b/SDK/foobar2000/SDK/tag_processor.h new file mode 100644 index 0000000..77d8212 --- /dev/null +++ b/SDK/foobar2000/SDK/tag_processor.h @@ -0,0 +1,101 @@ +PFC_DECLARE_EXCEPTION(exception_tag_not_found,exception_io_data,"Tag not found"); + +//! Callback interface for write-tags-to-temp-file-and-swap scheme, used for ID3v2 tag updates and such where entire file needs to be rewritten. +//! As a speed optimization, file content can be copied to a temporary file in the same directory as the file being updated, and then source file can be swapped for the newly created file with updated tags. +//! This also gives better security against data loss on crash compared to rewriting the file in place and using memory or generic temporary file APIs to store content being rewritten. +class NOVTABLE tag_write_callback { +public: + //! Called only once per operation (or not called at all when operation being performed can be done in-place). + //! Requests a temporary file to be created in the same directory + virtual bool open_temp_file(service_ptr_t & p_out,abort_callback & p_abort) = 0; +protected: + tag_write_callback() {} + ~tag_write_callback() {} +private: + tag_write_callback(const tag_write_callback &) {throw pfc::exception_not_implemented();} + const tag_write_callback & operator=(const tag_write_callback &) {throw pfc::exception_not_implemented();} +}; + +class tag_write_callback_dummy : public tag_write_callback { +public: + bool open_temp_file(service_ptr_t & p_out,abort_callback & p_abort) {return false;} +}; + +//! For internal use - call tag_processor namespace methods instead. +class NOVTABLE tag_processor_id3v2 : public service_base +{ +public: + virtual void read(const service_ptr_t & p_file,file_info & p_info,abort_callback & p_abort) = 0; + virtual void write(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort) = 0; + virtual void write_ex(tag_write_callback & p_callback,const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort) = 0; + + static bool g_get(service_ptr_t & p_out); + static void g_skip(const service_ptr_t & p_file,t_filesize & p_size_skipped,abort_callback & p_abort); + static void g_skip_at(const service_ptr_t & p_file,t_filesize p_base, t_filesize & p_size_skipped,abort_callback & p_abort); + static t_size g_multiskip(const service_ptr_t & p_file,t_filesize & p_size_skipped,abort_callback & p_abort); + static void g_remove(const service_ptr_t & p_file,t_filesize & p_size_removed,abort_callback & p_abort); + static void g_remove_ex(tag_write_callback & p_callback,const service_ptr_t & p_file,t_filesize & p_size_removed,abort_callback & p_abort); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(tag_processor_id3v2); +}; + +//! For internal use - call tag_processor namespace methods instead. +class NOVTABLE tag_processor_trailing : public service_base +{ +public: + enum { + flag_apev2 = 1, + flag_id3v1 = 2, + }; + + virtual void read(const service_ptr_t & p_file,file_info & p_info,abort_callback & p_abort) = 0; + virtual void write(const service_ptr_t & p_file,const file_info & p_info,unsigned p_flags,abort_callback & p_abort) = 0; + virtual void remove(const service_ptr_t & p_file,abort_callback & p_abort) = 0; + virtual bool is_id3v1_sufficient(const file_info & p_info) = 0; + virtual void truncate_to_id3v1(file_info & p_info) = 0; + virtual void read_ex(const service_ptr_t & p_file,file_info & p_info,t_filesize & p_tagoffset,abort_callback & p_abort) = 0; + + void write_id3v1(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort); + void write_apev2(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort); + void write_apev2_id3v1(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort); + + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(tag_processor_trailing); +}; + +namespace tag_processor { + //! Strips all recognized tags from the file and writes an ID3v1 tag with specified info. + void write_id3v1(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort); + //! Strips all recognized tags from the file and writes an APEv2 tag with specified info. + void write_apev2(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort); + //! Strips all recognized tags from the file and writes ID3v1+APEv2 tags with specified info. + void write_apev2_id3v1(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort); + //! Strips all recognized tags from the file and writes an ID3v2 tag with specified info. + void write_id3v2(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort); + //! Strips all recognized tags from the file and writes ID3v1+ID3v2 tags with specified info. + void write_id3v2_id3v1(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort); + //! Strips all recognized tags from the file and writes new tags with specified info according to parameters. + void write_multi(const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort,bool p_write_id3v1,bool p_write_id3v2,bool p_write_apev2); + //! Strips all recognized tags from the file and writes new tags with specified info according to parameters. Extended to allow write-tags-to-temp-file-and-swap scheme. + void write_multi_ex(tag_write_callback & p_callback,const service_ptr_t & p_file,const file_info & p_info,abort_callback & p_abort,bool p_write_id3v1,bool p_write_id3v2,bool p_write_apev2); + //! Removes trailing tags from the file. + void remove_trailing(const service_ptr_t & p_file,abort_callback & p_abort); + //! Removes ID3v2 tags from the file. Returns true when a tag was removed, false when the file was not altered. + bool remove_id3v2(const service_ptr_t & p_file,abort_callback & p_abort); + //! Removes ID3v2 and trailing tags from specified file (not to be confused with trailing ID3v2 which are not yet supported). + void remove_id3v2_trailing(const service_ptr_t & p_file,abort_callback & p_abort); + //! Reads trailing tags from the file. + void read_trailing(const service_ptr_t & p_file,file_info & p_info,abort_callback & p_abort); + //! Reads trailing tags from the file. Extended version, returns offset at which parsed tags start. + void read_trailing_ex(const service_ptr_t & p_file,file_info & p_info,t_filesize & p_tagoffset,abort_callback & p_abort); + //! Reads ID3v2 tags from specified file. + void read_id3v2(const service_ptr_t & p_file,file_info & p_info,abort_callback & p_abort); + //! Reads ID3v2 and trailing tags from specified file (not to be confused with trailing ID3v2 which are not yet supported). + void read_id3v2_trailing(const service_ptr_t & p_file,file_info & p_info,abort_callback & p_abort); + + void skip_id3v2(const service_ptr_t & p_file,t_filesize & p_size_skipped,abort_callback & p_abort); + + bool is_id3v1_sufficient(const file_info & p_info); + void truncate_to_id3v1(file_info & p_info); + +}; diff --git a/SDK/foobar2000/SDK/tag_processor_id3v2.cpp b/SDK/foobar2000/SDK/tag_processor_id3v2.cpp new file mode 100644 index 0000000..d76b00e --- /dev/null +++ b/SDK/foobar2000/SDK/tag_processor_id3v2.cpp @@ -0,0 +1,106 @@ +#include "foobar2000.h" + +bool tag_processor_id3v2::g_get(service_ptr_t & p_out) +{ + return service_enum_t().first(p_out); +} + +void tag_processor_id3v2::g_remove(const service_ptr_t & p_file,t_uint64 & p_size_removed,abort_callback & p_abort) { + tag_write_callback_dummy cb; + g_remove_ex(cb,p_file,p_size_removed,p_abort); +} + +void tag_processor_id3v2::g_remove_ex(tag_write_callback & p_callback,const service_ptr_t & p_file,t_uint64 & p_size_removed,abort_callback & p_abort) +{ + p_file->ensure_seekable(); + + t_filesize len; + + len = p_file->get_size(p_abort); + + if (len == filesize_invalid) throw exception_io_no_length(); + + p_file->seek(0,p_abort); + + t_uint64 offset; + g_multiskip(p_file,offset,p_abort); + + if (offset>0 && offset temp; + if (p_callback.open_temp_file(temp,p_abort)) { + file::g_transfer_object(p_file,temp,len,p_abort); + } else { + if (len > 16*1024*1024) filesystem::g_open_temp(temp,p_abort); + else filesystem::g_open_tempmem(temp,p_abort); + file::g_transfer_object(p_file,temp,len,p_abort); + p_file->seek(0,p_abort); + p_file->set_eof(p_abort); + temp->seek(0,p_abort); + file::g_transfer_object(temp,p_file,len,p_abort); + } + } + p_size_removed = offset; +} + +t_size tag_processor_id3v2::g_multiskip(const service_ptr_t & p_file,t_filesize & p_size_skipped,abort_callback & p_abort) { + t_filesize offset = 0; + t_size count = 0; + for(;;) { + t_filesize delta; + g_skip_at(p_file, offset, delta, p_abort); + if (delta == 0) break; + offset += delta; + ++count; + } + p_size_skipped = offset; + return count; +} +void tag_processor_id3v2::g_skip(const service_ptr_t & p_file,t_uint64 & p_size_skipped,abort_callback & p_abort) { + g_skip_at(p_file, 0, p_size_skipped, p_abort); +} + +void tag_processor_id3v2::g_skip_at(const service_ptr_t & p_file,t_filesize p_base, t_filesize & p_size_skipped,abort_callback & p_abort) { + + unsigned char tmp[10]; + + p_file->seek ( p_base, p_abort ); + + if (p_file->read( tmp, sizeof(tmp), p_abort) != sizeof(tmp)) { + p_file->seek ( p_base, p_abort ); + p_size_skipped = 0; + return; + } + + if ( + 0 != memcmp ( tmp, "ID3", 3) || + ( tmp[5] & 0x0F ) != 0 || + ((tmp[6] | tmp[7] | tmp[8] | tmp[9]) & 0x80) != 0 + ) { + p_file->seek ( p_base, p_abort ); + p_size_skipped = 0; + return; + } + + int FooterPresent = tmp[5] & 0x10; + + t_uint32 ret; + ret = tmp[6] << 21; + ret += tmp[7] << 14; + ret += tmp[8] << 7; + ret += tmp[9] ; + ret += 10; + if ( FooterPresent ) ret += 10; + + try { + p_file->seek ( p_base + ret, p_abort ); + } catch(exception_io_seek_out_of_range) { + p_file->seek( p_base, p_abort ); + p_size_skipped = 0; + return; + } + + p_size_skipped = ret; + +} diff --git a/SDK/foobar2000/SDK/threaded_process.cpp b/SDK/foobar2000/SDK/threaded_process.cpp new file mode 100644 index 0000000..532c4ab --- /dev/null +++ b/SDK/foobar2000/SDK/threaded_process.cpp @@ -0,0 +1,46 @@ +#include "foobar2000.h" + +void threaded_process_status::set_progress(t_size p_state,t_size p_max) +{ + set_progress( progress_min + MulDiv_Size(p_state,progress_max-progress_min,p_max) ); +} + +void threaded_process_status::set_progress_secondary(t_size p_state,t_size p_max) +{ + set_progress_secondary( progress_min + MulDiv_Size(p_state,progress_max-progress_min,p_max) ); +} + +void threaded_process_status::set_progress_float(double p_state) +{ + if (p_state < 0.0) set_progress(progress_min); + else if (p_state < 1.0) set_progress( progress_min + (t_size)(p_state * (progress_max - progress_min))); + else set_progress(progress_max); +} + +void threaded_process_status::set_progress_secondary_float(double p_state) +{ + if (p_state < 0.0) set_progress_secondary(progress_min); + else if (p_state < 1.0) set_progress_secondary( progress_min + (t_size)(p_state * (progress_max - progress_min))); + else set_progress_secondary(progress_max); +} + + +bool threaded_process::g_run_modal(service_ptr_t p_callback,unsigned p_flags,HWND p_parent,const char * p_title,t_size p_title_len) +{ + return static_api_ptr_t()->run_modal(p_callback,p_flags,p_parent,p_title,p_title_len); +} + +bool threaded_process::g_run_modeless(service_ptr_t p_callback,unsigned p_flags,HWND p_parent,const char * p_title,t_size p_title_len) +{ + return static_api_ptr_t()->run_modeless(p_callback,p_flags,p_parent,p_title,p_title_len); +} + +bool threaded_process::g_query_preventStandby() { + static const GUID guid_preventStandby = { 0x7aafeffb, 0x5f11, 0x483f, { 0xac, 0x65, 0x61, 0xec, 0x9c, 0x70, 0x37, 0x4e } }; + advconfig_entry_checkbox::ptr obj; + if (advconfig_entry::g_find_t(obj, guid_preventStandby)) { + return obj->get_state(); + } else { + return false; + } +} diff --git a/SDK/foobar2000/SDK/threaded_process.h b/SDK/foobar2000/SDK/threaded_process.h new file mode 100644 index 0000000..00d8bd9 --- /dev/null +++ b/SDK/foobar2000/SDK/threaded_process.h @@ -0,0 +1,119 @@ +//! Callback class passed to your threaded_process client code; allows you to give various visual feedback to the user. +class NOVTABLE threaded_process_status { +public: + enum {progress_min = 0, progress_max = 5000}; + + //! Sets the primary progress bar state; scale from progress_min to progress_max. + virtual void set_progress(t_size p_state) = 0; + //! Sets the secondary progress bar state; scale from progress_min to progress_max. + virtual void set_progress_secondary(t_size p_state) = 0; + //! Sets the currently progressed item label. When working with files, you should use set_file_path() instead. + virtual void set_item(const char * p_item,t_size p_item_len = ~0) = 0; + //! Sets the currently progressed item label; treats the label as a file path. + virtual void set_item_path(const char * p_item,t_size p_item_len = ~0) = 0; + //! Sets the title of the dialog. You normally don't need this function unless you want to override the title you set when initializing the threaded_process. + virtual void set_title(const char * p_title,t_size p_title_len = ~0) = 0; + //! Should not be used. + virtual void force_update() = 0; + //! Returns whether the process is paused. + virtual bool is_paused() = 0; + + //! Checks if process is paused and sleeps if needed; returns false when process should be aborted, true on success. \n + //! You should use poll_pause() instead of calling this directly. + virtual bool process_pause() = 0; + + //! Automatically sleeps if the process is paused. + void poll_pause() {if (!process_pause()) throw exception_aborted();} + + //! Helper; sets primary progress with a custom scale. + void set_progress(t_size p_state,t_size p_max); + //! Helper; sets secondary progress with a custom scale. + void set_progress_secondary(t_size p_state,t_size p_max); + //! Helper; sets primary progress with a float 0..1 scale. + void set_progress_float(double p_state); + //! Helper; sets secondary progress with a float 0..1 scale. + void set_progress_secondary_float(double p_state); +protected: + threaded_process_status() {} + ~threaded_process_status() {} +}; + +//! Callback class for the threaded_process API. You must implement this to create your own threaded_process client. +class NOVTABLE threaded_process_callback : public service_base { +public: + //! Called from the main thread before spawning the worker thread. \n + //! Note that you should not access the window handle passed to on_init() in the worker thread later on. + virtual void on_init(HWND p_wnd) {} + //! Called from the worker thread. Do all the hard work here. + virtual void run(threaded_process_status & p_status,abort_callback & p_abort) = 0; + //! Called after the worker thread has finished executing. + virtual void on_done(HWND p_wnd,bool p_was_aborted) {} + + FB2K_MAKE_SERVICE_INTERFACE(threaded_process_callback,service_base); +}; + + +//! The threaded_process API allows you to easily put timeconsuming tasks in worker threads, with progress dialog giving nice feedback to the user. \n +//! Thanks to this API you can perform such tasks with no user interface related programming at all. +class NOVTABLE threaded_process : public service_base { +public: + enum { + //! Shows the "abort" button. + flag_show_abort = 1, + //! Obsolete, do not use. + flag_show_minimize = 1 << 1, + //! Shows a progress bar. + flag_show_progress = 1 << 2, + //! Shows dual progress bars; implies flag_show_progress. + flag_show_progress_dual = 1 << 3, + //! Shows the item being currently processed. + flag_show_item = 1 << 4, + //! Shows the "pause" button. + flag_show_pause = 1 << 5, + //! Obsolete, do not use. + flag_high_priority = 1 << 6, + //! Make the dialog hidden by default and show it only if the operation could not be completed after 500ms. Implies flag_no_focus. Relevant only to modeless dialogs. + flag_show_delayed = 1 << 7, + //! Do not focus the dialog by default. + flag_no_focus = 1 << 8, + }; + + //! Runs a synchronous threaded_process operation - the function does not return until the operation has completed, though the app UI is not frozen and the operation is abortable. \n + //! This API is obsolete and should not be used. Please use run_modeless() instead if possible. + //! @param p_callback Interface to your threaded_process client. + //! @param p_flags Flags describing requested dialog functionality. See threaded_process::flag_* constants. + //! @param p_parent Parent window for the progress dialog - typically core_api::get_main_window(). + //! @param p_title Initial title of the dialog. + //! @returns True if the operation has completed normally, false if the user has aborted the operation. In case of a catastrophic failure such as dialog creation failure, exceptions will be thrown. + virtual bool run_modal(service_ptr_t p_callback,unsigned p_flags,HWND p_parent,const char * p_title,t_size p_title_len = ~0) = 0; + //! Runs an asynchronous threaded_process operation. + //! @param p_callback Interface to your threaded_process client. + //! @param p_flags Flags describing requested dialog functionality. See threaded_process::flag_* constants. + //! @param p_parent Parent window for the progress dialog - typically core_api::get_main_window(). + //! @param p_title Initial title of the dialog. + //! @returns True, always; the return value should be ignored. In case of a catastrophic failure such as dialog creation failure, exceptions will be thrown. + virtual bool run_modeless(service_ptr_t p_callback,unsigned p_flags,HWND p_parent,const char * p_title,t_size p_title_len = ~0) = 0; + + + //! Helper invoking run_modal(). + static bool g_run_modal(service_ptr_t p_callback,unsigned p_flags,HWND p_parent,const char * p_title,t_size p_title_len = ~0); + //! Helper invoking run_modeless(). + static bool g_run_modeless(service_ptr_t p_callback,unsigned p_flags,HWND p_parent,const char * p_title,t_size p_title_len = ~0); + + //! Queries user settings; returns whether various timeconsuming tasks should be blocking machine standby. + static bool g_query_preventStandby(); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(threaded_process); +}; + + +//! Helper - forward threaded_process_callback calls to a service object that for whatever reason cannot publish threaded_process_callback API by itself. +template class threaded_process_callback_redir : public threaded_process_callback { +public: + threaded_process_callback_redir(TTarget * target) : m_target(target) {} + void on_init(HWND p_wnd) {m_target->tpc_on_init(p_wnd);} + void run(threaded_process_status & p_status,abort_callback & p_abort) {m_target->tpc_run(p_status, p_abort);} + void on_done(HWND p_wnd,bool p_was_aborted) {m_target->tpc_on_done(p_wnd, p_was_aborted); } +private: + const service_ptr_t m_target; +}; diff --git a/SDK/foobar2000/SDK/titleformat.cpp b/SDK/foobar2000/SDK/titleformat.cpp new file mode 100644 index 0000000..974d672 --- /dev/null +++ b/SDK/foobar2000/SDK/titleformat.cpp @@ -0,0 +1,189 @@ +#include "foobar2000.h" + + +#define tf_profiler(x) // profiler(x) + +void titleformat_compiler::remove_color_marks(const char * src,pfc::string_base & out)//helper +{ + out.reset(); + while(*src) + { + if (*src==3) + { + src++; + while(*src && *src!=3) src++; + if (*src==3) src++; + } + else out.add_byte(*src++); + } +} + +static bool test_for_bad_char(const char * source,t_size source_char_len,const char * reserved) +{ + return pfc::strstr_ex(reserved,(t_size)(-1),source,source_char_len) != (t_size)(-1); +} + +void titleformat_compiler::remove_forbidden_chars(titleformat_text_out * p_out,const GUID & p_inputtype,const char * p_source,t_size p_source_len,const char * p_reserved_chars) +{ + if (p_reserved_chars == 0 || *p_reserved_chars == 0) + { + p_out->write(p_inputtype,p_source,p_source_len); + } + else + { + p_source_len = pfc::strlen_max(p_source,p_source_len); + t_size index = 0; + t_size good_byte_count = 0; + while(index < p_source_len) + { + t_size delta = pfc::utf8_char_len(p_source + index,p_source_len - index); + if (delta == 0) break; + if (test_for_bad_char(p_source+index,delta,p_reserved_chars)) + { + if (good_byte_count > 0) {p_out->write(p_inputtype,p_source+index-good_byte_count,good_byte_count);good_byte_count=0;} + p_out->write(p_inputtype,"_",1); + } + else + { + good_byte_count += delta; + } + index += delta; + } + if (good_byte_count > 0) {p_out->write(p_inputtype,p_source+index-good_byte_count,good_byte_count);good_byte_count=0;} + } +} + +void titleformat_compiler::remove_forbidden_chars_string_append(pfc::string_receiver & p_out,const char * p_source,t_size p_source_len,const char * p_reserved_chars) +{ + remove_forbidden_chars(&titleformat_text_out_impl_string(p_out),pfc::guid_null,p_source,p_source_len,p_reserved_chars); +} + +void titleformat_compiler::remove_forbidden_chars_string(pfc::string_base & p_out,const char * p_source,t_size p_source_len,const char * p_reserved_chars) +{ + p_out.reset(); + remove_forbidden_chars_string_append(p_out,p_source,p_source_len,p_reserved_chars); +} + +bool titleformat_hook_impl_file_info::process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag) { + return m_api->process_field(*m_info,m_location,p_out,p_name,p_name_length,p_found_flag); +} +bool titleformat_hook_impl_file_info::process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag) { + return m_api->process_function(*m_info,m_location,p_out,p_name,p_name_length,p_params,p_found_flag); +} + +void titleformat_object::run_hook(const playable_location & p_location,const file_info * p_source,titleformat_hook * p_hook,pfc::string_base & p_out,titleformat_text_filter * p_filter) +{ + if (p_hook) + { + run( + &titleformat_hook_impl_splitter( + p_hook, + &titleformat_hook_impl_file_info(p_location,p_source) + ), + p_out,p_filter); + } + else + { + run( + &titleformat_hook_impl_file_info(p_location,p_source), + p_out,p_filter); + } +} + +void titleformat_object::run_simple(const playable_location & p_location,const file_info * p_source,pfc::string_base & p_out) +{ + run(&titleformat_hook_impl_file_info(p_location,p_source),p_out,NULL); +} + +t_size titleformat_hook_function_params::get_param_uint(t_size index) +{ + const char * str; + t_size str_len; + get_param(index,str,str_len); + return pfc::atoui_ex(str,str_len); +} + + +void titleformat_text_out_impl_filter_chars::write(const GUID & p_inputtype,const char * p_data,t_size p_data_length) +{ + titleformat_compiler::remove_forbidden_chars(m_chain,p_inputtype,p_data,p_data_length,m_restricted_chars); +} + +bool titleformat_hook_impl_splitter::process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag) +{ + p_found_flag = false; + if (m_hook1 && m_hook1->process_field(p_out,p_name,p_name_length,p_found_flag)) return true; + p_found_flag = false; + if (m_hook2 && m_hook2->process_field(p_out,p_name,p_name_length,p_found_flag)) return true; + p_found_flag = false; + return false; +} + +bool titleformat_hook_impl_splitter::process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag) +{ + p_found_flag = false; + if (m_hook1 && m_hook1->process_function(p_out,p_name,p_name_length,p_params,p_found_flag)) return true; + p_found_flag = false; + if (m_hook2 && m_hook2->process_function(p_out,p_name,p_name_length,p_params,p_found_flag)) return true; + p_found_flag = false; + return false; +} + +void titleformat_text_out::write_int_padded(const GUID & p_inputtype,t_int64 val,t_int64 maxval) +{ + unsigned width = 0; + while(maxval > 0) {maxval/=10;width++;} + write(p_inputtype,pfc::format_int(val,width)); +} + +void titleformat_text_out::write_int(const GUID & p_inputtype,t_int64 val) +{ + write(p_inputtype,pfc::format_int(val)); +} +void titleformat_text_filter_impl_reserved_chars::write(const GUID & p_inputtype,pfc::string_receiver & p_out,const char * p_data,t_size p_data_length) +{ + if (p_inputtype == titleformat_inputtypes::meta) titleformat_compiler::remove_forbidden_chars_string_append(p_out,p_data,p_data_length,m_reserved_chars); + else p_out.add_string(p_data,p_data_length); +} + +void titleformat_compiler::run(titleformat_hook * p_source,pfc::string_base & p_out,const char * p_spec) +{ + service_ptr_t ptr; + if (!compile(ptr,p_spec)) p_out = "[COMPILATION ERROR]"; + else ptr->run(p_source,p_out,NULL); +} + +void titleformat_compiler::compile_safe(service_ptr_t & p_out,const char * p_spec) +{ + if (!compile(p_out,p_spec)) { + compile_force(p_out,"%filename%"); + } +} + + +namespace titleformat_inputtypes { + const GUID meta = { 0xcd839c8e, 0x5c66, 0x4ae1, { 0x8d, 0xad, 0x71, 0x1f, 0x86, 0x0, 0xa, 0xe3 } }; + const GUID unknown = { 0x673aa1cd, 0xa7a8, 0x40c8, { 0xbf, 0x9b, 0x34, 0x37, 0x99, 0x29, 0x16, 0x3b } }; +}; + +void titleformat_text_filter_impl_filename_chars::write(const GUID & p_inputType,pfc::string_receiver & p_out,const char * p_data,t_size p_dataLength) { + if (p_inputType == titleformat_inputtypes::meta) { + //slightly inefficient... + p_out.add_string( pfc::io::path::replaceIllegalNameChars(pfc::string(p_data,p_dataLength)).ptr()); + } else p_out.add_string(p_data,p_dataLength); +} + +void titleformat_compiler::compile_safe_ex(titleformat_object::ptr & p_out,const char * p_spec,const char * p_fallback) { + if (!compile(p_out,p_spec)) compile_force(p_out,p_fallback); +} + + +void titleformat_text_filter_nontext_chars::write(const GUID & p_inputtype,pfc::string_receiver & p_out,const char * p_data,t_size p_data_length) { + for(t_size walk = 0;;) { + t_size base = walk; + while(walk < p_data_length && !isReserved(p_data[walk]) && p_data[walk] != 0) walk++; + p_out.add_string(p_data+base,walk-base); + if (walk >= p_data_length || p_data[walk] == 0) break; + p_out.add_byte('_'); walk++; + } +} diff --git a/SDK/foobar2000/SDK/titleformat.h b/SDK/foobar2000/SDK/titleformat.h new file mode 100644 index 0000000..d698b0b --- /dev/null +++ b/SDK/foobar2000/SDK/titleformat.h @@ -0,0 +1,227 @@ +namespace titleformat_inputtypes { + extern const GUID meta, unknown; +}; + +class NOVTABLE titleformat_text_out { +public: + virtual void write(const GUID & p_inputtype,const char * p_data,t_size p_data_length = ~0) = 0; + void write_int(const GUID & p_inputtype,t_int64 val); + void write_int_padded(const GUID & p_inputtype,t_int64 val,t_int64 maxval); +protected: + titleformat_text_out() {} + ~titleformat_text_out() {} +}; + + +class NOVTABLE titleformat_text_filter { +public: + virtual void write(const GUID & p_inputtype,pfc::string_receiver & p_out,const char * p_data,t_size p_data_length) = 0; +protected: + titleformat_text_filter() {} + ~titleformat_text_filter() {} +}; + +class NOVTABLE titleformat_hook_function_params +{ +public: + virtual t_size get_param_count() = 0; + virtual void get_param(t_size index,const char * & p_string,t_size & p_string_len) = 0;//warning: not a null-terminated string + + //helper + t_size get_param_uint(t_size index); +}; + +class NOVTABLE titleformat_hook +{ +public: + virtual bool process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag) = 0; + virtual bool process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag) = 0; +}; +//! Represents precompiled executable title-formatting script. Use titleformat_compiler to instantiate; do not reimplement. +class NOVTABLE titleformat_object : public service_base +{ +public: + virtual void run(titleformat_hook * p_source,pfc::string_base & p_out,titleformat_text_filter * p_filter)=0; + + void run_hook(const playable_location & p_location,const file_info * p_source,titleformat_hook * p_hook,pfc::string_base & p_out,titleformat_text_filter * p_filter); + void run_simple(const playable_location & p_location,const file_info * p_source,pfc::string_base & p_out); + + FB2K_MAKE_SERVICE_INTERFACE(titleformat_object,service_base); +}; + +//! Standard service for instantiating titleformat_object. Implemented by the core; do not reimplement. +//! To instantiate, use static_api_ptr_t. +class NOVTABLE titleformat_compiler : public service_base +{ +public: + //! Returns false in case of a compilation error. + virtual bool compile(titleformat_object::ptr & p_out,const char * p_spec) = 0; + //! Helper; + void run(titleformat_hook * p_source,pfc::string_base & p_out,const char * p_spec); + //! Should never fail, falls back to %filename% in case of failure. + void compile_safe(titleformat_object::ptr & p_out,const char * p_spec); + + //! Falls back to p_fallback in case of failure. + void compile_safe_ex(titleformat_object::ptr & p_out,const char * p_spec,const char * p_fallback = ""); + + //! Throws a bug check exception when script can't be compiled. For use with hardcoded scripts only. + void compile_force(titleformat_object::ptr & p_out,const char * p_spec) {if (!compile(p_out,p_spec)) uBugCheck();} + + + static void remove_color_marks(const char * src,pfc::string_base & out);//helper + static void remove_forbidden_chars(titleformat_text_out * p_out,const GUID & p_inputtype,const char * p_source,t_size p_source_len,const char * p_forbidden_chars); + static void remove_forbidden_chars_string_append(pfc::string_receiver & p_out,const char * p_source,t_size p_source_len,const char * p_forbidden_chars); + static void remove_forbidden_chars_string(pfc::string_base & p_out,const char * p_source,t_size p_source_len,const char * p_forbidden_chars); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(titleformat_compiler); +}; + + +class titleformat_object_wrapper { +public: + titleformat_object_wrapper(const char * p_script) { + static_api_ptr_t()->compile_force(m_script,p_script); + } + + operator const service_ptr_t &() const {return m_script;} + +private: + service_ptr_t m_script; +}; + + +//helpers + + +class titleformat_text_out_impl_filter_chars : public titleformat_text_out +{ +public: + inline titleformat_text_out_impl_filter_chars(titleformat_text_out * p_chain,const char * p_restricted_chars) + : m_chain(p_chain), m_restricted_chars(p_restricted_chars) {} + void write(const GUID & p_inputtype,const char * p_data,t_size p_data_length); +private: + titleformat_text_out * m_chain; + const char * m_restricted_chars; +}; + +class titleformat_text_out_impl_string : public titleformat_text_out { +public: + titleformat_text_out_impl_string(pfc::string_receiver & p_string) : m_string(p_string) {} + void write(const GUID & p_inputtype,const char * p_data,t_size p_data_length) {m_string.add_string(p_data,p_data_length);} +private: + pfc::string_receiver & m_string; +}; + +class titleformat_common_methods : public service_base { +public: + virtual bool process_field(const file_info & p_info,const playable_location & p_location,titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag) = 0; + virtual bool process_function(const file_info & p_info,const playable_location & p_location,titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag) = 0; + virtual bool remap_meta(const file_info & p_info,t_size & p_index, const char * p_name, t_size p_name_length) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(titleformat_common_methods); +}; + +class titleformat_hook_impl_file_info : public titleformat_hook +{ +public: + titleformat_hook_impl_file_info(const playable_location & p_location,const file_info * p_info) : m_location(p_location), m_info(p_info) {}//caller must ensure that referenced file_info object is alive as long as the titleformat_hook_impl_file_info instance + bool process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag); + bool process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag); +protected: + bool remap_meta(t_size & p_index, const char * p_name, t_size p_name_length) {return m_api->remap_meta(*m_info,p_index,p_name,p_name_length);} + const file_info * m_info; +private: + const playable_location & m_location; + static_api_ptr_t m_api; +}; + +class titleformat_hook_impl_splitter : public titleformat_hook { +public: + inline titleformat_hook_impl_splitter(titleformat_hook * p_hook1,titleformat_hook * p_hook2) : m_hook1(p_hook1), m_hook2(p_hook2) {} + bool process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag); + bool process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag); +private: + titleformat_hook * m_hook1, * m_hook2; +}; + +class titleformat_text_filter_impl_reserved_chars : public titleformat_text_filter { +public: + titleformat_text_filter_impl_reserved_chars(const char * p_reserved_chars) : m_reserved_chars(p_reserved_chars) {} + virtual void write(const GUID & p_inputtype,pfc::string_receiver & p_out,const char * p_data,t_size p_data_length); +private: + const char * m_reserved_chars; +}; + +class titleformat_text_filter_impl_filename_chars : public titleformat_text_filter { +public: + void write(const GUID & p_inputType,pfc::string_receiver & p_out,const char * p_data,t_size p_dataLength); +}; + +class titleformat_text_filter_nontext_chars : public titleformat_text_filter { +public: + inline static bool isReserved(char c) { return c >= 0 && c < 0x20; } + void write(const GUID & p_inputtype,pfc::string_receiver & p_out,const char * p_data,t_size p_data_length); +}; + + + + + + + +class titleformat_hook_impl_list : public titleformat_hook { +public: + titleformat_hook_impl_list(t_size p_index /* zero-based! */,t_size p_total) : m_index(p_index), m_total(p_total) {} + + bool process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag) { + if ( + pfc::stricmp_ascii_ex(p_name,p_name_length,"list_index",~0) == 0 + ) { + p_out->write_int_padded(titleformat_inputtypes::unknown,m_index+1, m_total); + p_found_flag = true; return true; + } else if ( + pfc::stricmp_ascii_ex(p_name,p_name_length,"list_total",~0) == 0 + ) { + p_out->write_int(titleformat_inputtypes::unknown,m_total); + p_found_flag = true; return true; + } else { + p_found_flag = false; return false; + } + } + + bool process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag) {return false;} + +private: + t_size m_index, m_total; +}; + +class string_formatter_tf : public pfc::string_base { +public: + string_formatter_tf(titleformat_text_out * out, const GUID & inputType = titleformat_inputtypes::meta) : m_out(out), m_inputType(inputType) {} + + const char * get_ptr() const { + uBugCheck(); + } + void add_string(const char * p_string,t_size p_length) { + m_out->write(m_inputType,p_string,p_length); + } + void set_string(const char * p_string,t_size p_length) { + uBugCheck(); + } + void truncate(t_size len) { + uBugCheck(); + } + t_size get_length() const { + uBugCheck(); + } + char * lock_buffer(t_size p_requested_length) { + uBugCheck(); + } + void unlock_buffer() { + uBugCheck(); + } + +private: + titleformat_text_out * const m_out; + const GUID m_inputType; +}; diff --git a/SDK/foobar2000/SDK/track_property.h b/SDK/foobar2000/SDK/track_property.h new file mode 100644 index 0000000..18fc4f8 --- /dev/null +++ b/SDK/foobar2000/SDK/track_property.h @@ -0,0 +1,77 @@ +//! Callback interface for track_property_provider::enumerate_properties(). +class NOVTABLE track_property_callback { +public: + //! Sets a property list entry to display. Called by track_property_provider::enumerate_properties() implementation. + //! @param p_group Name of group to put the entry in, case-sensitive. Note that non-standard groups are sorted alphabetically. + //! @param p_sortpriority Sort priority of the property inside its group (smaller value means earlier in the list), pass 0 if you don't care (alphabetic order by name used when more than one item has same priority). + //! @param p_name Name of the property. + //! @param p_value Value of the property. + virtual void set_property(const char * p_group,double p_sortpriority,const char * p_name,const char * p_value) = 0; +protected: + track_property_callback const & operator=(track_property_callback const &) {return *this;} + ~track_property_callback() {} +}; + +class NOVTABLE track_property_callback_v2 : public track_property_callback { +public: + virtual bool is_group_wanted(const char * p_group) = 0; +protected: + ~track_property_callback_v2() {} +}; + +//! Service for adding custom entries in "Properties" tab of the properties dialog. +class NOVTABLE track_property_provider : public service_base { +public: + //! Enumerates properties of specified track list. + //! @param p_tracks List of tracks to enumerate properties on. + //! @param p_out Callback interface receiving enumerated properties. + virtual void enumerate_properties(metadb_handle_list_cref p_tracks, track_property_callback & p_out) = 0; + //! Returns whether specified tech info filed is processed by our service and should not be displayed among unknown fields. + //! @param p_name Name of tech info field being queried. + //! @returns True if the field is among fields processed by this track_property_provider implementation and should not be displayed among unknown fields, false otherwise. + virtual bool is_our_tech_info(const char * p_name) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(track_property_provider); +}; + +class NOVTABLE track_property_provider_v2 : public track_property_provider { + FB2K_MAKE_SERVICE_INTERFACE(track_property_provider_v2,track_property_provider) +public: + virtual void enumerate_properties_v2(metadb_handle_list_cref p_tracks, track_property_callback_v2 & p_out) = 0; +}; + +class NOVTABLE track_property_provider_v3_info_source { +public: + virtual metadb_info_container::ptr get_info(size_t index) = 0; +}; + +class track_property_provider_v3_info_source_impl : public track_property_provider_v3_info_source { +public: + track_property_provider_v3_info_source_impl(metadb_handle_list_cref items) : m_items(items) {} + metadb_info_container::ptr get_info(size_t index) {return m_items[index]->get_info_ref();} +private: + metadb_handle_list_cref m_items; +}; + +class track_property_callback_v2_proxy : public track_property_callback_v2 { +public: + track_property_callback_v2_proxy(track_property_callback & callback) : m_callback(callback) {} + void set_property(const char * p_group,double p_sortpriority,const char * p_name,const char * p_value) {m_callback.set_property(p_group, p_sortpriority, p_name, p_value);} + bool is_group_wanted(const char*) {return true;} + +private: + track_property_callback & m_callback; +}; + +//! \since 1.3 +class NOVTABLE track_property_provider_v3 : public track_property_provider_v2 { + FB2K_MAKE_SERVICE_INTERFACE(track_property_provider_v3,track_property_provider_v2) +public: + virtual void enumerate_properties_v3(metadb_handle_list_cref items, track_property_provider_v3_info_source & info, track_property_callback_v2 & callback) = 0; + + void enumerate_properties(metadb_handle_list_cref p_tracks, track_property_callback & p_out) {track_property_provider_v3_info_source_impl src(p_tracks); track_property_callback_v2_proxy cb(p_out); enumerate_properties_v3(p_tracks, src, cb);} + void enumerate_properties_v2(metadb_handle_list_cref p_tracks, track_property_callback_v2 & p_out) {track_property_provider_v3_info_source_impl src(p_tracks); enumerate_properties_v3(p_tracks, src, p_out);} +}; + +template +class track_property_provider_factory_t : public service_factory_single_t {}; diff --git a/SDK/foobar2000/SDK/ui.cpp b/SDK/foobar2000/SDK/ui.cpp new file mode 100644 index 0000000..f5283a7 --- /dev/null +++ b/SDK/foobar2000/SDK/ui.cpp @@ -0,0 +1,35 @@ +#include "foobar2000.h" + +bool ui_drop_item_callback::g_on_drop(interface IDataObject * pDataObject) +{ + service_enum_t e; + service_ptr_t ptr; + if (e.first(ptr)) do { + if (ptr->on_drop(pDataObject)) return true; + } while(e.next(ptr)); + return false; +} + +bool ui_drop_item_callback::g_is_accepted_type(interface IDataObject * pDataObject, DWORD * p_effect) +{ + service_enum_t e; + service_ptr_t ptr; + if (e.first(ptr)) do { + if (ptr->is_accepted_type(pDataObject,p_effect)) return true; + } while(e.next(ptr)); + return false; +} + +bool user_interface::g_find(service_ptr_t & p_out,const GUID & p_guid) +{ + service_enum_t e; + service_ptr_t ptr; + if (e.first(ptr)) do { + if (ptr->get_guid() == p_guid) + { + p_out = ptr; + return true; + } + } while(e.next(ptr)); + return false; +} diff --git a/SDK/foobar2000/SDK/ui.h b/SDK/foobar2000/SDK/ui.h new file mode 100644 index 0000000..349fa64 --- /dev/null +++ b/SDK/foobar2000/SDK/ui.h @@ -0,0 +1,228 @@ +#ifndef _WINDOWS +#error PORTME +#endif + +//! Entrypoint service for user interface modules. Implement when registering an UI module. Do not call existing implementations; only core enumerates / dispatches calls. To control UI behaviors from other components, use ui_control API. \n +//! Use user_interface_factory_t<> to register, e.g static user_interface_factory_t g_myclass_factory; +class NOVTABLE user_interface : public service_base { +public: + //!HookProc usage: \n + //! in your windowproc, call HookProc first, and if it returns true, return LRESULT value it passed to you + typedef BOOL (WINAPI * HookProc_t)(HWND wnd,UINT msg,WPARAM wp,LPARAM lp,LRESULT * ret); + + //! Retrieves name (UTF-8 null-terminated string) of the UI module. + virtual const char * get_name()=0; + //! Initializes the UI module - creates the main app window, etc. Failure should be signaled by appropriate exception (std::exception or a derivative). + virtual HWND init(HookProc_t hook)=0; + //! Deinitializes the UI module - destroys the main app window, etc. + virtual void shutdown()=0; + //! Activates main app window. + virtual void activate()=0; + //! Minimizes/hides main app window. + virtual void hide()=0; + //! Returns whether main window is visible / not minimized. Used for activate/hide command. + virtual bool is_visible() = 0; + //! Retrieves GUID of your implementation, to be stored in configuration file etc. + virtual GUID get_guid() = 0; + + //! Overrides statusbar text with specified string. The parameter is a null terminated UTF-8 string. The override is valid until another override_statusbar_text() call or revert_statusbar_text() call. + virtual void override_statusbar_text(const char * p_text) = 0; + //! Disables statusbar text override. + virtual void revert_statusbar_text() = 0; + + //! Shows now-playing item somehow (e.g. system notification area popup). + virtual void show_now_playing() = 0; + + static bool g_find(service_ptr_t & p_out,const GUID & p_guid); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(user_interface); +}; + +template +class user_interface_factory : public service_factory_single_t {}; + +//! Interface class allowing you to override UI statusbar text. There may be multiple callers trying to override statusbar text; backend decides which one succeeds so you will not always get what you want. Statusbar text override is automatically cancelled when the object is released.\n +//! Use ui_control::override_status_text_create() to instantiate. +//! Implemented by core. Do not reimplement. +class NOVTABLE ui_status_text_override : public service_base +{ +public: + //! Sets statusbar text to specified UTF-8 null-terminated string. + virtual void override_text(const char * p_message) = 0; + //! Cancels statusbar text override. + virtual void revert_text() = 0; + + FB2K_MAKE_SERVICE_INTERFACE(ui_status_text_override,service_base); +}; + +//! Serivce providing various UI-related commands. Implemented by core; do not reimplement. +//! Instantiation: use static_api_ptr_t. +class NOVTABLE ui_control : public service_base { +public: + //! Returns whether primary UI is visible/unminimized. + virtual bool is_visible()=0; + //! Activates/unminimizes main UI. + virtual void activate()=0; + //! Hides/minimizese main UI. + virtual void hide()=0; + //! Retrieves main GUI icon, to use as window icon etc. Returned handle does not need to be freed. + virtual HICON get_main_icon()=0; + //! Loads main GUI icon, version with specified width/height. Returned handle needs to be freed with DestroyIcon when you are done using it. + virtual HICON load_main_icon(unsigned width,unsigned height) = 0; + + //! Activates preferences dialog and navigates to specified page. See also: preference_page API. + virtual void show_preferences(const GUID & p_page) = 0; + + //! Instantiates ui_status_text_override service, that can be used to display status messages. + //! @param p_out receives new ui_status_text_override instance. + //! @returns true on success, false on failure (out of memory / no GUI loaded / etc) + virtual bool override_status_text_create(service_ptr_t & p_out) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(ui_control); +}; + +//! Service called from the UI when some object is dropped into the UI. Usable for modifying drag&drop behaviors such as adding custom handlers for object types other than supported media files.\n +//! Implement where needed; use ui_drop_item_callback_factory_t<> template to register, e.g. static ui_drop_item_callback_factory_t g_myclass_factory. +class NOVTABLE ui_drop_item_callback : public service_base { +public: + //! Called when an object was dropped; returns true if the object was processed and false if not. + virtual bool on_drop(interface IDataObject * pDataObject) = 0; + //! Tests whether specified object type is supported by this ui_drop_item_callback implementation. Returns true and sets p_effect when it's supported; returns false otherwise. \n + //! See IDropTarget::DragEnter() documentation for more information about p_effect values. + virtual bool is_accepted_type(interface IDataObject * pDataObject, DWORD * p_effect)=0; + + //! Static helper, calls all existing implementations appropriately. See on_drop(). + static bool g_on_drop(interface IDataObject * pDataObject); + //! Static helper, calls all existing implementations appropriately. See is_accepted_type(). + static bool g_is_accepted_type(interface IDataObject * pDataObject, DWORD * p_effect); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(ui_drop_item_callback); +}; + +template +class ui_drop_item_callback_factory_t : public service_factory_single_t {}; + + +class ui_selection_callback; + +//! Write interface and reference counter for the shared selection. +//! The ui_selection_manager stores the selected items as a list. +//! The ui_selection_holder service allows components to modify this list. +//! It also serves as a reference count: the ui_selection_manager clears the stored +//! selection when no component holds a reference to a ui_selection_holder. +//! +//! When a window that uses the shared selection gets the focus, it should acquire +//! a ui_selection_holder from the ui_selection_manager. If it contains selectable items, +//! it should use the appropriate method to store its selected items as the shared selection. +//! If it just wants to preserve the selection - for example so it can display it - it should +//! merely store the acquired ui_selection_holder. +//! +//! When the window loses the focus, it should release its ui_selection_holder. +//! It should not use a set method to clear the selection +class NOVTABLE ui_selection_holder : public service_base { +public: + //! Sets selected items. + virtual void set_selection(metadb_handle_list_cref data) = 0; + //! Sets selected items to playlist selection and enables tracking. + //! When the playlist selection changes, the stored selection is automatically updated. + //! Tracking ends when a set method is called on any ui_selection_holder or when + //! the last reference to this ui_selection_holder is released. + virtual void set_playlist_selection_tracking() = 0; + //! Sets selected items to the contents of the active playlist and enables tracking. + //! When the active playlist or its contents changes, the stored selection is automatically updated. + //! Tracking ends when a set method is called on any ui_selection_holder or when + //! the last reference to this ui_selection_holder is released. + virtual void set_playlist_tracking() = 0; + + //! Sets selected items and type of selection holder. + //! @param type Specifies type of selection. Values same as contextmenu_item caller IDs. + virtual void set_selection_ex(metadb_handle_list_cref data, const GUID & type) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(ui_selection_holder,service_base); +}; + +class NOVTABLE ui_selection_manager : public service_base { +public: + //! Retrieves the current selection. + virtual void get_selection(metadb_handle_list_ref p_selection) = 0; + //! Registers a callback. It is recommended to use ui_selection_callback_impl_base class instead of calling this directly. + virtual void register_callback(ui_selection_callback * p_callback) = 0; + //! Unregisters a callback. It is recommended to use ui_selection_callback_impl_base class instead of calling this directly. + virtual void unregister_callback(ui_selection_callback * p_callback) = 0; + + virtual ui_selection_holder::ptr acquire() = 0; + + //! Retrieves type of the active selection holder. Values same as contextmenu_item caller IDs. + virtual GUID get_selection_type() = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(ui_selection_manager); +}; + +//! \since 1.0 +class NOVTABLE ui_selection_manager_v2 : public ui_selection_manager { + FB2K_MAKE_SERVICE_INTERFACE(ui_selection_manager_v2, ui_selection_manager) +public: + enum { flag_no_now_playing = 1 }; + virtual void get_selection(metadb_handle_list_ref out, t_uint32 flags) = 0; + virtual GUID get_selection_type(t_uint32 flags) = 0; + virtual void register_callback(ui_selection_callback * callback, t_uint32 flags) = 0; +}; + +class ui_selection_callback { +public: + virtual void on_selection_changed(metadb_handle_list_cref p_selection) = 0; +protected: + ui_selection_callback() {} + ~ui_selection_callback() {} +}; + +//! ui_selection_callback implementation helper with autoregistration - do not instantiate statically +class ui_selection_callback_impl_base : public ui_selection_callback { +protected: + ui_selection_callback_impl_base(bool activate = true) : m_active() {ui_selection_callback_activate(activate);} + ~ui_selection_callback_impl_base() {ui_selection_callback_activate(false);} + + void ui_selection_callback_activate(bool state = true) { + if (state != m_active) { + m_active = state; + static_api_ptr_t api; + if (state) api->register_callback(this); + else api->unregister_callback(this); + } + } + + //avoid pure virtual function calls in rare cases - provide a dummy implementation + void on_selection_changed(metadb_handle_list_cref p_selection) {} + + PFC_CLASS_NOT_COPYABLE_EX(ui_selection_callback_impl_base); +private: + bool m_active; +}; + +//! \since 1.0 +//! ui_selection_callback implementation helper with autoregistration - do not instantiate statically +template +class ui_selection_callback_impl_base_ex : public ui_selection_callback { +protected: + enum { + ui_selection_flags = flags + }; + ui_selection_callback_impl_base_ex(bool activate = true) : m_active() {ui_selection_callback_activate(activate);} + ~ui_selection_callback_impl_base_ex() {ui_selection_callback_activate(false);} + + void ui_selection_callback_activate(bool state = true) { + if (state != m_active) { + m_active = state; + static_api_ptr_t api; + if (state) api->register_callback(this, flags); + else api->unregister_callback(this); + } + } + + //avoid pure virtual function calls in rare cases - provide a dummy implementation + void on_selection_changed(metadb_handle_list_cref p_selection) {} + + PFC_CLASS_NOT_COPYABLE(ui_selection_callback_impl_base_ex, ui_selection_callback_impl_base_ex); +private: + bool m_active; +}; diff --git a/SDK/foobar2000/SDK/ui_edit_context.h b/SDK/foobar2000/SDK/ui_edit_context.h new file mode 100644 index 0000000..a7e5fc9 --- /dev/null +++ b/SDK/foobar2000/SDK/ui_edit_context.h @@ -0,0 +1,128 @@ + +class NOVTABLE ui_edit_context : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(ui_edit_context, service_base) +public: + //! Called by core only. + virtual void initialize() = 0; + //! Called by core only. \n + //! WARNING: you may get other methods called after shutdown() in case someone using ui_edit_context_manager has kept a reference to your service - for an example during an async operation. You should behave sanely in such case - either execute the operation if still possible or fail cleanly. + virtual void shutdown() = 0; + + enum { + flag_removable = 1, + flag_reorderable = 2, + flag_undoable = 4, + flag_redoable = 8, + flag_linearlist = 16, + flag_searchable = 32, + flag_insertable = 64, + }; + + virtual t_uint32 get_flags() = 0; + + bool can_remove() {return (get_flags() & flag_removable) != 0;} + bool test_flags(t_uint32 flags) {return (get_flags() & flags) == flags;} + bool can_remove_mask() {return test_flags(flag_removable | flag_linearlist);} + bool can_reorder() {return test_flags(flag_reorderable);} + bool can_search() {return test_flags(flag_searchable);} + + virtual void select_all() {update_selection(bit_array_true(), bit_array_true());} + virtual void select_none() {update_selection(bit_array_true(), bit_array_false());} + virtual void get_selected_items(metadb_handle_list_ref out) {bit_array_bittable mask(get_item_count()); get_selection_mask(mask); get_items(out, mask);} + virtual void remove_selection() {bit_array_bittable mask(get_item_count()); get_selection_mask(mask); remove_items(mask);} + virtual void crop_selection() {bit_array_bittable mask(get_item_count()); get_selection_mask(mask); remove_items(bit_array_not(mask));} + virtual void clear() {remove_items(bit_array_true());} + virtual void get_all_items(metadb_handle_list_ref out) {get_items(out, bit_array_true());} + virtual GUID get_selection_type() = 0; + + // available if flag_linearlist is set + virtual void get_selection_mask(pfc::bit_array_var & out) { + const t_size count = get_item_count(); for(t_size walk = 0; walk < count; ++walk) out.set(walk, is_item_selected(walk)); + } + virtual void update_selection(const pfc::bit_array & mask, const pfc::bit_array & newVals) = 0; + virtual t_size get_item_count(t_size max = ~0) = 0; + virtual metadb_handle_ptr get_item(t_size index) = 0; + virtual void get_items(metadb_handle_list_ref out, pfc::bit_array const & mask) = 0; + virtual bool is_item_selected(t_size item) = 0; + virtual void remove_items(pfc::bit_array const & mask) = 0; + virtual void reorder_items(const t_size * order, t_size count) = 0; + virtual t_size get_selection_count(t_size max = ~0) { + t_size count = 0; + const t_size total = get_item_count(); + for(t_size walk = 0; walk < total && count < max; ++walk) if (is_item_selected(walk)) ++count; + return count; + } + + virtual void search() = 0; + + virtual void undo_backup() = 0; + virtual void undo_restore() = 0; + virtual void redo_restore() = 0; + + virtual void insert_items(t_size at, metadb_handle_list_cref items, pfc::bit_array const & selection) = 0; + + virtual t_size query_insert_mark() = 0; + + void sort_by_format(const char * spec, bool onlySelection) { + const t_size count = get_item_count(); + pfc::array_t order; order.set_size(count); + pfc::array_t sel_map; + if (onlySelection) { + sel_map.set_size(count); + t_size sel_count = 0; + for(t_size n=0;n order_temp; + if (onlySelection) { + get_selected_items(temp); + order_temp.set_size(count); + } else { + get_all_items(temp); + } + + + if (spec != NULL) { + temp.sort_by_format_get_order(onlySelection ? order_temp.get_ptr() : order.get_ptr(),spec,0); + } else { + static_api_ptr_t api; api->seed((unsigned)__rdtsc()); + api->generate_random_order(onlySelection ? order_temp.get_ptr() : order.get_ptr(),temp.get_count()); + } + + if (onlySelection) { + t_size n,ptr; + for(n=0,ptr=0;n(buffer),size); + } + + void * get_data_var() {return m_content.get_ptr();} + void set_data_size(t_size size) {m_content.set_size(size);} + + GUID get_guid() const {return m_guid;} + const void * get_data() const {return m_content.get_ptr();} + t_size get_data_size() const {return m_content.get_size();} + private: + const GUID m_guid; + pfc::array_t m_content; + }; + +} + +service_ptr_t ui_element_config::g_create(const GUID& id, const void * data, t_size size) { + return new service_impl_t(id,data,size); +} + +service_ptr_t ui_element_config::g_create(const GUID & id, stream_reader * in, t_size bytes, abort_callback & abort) { + service_ptr_t data = new service_impl_t(id); + data->set_data_size(bytes); + in->read_object(data->get_data_var(),bytes,abort); + return data; +} + +service_ptr_t ui_element_config::g_create(stream_reader * in, t_size bytes, abort_callback & abort) { + if (bytes < sizeof(GUID)) throw exception_io_data_truncation(); + GUID id; stream_reader_formatter<>(*in,abort) >> id; + return g_create(id,in,bytes - sizeof(GUID),abort); +} + +ui_element_config::ptr ui_element_config_parser::subelement(t_size size) { + return ui_element_config::g_create(&m_stream, size, m_abort); +} +ui_element_config::ptr ui_element_config_parser::subelement(const GUID & id, t_size dataSize) { + return ui_element_config::g_create(id, &m_stream, dataSize, m_abort); +} + +service_ptr_t ui_element_config::g_create(const void * data, t_size size) { + stream_reader_memblock_ref stream(data,size); + return g_create(&stream,size,abort_callback_dummy()); +} + +bool ui_element_subclass_description(const GUID & id, pfc::string_base & p_out) { + if (id == ui_element_subclass_playlist_renderers) { + p_out = "Playlist Renderers"; return true; + } else if (id == ui_element_subclass_media_library_viewers) { + p_out = "Media Library Viewers"; return true; + } else if (id == ui_element_subclass_selection_information) { + p_out = "Selection Information"; return true; + } else if (id == ui_element_subclass_playback_visualisation) { + p_out = "Playback Visualization"; return true; + } else if (id == ui_element_subclass_playback_information) { + p_out = "Playback Information"; return true; + } else if (id == ui_element_subclass_utility) { + p_out = "Utility"; return true; + } else if (id == ui_element_subclass_containers) { + p_out = "Containers"; return true; + } else { + return false; + } +} + +bool ui_element::get_element_group(pfc::string_base & p_out) { + return ui_element_subclass_description(get_subclass(),p_out); +} + +t_ui_color ui_element_instance_callback::query_std_color(const GUID & p_what) { +#ifdef _WIN32 + t_ui_color ret; + if (query_color(p_what,ret)) return ret; + int idx = ui_color_to_sys_color_index(p_what); + if (idx < 0) return 0;//should not be triggerable + return GetSysColor(idx); +#else +#error portme +#endif +} + +bool ui_element::g_find(service_ptr_t & out, const GUID & id) { + return service_by_guid(out, id); +} + +bool ui_element::g_get_name(pfc::string_base & p_out,const GUID & p_guid) { + ui_element::ptr ptr; if (!g_find(ptr,p_guid)) return false; + ptr->get_name(p_out); return true; +} + +bool ui_element_instance_callback::is_elem_visible_(service_ptr_t elem) { + ui_element_instance_callback_v2::ptr v2; + if (!this->service_query_t(v2)) { + PFC_ASSERT(!"Should not get here - somebody implemented ui_element_instance_callback but not ui_element_instance_callback_v2."); + return true; + } + return v2->is_elem_visible(elem); +} + +bool ui_element_instance_callback::set_elem_label(ui_element_instance * source, const char * label) { + return notify_(source, ui_element_host_notify_set_elem_label, 0, label, strlen(label)) != 0; +} + +t_uint32 ui_element_instance_callback::get_dialog_texture(ui_element_instance * source) { + return (t_uint32) notify_(source, ui_element_host_notify_get_dialog_texture, 0, NULL, 0); +} + +bool ui_element_instance_callback::is_border_needed(ui_element_instance * source) { + return notify_(source, ui_element_host_notify_is_border_needed, 0, NULL, 0) != 0; +} + +t_size ui_element_instance_callback::notify_(ui_element_instance * source, const GUID & what, t_size param1, const void * param2, t_size param2size) { + ui_element_instance_callback_v3::ptr v3; + if (!this->service_query_t(v3)) { PFC_ASSERT(!"Outdated UI Element host implementation"); return 0; } + return v3->notify(source, what, param1, param2, param2size); +} diff --git a/SDK/foobar2000/SDK/ui_element.h b/SDK/foobar2000/SDK/ui_element.h new file mode 100644 index 0000000..c97be75 --- /dev/null +++ b/SDK/foobar2000/SDK/ui_element.h @@ -0,0 +1,618 @@ +//! Configuration of a UI element. +class NOVTABLE ui_element_config : public service_base { +public: + //! Returns GUID of the UI element this configuration data belongs to. + virtual GUID get_guid() const = 0; + //! Returns raw configuration data pointer. + virtual const void * get_data() const = 0; + //! Returns raw configuration data size, in bytes. + virtual t_size get_data_size() const = 0; + + + //! Helper. + static service_ptr_t g_create(const GUID& id, const void * data, t_size size); + + template static service_ptr_t g_create(const GUID& id, t_source const & data) { + pfc::assert_byte_type(); + return g_create(id, data.get_ptr(), data.get_size()); + } + + static service_ptr_t g_create_empty(const GUID & id = pfc::guid_null) {return g_create(id,NULL,0);} + + static service_ptr_t g_create(const GUID & id, stream_reader * in, t_size bytes, abort_callback & abort); + static service_ptr_t g_create(stream_reader * in, t_size bytes, abort_callback & abort); + static service_ptr_t g_create(const void * data, t_size size); + service_ptr_t clone() const { + return g_create(get_guid(), get_data(), get_data_size()); + } + + FB2K_MAKE_SERVICE_INTERFACE(ui_element_config,service_base); +}; + +//! Helper. +class ui_element_config_parser : public stream_reader_formatter<> { +public: + ui_element_config_parser(ui_element_config::ptr in) : m_data(in), _m_stream(in->get_data(),in->get_data_size()), stream_reader_formatter(_m_stream,_m_abort) {} + + void reset() {_m_stream.reset();} + t_size get_remaining() const {return _m_stream.get_remaining();} + + ui_element_config::ptr subelement(t_size size); + ui_element_config::ptr subelement(const GUID & id, t_size dataSize); +private: + const ui_element_config::ptr m_data; + abort_callback_dummy _m_abort; + stream_reader_memblock_ref _m_stream; +}; + +//! Helper. +class ui_element_config_builder : public stream_writer_formatter<> { +public: + ui_element_config_builder() : stream_writer_formatter(_m_stream,_m_abort) {} + ui_element_config::ptr finish(const GUID & id) { + return ui_element_config::g_create(id,_m_stream.m_buffer); + } + void reset() { + _m_stream.m_buffer.set_size(0); + } +private: + abort_callback_dummy _m_abort; + stream_writer_buffer_simple _m_stream; +}; + + +FB2K_STREAM_WRITER_OVERLOAD(ui_element_config::ptr) { + stream << value->get_guid(); + t_size size = value->get_data_size(); + stream << pfc::downcast_guarded(size); + stream.write_raw(value->get_data(),size); + return stream; +} +FB2K_STREAM_READER_OVERLOAD(ui_element_config::ptr) { + GUID guid; + t_uint32 size; + stream >> guid >> size; + value = ui_element_config::g_create(guid,&stream.m_stream,size,stream.m_abort); + return stream; +} + + + + +typedef COLORREF t_ui_color; +typedef HFONT t_ui_font; +typedef HICON t_ui_icon; + +static const GUID ui_color_text = { 0x5dd38be7, 0xff8a, 0x416f, { 0x88, 0x2d, 0xa4, 0x8e, 0x31, 0x87, 0x85, 0xb2 } }; +static const GUID ui_color_background = { 0x16fc40c1, 0x1cba, 0x4385, { 0x93, 0x3b, 0xe9, 0x32, 0x7f, 0x6e, 0x35, 0x1f } }; +static const GUID ui_color_highlight = { 0xd2f98042, 0x3e6a, 0x423a, { 0xb8, 0x66, 0x65, 0x1, 0xfe, 0xa9, 0x75, 0x93 } }; +static const GUID ui_color_selection = { 0xebe1a36b, 0x7e0a, 0x469a, { 0x8e, 0xc5, 0xcf, 0x3, 0x12, 0x90, 0x40, 0xb5 } }; + +static const GUID ui_font_default = { 0x9ef02cef, 0xe58a, 0x4f99, { 0x9f, 0xe3, 0x85, 0x39, 0xb, 0xed, 0xc5, 0xe0 } }; +static const GUID ui_font_tabs = { 0x65ffd7ac, 0x71ce, 0x495c, { 0xa5, 0x99, 0x48, 0x5b, 0xbf, 0x7a, 0x4, 0x7b } }; +static const GUID ui_font_lists = { 0xa86198b3, 0xb5d8, 0x40cf, { 0xac, 0x19, 0xf9, 0xda, 0xc, 0xb5, 0xd4, 0x24 } }; +static const GUID ui_font_playlists = { 0xd85b7b7e, 0xbf83, 0x41ed, { 0x88, 0xce, 0x1, 0x99, 0x31, 0x94, 0x3e, 0x2f } }; +static const GUID ui_font_statusbar = { 0xc7fd555b, 0xbd15, 0x4f74, { 0x93, 0xe, 0xba, 0x55, 0x52, 0x9d, 0xd9, 0x71 } }; +static const GUID ui_font_console = { 0xb08c619d, 0xd3d1, 0x4089, { 0x93, 0xb2, 0xd5, 0xb, 0x87, 0x2d, 0x1a, 0x25 } }; + + + + +//! @returns -1 when the GUID is unknown / unmappable, index that can be passed over to GetSysColor() otherwise. +static int ui_color_to_sys_color_index(const GUID & p_guid) { + if (p_guid == ui_color_text) { + return COLOR_WINDOWTEXT; + } else if (p_guid == ui_color_background) { + return COLOR_WINDOW; + } else if (p_guid == ui_color_highlight) { + return COLOR_HOTLIGHT; + } else if (p_guid == ui_color_selection) { + return COLOR_HIGHLIGHT; + } else { + return -1; + } +} + + +struct ui_element_min_max_info { + ui_element_min_max_info() : m_min_width(0), m_max_width(~0), m_min_height(0), m_max_height(~0) {} + t_uint32 m_min_width, m_max_width, m_min_height, m_max_height; + + const ui_element_min_max_info & operator|=(const ui_element_min_max_info & p_other) { + m_min_width = pfc::max_t(m_min_width,p_other.m_min_width); + m_min_height = pfc::max_t(m_min_height,p_other.m_min_height); + m_max_width = pfc::min_t(m_max_width,p_other.m_max_width); + m_max_height = pfc::min_t(m_max_height,p_other.m_max_height); + return *this; + } + ui_element_min_max_info operator|(const ui_element_min_max_info & p_other) const { + ui_element_min_max_info ret(*this); + ret |= p_other; + return ret; + } + +}; + +//! Callback class passed by a UI element host to a UI element instance, allowing each UI element instance to communicate with its host. \n +//! Each ui_element_instance_callback implementation must also implement ui_element_instance_callback_v2. +class NOVTABLE ui_element_instance_callback : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(ui_element_instance_callback,service_base); +public: + virtual void on_min_max_info_change() = 0; + //! Deprecated, does nothing. + virtual void on_alt_pressed(bool p_state) = 0; + //! Returns true on success, false when the color is undefined and defaults such as global windows settings should be used. + virtual bool query_color(const GUID & p_what,t_ui_color & p_out) = 0; + //! Tells the host that specified element wants to activate itself as a result of some kind of external user command (eg. menu command). Host should ensure that requesting child element's window is visible.\n + //! @returns True when relevant child element window has been properly made visible and requesting code should proceed to SetFocus their window etc, false when denied. + virtual bool request_activation(service_ptr_t p_item) = 0; + + //! Queries whether "edit mode" is enabled. Most of UI element editing functionality should be locked when it's not. + virtual bool is_edit_mode_enabled() = 0; + + //! Tells the host that the user has requested the element to be replaced with another one. + //! Note: this is generally used only when "edit mode" is enabled, but legal to call when it's not (eg. dummy element calls it regardless of settings when clicked). + virtual void request_replace(service_ptr_t p_item) = 0; + + //! Deprecated - use query_font_ex. Equivalent to query_font_ex(ui_font_default). + t_ui_font query_font() {return query_font_ex(ui_font_default);} + + //! Retrieves an user-configurable font to use for specified kind of display. See ui_font_* constant for possible parameters. + virtual t_ui_font query_font_ex(const GUID & p_what) = 0; + + //! Helper - a wrapper around query_color(), if the color is not user-overridden, returns relevant system color. + t_ui_color query_std_color(const GUID & p_what); + + bool is_elem_visible_(service_ptr_t elem); + + t_size notify_(ui_element_instance * source, const GUID & what, t_size param1, const void * param2, t_size param2size); + bool set_elem_label(ui_element_instance * source, const char * label); + t_uint32 get_dialog_texture(ui_element_instance * source); + bool is_border_needed(ui_element_instance * source); +}; + + +class NOVTABLE ui_element_instance_callback_v2 : public ui_element_instance_callback { + FB2K_MAKE_SERVICE_INTERFACE(ui_element_instance_callback_v2, ui_element_instance_callback); +public: + virtual bool is_elem_visible(service_ptr_t elem) = 0; +}; + +class NOVTABLE ui_element_instance_callback_v3 : public ui_element_instance_callback_v2 { + FB2K_MAKE_SERVICE_INTERFACE(ui_element_instance_callback_v3, ui_element_instance_callback_v2) +public: + //! Returns zero when the notification was not handled, return value depends on the notification otherwise. + virtual t_size notify(ui_element_instance * source, const GUID & what, t_size param1, const void * param2, t_size param2size) = 0; +}; + +typedef service_ptr_t ui_element_instance_callback_ptr; + +//! ui_element_instance_callback implementation helper. +template class ui_element_instance_callback_impl : public ui_element_instance_callback_v3 { +public: + ui_element_instance_callback_impl(t_receiver * p_receiver) : m_receiver(p_receiver) {} + void on_min_max_info_change() { + if (m_receiver != NULL) m_receiver->on_min_max_info_change(); + } + void on_alt_pressed(bool p_state) {} + + bool query_color(const GUID & p_what,t_ui_color & p_out) { + if (m_receiver != NULL) return m_receiver->query_color(p_what,p_out); + else return false; + } + + bool request_activation(service_ptr_t p_item) { + if (m_receiver) return m_receiver->request_activation(p_item); + else return false; + } + + bool is_edit_mode_enabled() { + if (m_receiver) return m_receiver->is_edit_mode_enabled(); + else return false; + } + void request_replace(service_ptr_t p_item) { + if (m_receiver) m_receiver->request_replace(p_item); + } + + t_ui_font query_font_ex(const GUID & p_what) { + if (m_receiver) return m_receiver->query_font_ex(p_what); + else return NULL; + } + + void orphan() {m_receiver = NULL;} + + bool is_elem_visible(service_ptr_t elem) { + if (m_receiver) return m_receiver->is_elem_visible(elem); + else return false; + } + t_size notify(ui_element_instance * source, const GUID & what, t_size param1, const void * param2, t_size param2size) { + if (m_receiver) return m_receiver->host_notify(source, what, param1, param2, param2size); + else return 0; + } +private: + t_receiver * m_receiver; +}; + +//! ui_element_instance_callback implementation helper. +class ui_element_instance_callback_receiver { +public: + virtual void on_min_max_info_change() {} + virtual bool query_color(const GUID & p_what,t_ui_color & p_out) {return false;} + virtual bool request_activation(service_ptr_t p_item) {return false;} + virtual bool is_edit_mode_enabled() {return false;} + virtual void request_replace(service_ptr_t p_item) {} + virtual t_ui_font query_font_ex(const GUID&) {return NULL;} + virtual bool is_elem_visible(service_ptr_t elem) {return true;} + virtual t_size host_notify(ui_element_instance * source, const GUID & what, t_size param1, const void * param2, t_size param2size) {return 0;} + ui_element_instance_callback_ptr ui_element_instance_callback_get_ptr() { + if (m_callback.is_empty()) m_callback = new service_impl_t(this); + return m_callback; + } + void ui_element_instance_callback_release() { + if (m_callback.is_valid()) { + m_callback->orphan(); + m_callback.release(); + } + } +protected: + ~ui_element_instance_callback_receiver() { + ui_element_instance_callback_release(); + } + ui_element_instance_callback_receiver() {} + +private: + typedef ui_element_instance_callback_receiver t_self; + typedef ui_element_instance_callback_impl t_callback; + service_ptr_t m_callback; +}; + +//! Instance of a UI element. +class NOVTABLE ui_element_instance : public service_base { +public: + //! Returns ui_element_instance's window handle.\n + //! UI Element's window must be created when the ui_element_instance object is created. The window may or may not be destroyed by caller before the ui_element_instance itself is destroyed. If caller doesn't destroy the window before ui_element_instance destruction, ui_element_instance destructor should do it. + virtual HWND get_wnd() = 0; + + //! Alters element's current configuration. Specified ui_element_config's GUID must be the same as this element's GUID. + virtual void set_configuration(ui_element_config::ptr data) = 0; + //! Retrieves element's current configuration. Returned object's GUID must be set to your element's GUID so your element can be re-instantiated with stored settings. + virtual ui_element_config::ptr get_configuration() = 0; + + //! Returns GUID of the element. The return value must be the same as your ui_element::get_guid(). + virtual GUID get_guid() = 0; + //! Returns subclass GUID of the element. The return value must be the same as your ui_element::get_guid(). + virtual GUID get_subclass() = 0; + + //! Returns element's focus priority. + virtual double get_focus_priority() {return 0;} + //! Elements that host other elements should pass the call to the child with the highest priority. Override for container elements. + virtual void set_default_focus() {set_default_focus_fallback();} + + //! Overridden by containers only. + virtual bool get_focus_priority_subclass(double & p_out,const GUID & p_subclass) { + if (p_subclass == get_subclass()) {p_out = get_focus_priority(); return true;} + else {return false;} + } + //! Overridden by containers only. + virtual bool set_default_focus_subclass(const GUID & p_subclass) { + if (p_subclass == get_subclass()) {set_default_focus(); return true;} + else {return false;} + } + + //! Retrieves element's minimum/maximum window size. Default implementation will fall back to WM_GETMINMAXINFO. + virtual ui_element_min_max_info get_min_max_info() { + ui_element_min_max_info ret; + MINMAXINFO temp = {}; + temp.ptMaxTrackSize.x = 1024*1024;//arbitrary huge number + temp.ptMaxTrackSize.y = 1024*1024; + SendMessage(get_wnd(),WM_GETMINMAXINFO,0,(LPARAM)&temp); + if (temp.ptMinTrackSize.x >= 0) ret.m_min_width = temp.ptMinTrackSize.x; + if (temp.ptMaxTrackSize.x > 0) ret.m_max_width = temp.ptMaxTrackSize.x; + if (temp.ptMinTrackSize.y >= 0) ret.m_min_height = temp.ptMinTrackSize.y; + if (temp.ptMaxTrackSize.y > 0) ret.m_max_height = temp.ptMaxTrackSize.y; + return ret; + } + + //! Used by host to notify the element about various events. See ui_element_notify_* GUIDs for possible p_what parameter; meaning of other parameters depends on p_what value. Container classes should dispatch all notifications to their children. + virtual void notify(const GUID & p_what, t_size p_param1, const void * p_param2, t_size p_param2size) {} + + //! @param p_point Context menu point in screen coordinates. Always within out window's rect. + //! @return True to request edit_mode_context_menu_build() call to add our own items to the menu, false if we can't supply a context menu for this point. + virtual bool edit_mode_context_menu_test(const POINT & p_point,bool p_fromkeyboard) {return false;} + virtual void edit_mode_context_menu_build(const POINT & p_point,bool p_fromkeyboard,HMENU p_menu,unsigned p_id_base) {} + virtual void edit_mode_context_menu_command(const POINT & p_point,bool p_fromkeyboard,unsigned p_id,unsigned p_id_base) {} + //! @param p_point Receives the point to spawn context menu over when user has pressed the context menu key; in screen coordinates. + virtual bool edit_mode_context_menu_get_focus_point(POINT & p_point) {return false;} + + virtual bool edit_mode_context_menu_get_description(unsigned p_id,unsigned p_id_base,pfc::string_base & p_out) {return false;} + + + //! Helper. + void set_default_focus_fallback() { + const HWND thisWnd = this->get_wnd(); + if (thisWnd != NULL) ::SetFocus(thisWnd); + } + + FB2K_MAKE_SERVICE_INTERFACE(ui_element_instance,service_base); +}; + +typedef service_ptr_t ui_element_instance_ptr; + + +//! Interface to enumerate and possibly alter children of a container element. Obtained from ui_element::enumerate_children(). +class NOVTABLE ui_element_children_enumerator : public service_base { +public: + //! Retrieves the container's children count. + virtual t_size get_count() = 0; + //! Retrieves the configuration of the child at specified index, 0 <= index < get_count(). + virtual ui_element_config::ptr get_item(t_size p_index) = 0; + + //! Returns whether children count can be altered. For certain containers, children count is fixed and this method returns false. + virtual bool can_set_count() = 0; + //! Alters container's children count (behavior is undefined when can_set_count() returns false). Newly allocated children get default empty element configuration. + virtual void set_count(t_size count) = 0; + //! Alters the selected item. + virtual void set_item(t_size p_index,ui_element_config::ptr cfg) = 0; + //! Creates a new ui_element_config for this container, with our changes (set_count(), set_item()) applied. + virtual ui_element_config::ptr commit() = 0; + + FB2K_MAKE_SERVICE_INTERFACE(ui_element_children_enumerator,service_base); +}; + + +typedef service_ptr_t ui_element_children_enumerator_ptr; + + +//! Entrypoint interface for each UI element implementation. +class NOVTABLE ui_element : public service_base { +public: + //! Retrieves GUID of the element. + virtual GUID get_guid() = 0; + + //! Retrieves subclass GUID of the element. Typically one of ui_element_subclass_* values, but you can create your own custom subclasses. Subclass GUIDs are used for various purposes such as focusing an UI element that provides specific functionality. + virtual GUID get_subclass() = 0; + + //! Retrieves a simple human-readable name of the element. + virtual void get_name(pfc::string_base & p_out) = 0; + + //! Instantiates the element using specified settings. + virtual ui_element_instance_ptr instantiate(HWND p_parent,ui_element_config::ptr cfg,ui_element_instance_callback_ptr p_callback) = 0; + + //! Retrieves default configuration of the element. + virtual ui_element_config::ptr get_default_configuration() = 0; + + //! Implemented by container elements only. Returns NULL for non-container elements. \n + //! Allows caller to parse and edit child element structure of container elements. + virtual ui_element_children_enumerator_ptr enumerate_children(ui_element_config::ptr cfg) = 0; + + + //! In certain cases, an UI element can import settings of another UI element (eg. vertical<=>horizontal splitter, tabs<=>splitters) when user directly replaces one of such elements with another. Overriding this function allows special handling of such cases. \n + //! Implementation hint: when implementing a multi-child container, you probably want to takeover child elements replacing another container element; use enumerate_children() on the element the configuration belongs to to grab those. + //! @returns A new ui_element_config on success, a null pointer when the input data could not be parsed / is in an unknown format. + virtual ui_element_config::ptr import(ui_element_config::ptr cfg) {return NULL;} + + //! Override this to return false when your element is for internal use only and should not be user-addable. + virtual bool is_user_addable() {return true;} + + //! Returns an icon to show in available UI element lists, etc. Returns NULL when there is no icon to display. + virtual t_ui_icon get_icon() {return NULL;} + + //! Retrieves a human-readable description of the element. + virtual bool get_description(pfc::string_base & p_out) {return false;} + + //! Retrieves a human-readable description of the element's function to use for grouping in the element list. The default implementation relies on get_subclass() return value. + virtual bool get_element_group(pfc::string_base & p_out); + + static bool g_find(service_ptr_t & out, const GUID & id); + static bool g_get_name(pfc::string_base & p_out,const GUID & p_guid); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(ui_element); +}; + +//! Extended interface for a UI element implementation. +class NOVTABLE ui_element_v2 : public ui_element { +public: + enum { + //! Indicates that bump() method is supported. + KFlagSupportsBump = 1 << 0, + //! Tells UI backend to auto-generate a menu command activating your element - bumping an existing instance if possible, spawning a popup otherwise. + //! Currently menu commands are generated for ui_element_subclass_playback_visualisation, ui_element_subclass_media_library_viewers and ui_element_subclass_utility subclasses, in relevant menus. + KFlagHavePopupCommand = 1 << 1, + //! Tells backend that your element supports fullscreen mode (typically set only for visualisations). + KFlagHaveFullscreen = 1 << 2, + + KFlagPopupCommandHidden = 1 << 3, + + KFlagsVisualisation = KFlagHavePopupCommand | KFlagHaveFullscreen, + }; + virtual t_uint32 get_flags() = 0; + //! Called only when get_flags() return value has KFlagSupportsBump bit set. + //! Returns true when an existing instance of this element has been "bumped" - brought to user's attention in some way, false when there's no instance to bump or none of existing instances could be bumped for whatever reason. + virtual bool bump() = 0; + + //! Override to use another GUID for our menu command. Relevant only when KFlagHavePopupCommand is set. + virtual GUID get_menu_command_id() {return get_guid();} + + //! Override to use another description for our menu command. Relevant only when KFlagHavePopupCommand is set. + virtual bool get_menu_command_description(pfc::string_base & out) { + pfc::string8 name; get_name(name); + out = pfc::string_formatter() << "Activates " << name << " window."; + return true; + } + + //! Override to use another name for our menu command. Relevant only when KFlagHavePopupCommand is set. + virtual void get_menu_command_name(pfc::string_base & out) {get_name(out);} + //! Relevant only when KFlagHavePopupCommand is set. + //! @param defSize Default window size @ 96DPI. If screen DPI is different, it will be rescaled appropriately. + //! @param title Window title to use. + //! @returns True when implemented, false when not - caller will automatically determine default size and window title then. + virtual bool get_popup_specs(SIZE & defSize, pfc::string_base & title) {return false;} + + + FB2K_MAKE_SERVICE_INTERFACE(ui_element_v2, ui_element) +}; + +class NOVTABLE ui_element_popup_host_callback : public service_base { +public: + virtual void on_resize(t_uint32 width, t_uint32 height) = 0; + virtual void on_close() = 0; + virtual void on_destroy() = 0; + + FB2K_MAKE_SERVICE_INTERFACE(ui_element_popup_host_callback,service_base); +}; + +class NOVTABLE ui_element_popup_host : public service_base { + FB2K_MAKE_SERVICE_INTERFACE(ui_element_popup_host,service_base); +public: + virtual ui_element_instance::ptr get_root_elem() = 0; + virtual HWND get_wnd() = 0; + virtual ui_element_config::ptr get_config() = 0; + virtual void set_config(ui_element_config::ptr cfg) = 0; + //! Sets edit mode on/off. Default: off. + virtual void set_edit_mode(bool state) = 0; +}; + +class NOVTABLE ui_element_popup_host_v2 : public ui_element_popup_host { + FB2K_MAKE_SERVICE_INTERFACE(ui_element_popup_host_v2, ui_element_popup_host); +public: + virtual void set_window_title(const char * title) = 0; + virtual void allow_element_specified_title(bool allow) = 0; +}; + +//! For use with static_api_ptr_t<> +class NOVTABLE ui_element_common_methods : public service_base { +public: + virtual void copy(ui_element_config::ptr cfg) = 0; + virtual void cut(ui_element_instance_ptr & p_instance,HWND p_parent,ui_element_instance_callback_ptr p_callback) = 0; + virtual bool paste(ui_element_instance_ptr & p_instance,HWND p_parent,ui_element_instance_callback_ptr p_callback) = 0; + virtual bool is_paste_available() = 0; + virtual bool paste(ui_element_config::ptr & out) = 0; + + virtual bool parse_dataobject_check(pfc::com_ptr_t in, DWORD & dropEffect) = 0; + virtual bool parse_dataobject(pfc::com_ptr_t in,ui_element_config::ptr & out, DWORD & dropEffect) = 0; + + virtual pfc::com_ptr_t create_dataobject(ui_element_config::ptr in) = 0; + + virtual HWND spawn_scratchbox(HWND parent,ui_element_config::ptr cfg) = 0; + + virtual ui_element_popup_host::ptr spawn_host(HWND parent, ui_element_config::ptr cfg, ui_element_popup_host_callback::ptr callback, ui_element::ptr elem = NULL, DWORD style = WS_POPUPWINDOW|WS_CAPTION|WS_THICKFRAME, DWORD styleEx = WS_EX_CONTROLPARENT) = 0; + + void copy(ui_element_instance_ptr p_instance) {copy(p_instance->get_configuration());} + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(ui_element_common_methods); +}; + +//! For use with static_api_ptr_t<> +class NOVTABLE ui_element_common_methods_v2 : public ui_element_common_methods { +public: + virtual void spawn_host_simple(HWND parent, ui_element::ptr elem, bool fullScreenMode) = 0; + + void spawn_host_simple(HWND parent, const GUID & elem, bool fullScreenMode) { + spawn_host_simple(parent, service_by_guid(elem), fullScreenMode); + } + + virtual void toggle_fullscreen(ui_element::ptr elem, HWND parent) = 0; + + void toggle_fullscreen(const GUID & elem, HWND parent) { + toggle_fullscreen(service_by_guid(elem), parent); + } + + FB2K_MAKE_SERVICE_INTERFACE(ui_element_common_methods_v2, ui_element_common_methods); +}; + +class NOVTABLE ui_element_typable_window_manager : public service_base { +public: + virtual void add(HWND wnd) = 0; + virtual void remove(HWND wnd) = 0; + virtual bool is_registered(HWND wnd) = 0; + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(ui_element_typable_window_manager) +}; + +//! Dispatched through ui_element_instance::notify() when host changes color settings. Other parameters are not used and should be set to zero. +static const GUID ui_element_notify_colors_changed = { 0xeedda994, 0xe3d2, 0x441a, { 0xbe, 0x47, 0xa1, 0x63, 0x5b, 0x71, 0xab, 0x60 } }; +static const GUID ui_element_notify_font_changed = { 0x7a6964a8, 0xc797, 0x4737, { 0x90, 0x55, 0x7d, 0x84, 0xe7, 0x3d, 0x63, 0x6e } }; +static const GUID ui_element_notify_edit_mode_changed = { 0xf72f00af, 0xec76, 0x4251, { 0xb2, 0x67, 0x89, 0x4c, 0x52, 0x5f, 0x18, 0xc6 } }; + +//! Sent when a portion of the GUI is shown/hidden. First parameter is a bool flag indicating whether your UI Element is now visible. +static const GUID ui_element_notify_visibility_changed = { 0x313c22b9, 0x287a, 0x4804, { 0x8e, 0x6c, 0xff, 0xef, 0x4, 0x10, 0xcd, 0xea } }; + +//! Sent to retrieve areas occupied by elements to show overlay labels. Param1 is ignored, param2 is a pointer to ui_element_notify_get_element_labels_callback, param2size is ignored. +static const GUID ui_element_notify_get_element_labels = { 0x4850a2cb, 0x6cfc, 0x4d74, { 0x9a, 0x6d, 0xc, 0x7b, 0x29, 0x16, 0x5e, 0x69 } }; + + +//! Set to ui_element_instance_callback_v3 to set our element's label. Param1 is ignored, param2 is a pointer to a UTF-8 string containing the new label. Return value is 1 if the label is user-visible, 0 if the host does not support displaying overridden labels. +static const GUID ui_element_host_notify_set_elem_label = { 0x24598cb7, 0x9c5c, 0x488e, { 0xba, 0xff, 0xd, 0x2f, 0x11, 0x93, 0xe4, 0xf2 } }; +static const GUID ui_element_host_notify_get_dialog_texture = { 0xbb98eb99, 0x7b07, 0x42f3, { 0x8c, 0xd1, 0x12, 0xa2, 0xc2, 0x23, 0xb5, 0xbc } }; +static const GUID ui_element_host_notify_is_border_needed = { 0x2974f554, 0x2f31, 0x49c5, { 0xab, 0x4, 0x76, 0x4a, 0xf7, 0x94, 0x7c, 0x4f } }; + + + +class ui_element_notify_get_element_labels_callback { +public: + virtual void set_area_label(const RECT & rc, const char * name) = 0; + virtual void set_visible_element(ui_element_instance::ptr item) = 0; +protected: + ui_element_notify_get_element_labels_callback() {} + ~ui_element_notify_get_element_labels_callback() {} + + PFC_CLASS_NOT_COPYABLE_EX(ui_element_notify_get_element_labels_callback); +}; + + +static const GUID ui_element_subclass_playlist_renderers = { 0x3c4c68a0, 0xfc5, 0x400a, { 0xa3, 0x4a, 0x2e, 0x3a, 0xae, 0x6e, 0x90, 0x76 } }; +static const GUID ui_element_subclass_media_library_viewers = { 0x58455355, 0x289d, 0x459c, { 0x8f, 0x8a, 0xe1, 0x49, 0x6, 0xfc, 0x14, 0x56 } }; +static const GUID ui_element_subclass_containers = { 0x72dc5954, 0x1f26, 0x41be, { 0xae, 0xf2, 0x92, 0x9d, 0x25, 0xb5, 0x8d, 0xcf } }; +static const GUID ui_element_subclass_selection_information = { 0x68084e43, 0x7359, 0x46a5, { 0xb6, 0x84, 0x3c, 0xd7, 0x57, 0xf6, 0xde, 0xfd } }; +static const GUID ui_element_subclass_playback_visualisation = { 0x1f3c62f2, 0x8bb5, 0x4700, { 0x9e, 0x82, 0x8c, 0x48, 0x22, 0xf0, 0x18, 0x35 } }; +static const GUID ui_element_subclass_playback_information = { 0x84859f2d, 0xbb9c, 0x4e70, { 0x9d, 0x4, 0x14, 0x71, 0xb5, 0x63, 0x1f, 0x7f } }; +static const GUID ui_element_subclass_utility = { 0xffa4f4fc, 0xc169, 0x4766, { 0x9c, 0x94, 0xfa, 0xef, 0xae, 0xb2, 0x7e, 0xf } }; + +bool ui_element_subclass_description(const GUID & id, pfc::string_base & out); + + +#define ReplaceUIElementCommand "Replace UI Element..." +#define ReplaceUIElementDescription "Replaces this UI Element with another one." + +#define CopyUIElementCommand "Copy UI Element" +#define CopyUIElementDescription "Copies this UI Element to Windows Clipboard." + +#define PasteUIElementCommand "Paste UI Element" +#define PasteUIElementDescription "Replaces this UI Element with Windows Clipboard content." + +#define CutUIElementCommand "Cut UI Element" +#define CutUIElementDescription "Copies this UI Element to Windows Clipboard and replaces it with an empty UI Element." + +#define AddNewUIElementCommand "Add New UI Element..." +#define AddNewUIElementDescription "Replaces the selected empty space with a new UI Element." + + + + +template class ui_element_impl : public TInterface { +public: + GUID get_guid() { return TImpl::g_get_guid();} + GUID get_subclass() { return TImpl::g_get_subclass();} + void get_name(pfc::string_base & out) { TImpl::g_get_name(out); } + ui_element_instance::ptr instantiate(HWND parent,ui_element_config::ptr cfg,ui_element_instance_callback::ptr callback) { + PFC_ASSERT( cfg->get_guid() == get_guid() ); + service_nnptr_t item = new window_service_impl_t(cfg,callback); + item->initialize_window(parent); + return item; + } + ui_element_config::ptr get_default_configuration() { return TImpl::g_get_default_configuration(); } + ui_element_children_enumerator_ptr enumerate_children(ui_element_config::ptr cfg) {return NULL;} + bool get_description(pfc::string_base & out) {out = TImpl::g_get_description(); return true;} +private: + class ui_element_instance_impl_helper : public TImpl { + public: + ui_element_instance_impl_helper(ui_element_config::ptr cfg, ui_element_instance_callback::ptr callback) : TImpl(cfg,callback) {} + + GUID get_guid() {return TImpl::g_get_guid();} + GUID get_subclass() {return TImpl::g_get_subclass();} + HWND get_wnd() {return *this;} + }; +public: + typedef ui_element_instance_impl_helper TInstance; + static TInstance const & instanceGlobals() {return *reinterpret_cast(NULL);} +}; diff --git a/SDK/foobar2000/SDK/unpack.h b/SDK/foobar2000/SDK/unpack.h new file mode 100644 index 0000000..9d5328b --- /dev/null +++ b/SDK/foobar2000/SDK/unpack.h @@ -0,0 +1,22 @@ +//! Service providing "unpacker" functionality - processes "packed" file (such as a zip file containing a single media file inside) to allow its contents to be accessed transparently.\n +//! To access existing unpacker implementations, use unpacker::g_open helper function.\n +//! To register your own implementation, use unpacker_factory_t template. +class NOVTABLE unpacker : public service_base { +public: + //! Attempts to open specified file for unpacking, creates interface to virtual file with uncompressed data on success. When examined file doesn't appear to be one of formats supported by this unpacker implementation, throws exception_io_data. + //! @param p_out Receives interface to virtual file with uncompressed data on success. + //! @param p_source Source file to process. + //! @param p_abort abort_callback object signaling user aborting the operation. + virtual void open(service_ptr_t & p_out,const service_ptr_t & p_source,abort_callback & p_abort) = 0; + + //! Static helper querying existing unpacker implementations until one that successfully opens specified file is found. Attempts to open specified file for unpacking, creates interface to virtual file with uncompressed data on success. When examined file doesn't appear to be one of formats supported by registered unpacker implementations, throws exception_io_data. + //! @param p_out Receives interface to virtual file with uncompressed data on success. + //! @param p_source Source file to process. + //! @param p_abort abort_callback object signaling user aborting the operation. + static void g_open(service_ptr_t & p_out,const service_ptr_t & p_source,abort_callback & p_abort); + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(unpacker); +}; + +template +class unpacker_factory_t : public service_factory_single_t {}; diff --git a/SDK/foobar2000/SDK/vis.h b/SDK/foobar2000/SDK/vis.h new file mode 100644 index 0000000..f1e003d --- /dev/null +++ b/SDK/foobar2000/SDK/vis.h @@ -0,0 +1,78 @@ +//! This class provides abstraction for retrieving visualisation data. Instances of visualisation_stream being created/released serve as an indication for visualisation backend to process currently played audio data or shut down when there are no visualisation clients active.\n +//! Use visualisation_manager::create_stream to instantiate. +class NOVTABLE visualisation_stream : public service_base { +public: + //! Retrieves absolute playback time since last playback start or seek. You typically pass value retrieved by this function - optionally with offset added - to other visualisation_stream methods. + virtual bool get_absolute_time(double & p_value) = 0; + + //! Retrieves an audio chunk starting at specified offset (see get_absolute_time()), of specified length. + //! @returns False when requested timestamp is out of available range, true on success. + virtual bool get_chunk_absolute(audio_chunk & p_chunk,double p_offset,double p_requested_length) = 0; + //! Retrieves spectrum for audio data at specified offset (see get_absolute_time()), with specified FFT size. + //! @param p_chunk Receives spectrum data. audio_chunk type is used for consistency (since required functionality is identical to provided by audio_chunk), the data is *not* PCM. Returned sample count is equal to half of FFT size; channels and sample rate are as in audio stream the spectrum was generated from. + //! @param p_offset Timestamp of spectrum to retrieve. See get_absolute_time(). + //! @param p_fft_size FFT size to use for spectrum generation. Must be a power of 2. + //! @returns False when requested timestamp is out of available range, true on success. + virtual bool get_spectrum_absolute(audio_chunk & p_chunk,double p_offset,unsigned p_fft_size) = 0; + + //! Generates fake audio chunk to display when get_chunk_absolute() fails - e.g. shortly after visualisation_stream creation data for currently played audio might not be available yet. + //! Throws std::exception derivatives on failure. + virtual void make_fake_chunk_absolute(audio_chunk & p_chunk,double p_offset,double p_requested_length) = 0; + //! Generates fake spectrum to display when get_spectrum_absolute() fails - e.g. shortly after visualisation_stream creation data for currently played audio might not be available yet. + //! Throws std::exception derivatives on failure. + virtual void make_fake_spectrum_absolute(audio_chunk & p_chunk,double p_offset,unsigned p_fft_size) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(visualisation_stream,service_base); +}; + +//! New in 0.9.5. +class NOVTABLE visualisation_stream_v2 : public visualisation_stream { +public: + virtual void request_backlog(double p_time) = 0; + virtual void set_channel_mode(t_uint32 p_mode) = 0; + + enum { + channel_mode_default = 0, + channel_mode_mono, + channel_mode_frontonly, + channel_mode_backonly, + }; + + FB2K_MAKE_SERVICE_INTERFACE(visualisation_stream_v2,visualisation_stream); +}; + +//! New in 0.9.5.2. +class NOVTABLE visualisation_stream_v3 : public visualisation_stream_v2 { +public: + virtual void chunk_to_spectrum(audio_chunk const & chunk, audio_chunk & spectrum, double centerOffset) = 0; + + FB2K_MAKE_SERVICE_INTERFACE(visualisation_stream_v3,visualisation_stream_v2); +}; + +//! Entrypoint service for visualisation processing; use this to create visualisation_stream objects that can be used to retrieve properties of currently played audio. \n +//! Implemented by core; do not reimplement.\n +//! Use static_api_ptr_t to access it, e.g. static_api_ptr_t()->create_stream(mystream,0); +class NOVTABLE visualisation_manager : public service_base { +public: + //! Creates a visualisation_stream object. See visualisation_stream for more info. + //! @param p_out Receives newly created visualisation_stream instance. + //! @param p_flags Combination of one or more KStreamFlag* values. Currently only KStreamFlagNewFFT is defined. + //! It's recommended that you set p_flags to KStreamFlagNewFFT to get the new FFT behavior (better quality and result normalization), the old behavior for null flags is preserved for compatibility with old components that rely on it. + virtual void create_stream(service_ptr_t & p_out,unsigned p_flags) = 0; + + enum { + //! New FFT behavior for spectrum-generating methods, available in 0.9.5.2 and newer: output normalized to 0..1, Gauss window used instead of rectangluar (better quality / less aliasing). + //! It's recommended to always set this flag. The old behavior is preserved for backwards compatibility. + KStreamFlagNewFFT = 1 << 0, + }; + + + //! Wrapper around non-template create_stream(); retrieves one of newer visualisation_stream_* interfaces rather than base visualisation_stream interface. Throws exception_service_extension_not_found() when running too old foobar2000 version for the requested interface. + template + void create_stream(t_streamptr & out, unsigned flags) { + visualisation_stream::ptr temp; create_stream(temp, flags); + if (!temp->service_query_t(out)) throw exception_service_extension_not_found(); + } + + FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(visualisation_manager); +}; diff --git a/SDK/foobar2000/foobar2000_component_client/component_client.cpp b/SDK/foobar2000/foobar2000_component_client/component_client.cpp new file mode 100644 index 0000000..b9b5e06 --- /dev/null +++ b/SDK/foobar2000/foobar2000_component_client/component_client.cpp @@ -0,0 +1,123 @@ +#include "../SDK/foobar2000.h" +#include "../SDK/component.h" + +static HINSTANCE g_hIns; + +static pfc::string_simple g_name,g_full_path; + +static bool g_services_available = false, g_initialized = false; + + + +namespace core_api +{ + + HINSTANCE get_my_instance() + { + return g_hIns; + } + + HWND get_main_window() + { + PFC_ASSERT( g_foobar2000_api != NULL ); + return g_foobar2000_api->get_main_window(); + } + const char* get_my_file_name() + { + return g_name; + } + + const char* get_my_full_path() + { + return g_full_path; + } + + bool are_services_available() + { + return g_services_available; + } + bool assert_main_thread() + { + return (g_services_available && g_foobar2000_api) ? g_foobar2000_api->assert_main_thread() : true; + } + + void ensure_main_thread() { + if (!is_main_thread()) uBugCheck(); + } + + bool is_main_thread() + { + return (g_services_available && g_foobar2000_api) ? g_foobar2000_api->is_main_thread() : true; + } + const char* get_profile_path() + { + PFC_ASSERT( g_foobar2000_api != NULL ); + return g_foobar2000_api->get_profile_path(); + } + + bool is_shutting_down() + { + return (g_services_available && g_foobar2000_api) ? g_foobar2000_api->is_shutting_down() : g_initialized; + } + bool is_initializing() + { + return (g_services_available && g_foobar2000_api) ? g_foobar2000_api->is_initializing() : !g_initialized; + } + bool is_portable_mode_enabled() { + PFC_ASSERT( g_foobar2000_api != NULL ); + return g_foobar2000_api->is_portable_mode_enabled(); + } + + bool is_quiet_mode_enabled() { + PFC_ASSERT( g_foobar2000_api != NULL ); + return g_foobar2000_api->is_quiet_mode_enabled(); + } +} + +namespace { + class foobar2000_client_impl : public foobar2000_client, private foobar2000_component_globals + { + public: + t_uint32 get_version() {return FOOBAR2000_CLIENT_VERSION;} + pservice_factory_base get_service_list() {return service_factory_base::__internal__list;} + + void get_config(stream_writer * p_stream,abort_callback & p_abort) { + cfg_var::config_write_file(p_stream,p_abort); + } + + void set_config(stream_reader * p_stream,abort_callback & p_abort) { + cfg_var::config_read_file(p_stream,p_abort); + } + + void set_library_path(const char * path,const char * name) { + g_full_path = path; + g_name = name; + } + + void services_init(bool val) { + if (val) g_initialized = true; + g_services_available = val; + } + + bool is_debug() { +#ifdef _DEBUG + return true; +#else + return false; +#endif + } + }; +} + +static foobar2000_client_impl g_client; + +extern "C" +{ + __declspec(dllexport) foobar2000_client * _cdecl foobar2000_get_interface(foobar2000_api * p_api,HINSTANCE hIns) + { + g_hIns = hIns; + g_foobar2000_api = p_api; + + return &g_client; + } +} diff --git a/SDK/foobar2000/foobar2000_component_client/foobar2000_component_client.vcxproj b/SDK/foobar2000/foobar2000_component_client/foobar2000_component_client.vcxproj new file mode 100644 index 0000000..aa973aa --- /dev/null +++ b/SDK/foobar2000/foobar2000_component_client/foobar2000_component_client.vcxproj @@ -0,0 +1,179 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {71AD2674-065B-48F5-B8B0-E1F9D3892081} + foobar2000_component_client + + + + StaticLibrary + false + Unicode + true + v143 + + + StaticLibrary + false + Unicode + v143 + + + StaticLibrary + false + Unicode + true + v143 + + + StaticLibrary + false + Unicode + v143 + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(Configuration)\ + $(Configuration)\ + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + $(Configuration)\ + $(Configuration)\ + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + + + + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + EnableFastChecks + + + Level3 + true + ProgramDatabase + MultiThreadedDebugDLL + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + X64 + + + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + + + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + MinSpace + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + false + Fast + false + Level3 + true + ProgramDatabase + MultiThreadedDLL + NotSet + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + X64 + + + false + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + Fast + false + Level3 + true + MultiThreadedDLL + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + Disabled + EnableFastChecks + Disabled + EnableFastChecks + MaxSpeed + MaxSpeed + + + + + + \ No newline at end of file diff --git a/SDK/foobar2000/foobar2000_component_client/foobar2000_component_client.vcxproj.user b/SDK/foobar2000/foobar2000_component_client/foobar2000_component_client.vcxproj.user new file mode 100644 index 0000000..0f14913 --- /dev/null +++ b/SDK/foobar2000/foobar2000_component_client/foobar2000_component_client.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/SDK/foobar2000/helpers/COM_utils.h b/SDK/foobar2000/helpers/COM_utils.h new file mode 100644 index 0000000..b4a2a50 --- /dev/null +++ b/SDK/foobar2000/helpers/COM_utils.h @@ -0,0 +1,10 @@ +#define FB2K_COM_CATCH catch(exception_com const & e) {return e.get_code();} catch(std::bad_alloc) {return E_OUTOFMEMORY;} catch(pfc::exception_invalid_params) {return E_INVALIDARG;} catch(...) {return E_UNEXPECTED;} + +#define COM_QI_BEGIN() HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,void ** ppvObject) { if (ppvObject == NULL) return E_INVALIDARG; +#define COM_QI_ENTRY(IWhat) { if (iid == __uuidof(IWhat)) {IWhat * temp = this; temp->AddRef(); * ppvObject = temp; return S_OK;} } +#define COM_QI_ENTRY_(IWhat, IID) { if (iid == IID) {IWhat * temp = this; temp->AddRef(); * ppvObject = temp; return S_OK;} } +#define COM_QI_END() * ppvObject = NULL; return E_NOINTERFACE; } + +#define COM_QI_CHAIN(Parent) { HRESULT status = Parent::QueryInterface(iid, ppvObject); if (SUCCEEDED(status)) return status; } + +#define COM_QI_SIMPLE(IWhat) COM_QI_BEGIN() COM_QI_ENTRY(IUnknown) COM_QI_ENTRY(IWhat) COM_QI_END() \ No newline at end of file diff --git a/SDK/foobar2000/helpers/CPowerRequest.cpp b/SDK/foobar2000/helpers/CPowerRequest.cpp new file mode 100644 index 0000000..9970c07 --- /dev/null +++ b/SDK/foobar2000/helpers/CPowerRequest.cpp @@ -0,0 +1,89 @@ +#include "stdafx.h" + +#ifdef _WIN32 + +// win32 API declaration duplicate - not always defined on some of the Windows versions we target +namespace winapi_substitute { + + typedef struct _REASON_CONTEXT { + ULONG Version; + DWORD Flags; + union { + struct { + HMODULE LocalizedReasonModule; + ULONG LocalizedReasonId; + ULONG ReasonStringCount; + LPWSTR *ReasonStrings; + + } Detailed; + + LPWSTR SimpleReasonString; + } Reason; + } REASON_CONTEXT, *PREASON_CONTEXT; + + // + // Power Request APIs + // + + typedef REASON_CONTEXT POWER_REQUEST_CONTEXT, *PPOWER_REQUEST_CONTEXT, *LPPOWER_REQUEST_CONTEXT; + +} + +HANDLE CPowerRequestAPI::PowerCreateRequestNamed( const wchar_t * str ) { + winapi_substitute::REASON_CONTEXT ctx = {POWER_REQUEST_CONTEXT_VERSION, POWER_REQUEST_CONTEXT_SIMPLE_STRING}; + ctx.Reason.SimpleReasonString = const_cast(str); + return this->PowerCreateRequest(&ctx); +} + +CPowerRequest::CPowerRequest(const wchar_t * Reason) : m_Request(INVALID_HANDLE_VALUE), m_bSystem(), m_bDisplay() { + HMODULE kernel32 = GetModuleHandle(_T("kernel32.dll")); + if (m_API.IsValid()) { + winapi_substitute::REASON_CONTEXT ctx = {POWER_REQUEST_CONTEXT_VERSION, POWER_REQUEST_CONTEXT_SIMPLE_STRING}; + ctx.Reason.SimpleReasonString = const_cast(Reason); + m_Request = m_API.PowerCreateRequest(&ctx); + } +} + +void CPowerRequest::SetSystem(bool bSystem) { + if (bSystem == m_bSystem) return; + m_bSystem = bSystem; + if (m_Request != INVALID_HANDLE_VALUE) { + m_API.ToggleSystem( m_Request, bSystem ); + } else { + _UpdateTES(); + } +} + +void CPowerRequest::SetExecution(bool bExecution) { + if (bExecution == m_bSystem) return; + m_bSystem = bExecution; + if (m_Request != INVALID_HANDLE_VALUE) { + m_API.ToggleExecution( m_Request, bExecution ); + } else { + _UpdateTES(); + } +} + +void CPowerRequest::SetDisplay(bool bDisplay) { + if (bDisplay == m_bDisplay) return; + m_bDisplay = bDisplay; + if (m_Request != INVALID_HANDLE_VALUE) { + m_API.ToggleDisplay(m_Request, bDisplay); + } else { + _UpdateTES(); + } +} + +CPowerRequest::~CPowerRequest() { + if (m_Request != INVALID_HANDLE_VALUE) { + CloseHandle(m_Request); + } else { + if (m_bDisplay || m_bSystem) SetThreadExecutionState(ES_CONTINUOUS); + } +} + +void CPowerRequest::_UpdateTES() { + SetThreadExecutionState(ES_CONTINUOUS | (m_bSystem ? ES_SYSTEM_REQUIRED : 0 ) | (m_bDisplay ? ES_DISPLAY_REQUIRED : 0) ); +} +#endif // _WIN32 + diff --git a/SDK/foobar2000/helpers/CPowerRequest.h b/SDK/foobar2000/helpers/CPowerRequest.h new file mode 100644 index 0000000..3fb907d --- /dev/null +++ b/SDK/foobar2000/helpers/CPowerRequest.h @@ -0,0 +1,101 @@ +#ifdef _WIN32 + +typedef HANDLE (WINAPI * pPowerCreateRequest_t) ( + __in void* Context + ); + +typedef BOOL (WINAPI * pPowerSetRequest_t) ( + __in HANDLE PowerRequest, + __in POWER_REQUEST_TYPE RequestType + ); + +typedef BOOL (WINAPI * pPowerClearRequest_t) ( + __in HANDLE PowerRequest, + __in POWER_REQUEST_TYPE RequestType + ); + +class CPowerRequestAPI { +public: + CPowerRequestAPI() : PowerCreateRequest(), PowerSetRequest(), PowerClearRequest() { + Bind(); + } + bool Bind() { + HMODULE kernel32 = GetModuleHandle(_T("kernel32.dll")); + return Bind(PowerCreateRequest, kernel32, "PowerCreateRequest") + && Bind(PowerSetRequest, kernel32, "PowerSetRequest") + && Bind(PowerClearRequest, kernel32, "PowerClearRequest") ; + } + bool IsValid() {return PowerCreateRequest != NULL;} + + void ToggleSystem(HANDLE hRequest, bool bSystem) { + Toggle(hRequest, bSystem, PowerRequestSystemRequired); + } + + void ToggleExecution(HANDLE hRequest, bool bSystem) { + const POWER_REQUEST_TYPE _PowerRequestExecutionRequired = (POWER_REQUEST_TYPE)3; + const POWER_REQUEST_TYPE RequestType = IsWin8() ? _PowerRequestExecutionRequired : PowerRequestSystemRequired; + Toggle(hRequest, bSystem, RequestType); + } + + void ToggleDisplay(HANDLE hRequest, bool bDisplay) { + Toggle(hRequest, bDisplay, PowerRequestDisplayRequired); + } + + void Toggle(HANDLE hRequest, bool bToggle, POWER_REQUEST_TYPE what) { + if (bToggle) { + PowerSetRequest(hRequest, what); + } else { + PowerClearRequest(hRequest, what); + } + + } + HANDLE PowerCreateRequestNamed( const wchar_t * str ); + + static bool IsWin8() { + auto ver = myGetOSVersion(); + return ver >= 0x602; + } + static WORD myGetOSVersion() { + const DWORD ver = GetVersion(); + return (WORD)HIBYTE(LOWORD(ver)) | ((WORD)LOBYTE(LOWORD(ver)) << 8); + } + + pPowerCreateRequest_t PowerCreateRequest; + pPowerSetRequest_t PowerSetRequest; + pPowerClearRequest_t PowerClearRequest; +private: + template static bool Bind(func_t & f, HMODULE dll, const char * name) { + f = reinterpret_cast(GetProcAddress(dll, name)); + return f != NULL; + } +}; + +class CPowerRequest { +public: + CPowerRequest(const wchar_t * Reason); + void SetSystem(bool bSystem); + void SetExecution(bool bExecution); + void SetDisplay(bool bDisplay); + ~CPowerRequest(); +private: + void _UpdateTES(); + HANDLE m_Request; + bool m_bSystem, m_bDisplay; + CPowerRequestAPI m_API; + CPowerRequest(const CPowerRequest&); + void operator=(const CPowerRequest&); +}; +#else + +class CPowerRequest { +public: + CPowerRequest(const wchar_t * Reason) {} + void SetSystem(bool bSystem) {} + void SetExecution(bool bExecution) {} + void SetDisplay(bool bDisplay) {} +private: + CPowerRequest(const CPowerRequest&); + void operator=(const CPowerRequest&); +}; + +#endif \ No newline at end of file diff --git a/SDK/foobar2000/helpers/CallForwarder.h b/SDK/foobar2000/helpers/CallForwarder.h new file mode 100644 index 0000000..6ce9c05 --- /dev/null +++ b/SDK/foobar2000/helpers/CallForwarder.h @@ -0,0 +1,48 @@ +namespace CF { + template class _inMainThread : public main_thread_callback { + public: + _inMainThread(obj_t const & obj, const arg_t & arg) : m_obj(obj), m_arg(arg) {} + + void callback_run() { + if (m_obj.IsValid()) callInMainThread::callThis(&*m_obj, m_arg); + } + private: + obj_t m_obj; + arg_t m_arg; + }; + + template class CallForwarder { + public: + CallForwarder(TWhat * ptr) { m_ptr.new_t(ptr); } + + void Orphan() {*m_ptr = NULL;} + bool IsValid() const { return *m_ptr != NULL; } + bool IsEmpty() const { return !IsValid(); } + + TWhat * operator->() const { + PFC_ASSERT( IsValid() ); + return *m_ptr; + } + + TWhat & operator*() const { + PFC_ASSERT( IsValid() ); + return **m_ptr; + } + + template + void callInMainThread(const arg_t & arg) { + main_thread_callback_add( new service_impl_t<_inMainThread< CallForwarder, arg_t> >(*this, arg) ); + } + private: + pfc::rcptr_t m_ptr; + }; + + template class CallForwarderMaster : public CallForwarder { + public: + CallForwarderMaster(TWhat * ptr) : CallForwarder(ptr) {} + ~CallForwarderMaster() { this->Orphan(); } + + PFC_CLASS_NOT_COPYABLE(CallForwarderMaster, CallForwarderMaster); + }; + +} \ No newline at end of file diff --git a/SDK/foobar2000/helpers/IDataObjectUtils.cpp b/SDK/foobar2000/helpers/IDataObjectUtils.cpp new file mode 100644 index 0000000..d1a6160 --- /dev/null +++ b/SDK/foobar2000/helpers/IDataObjectUtils.cpp @@ -0,0 +1,189 @@ +#include "stdafx.h" + +#ifdef _WIN32 + +HRESULT IDataObjectUtils::DataBlockToSTGMEDIUM(const void * blockPtr, t_size blockSize, STGMEDIUM * medium, DWORD tymed, bool bHere) throw() { + try { + if (bHere) { + switch(tymed) { + case TYMED_ISTREAM: + { + if (medium->pstm == NULL) return E_INVALIDARG; + ULONG written = 0; + HRESULT state; + state = medium->pstm->Write(blockPtr, pfc::downcast_guarded(blockSize),&written); + if (FAILED(state)) return state; + if (written != blockSize) return STG_E_MEDIUMFULL; + return S_OK; + } + default: + return DV_E_TYMED; + } + } else { + if (tymed & TYMED_HGLOBAL) { + HGLOBAL hMem = HGlobalFromMemblock(blockPtr, blockSize); + if (hMem == NULL) return E_OUTOFMEMORY; + medium->tymed = TYMED_HGLOBAL; + medium->hGlobal = hMem; + medium->pUnkForRelease = NULL; + return S_OK; + } + if (tymed & TYMED_ISTREAM) { + HRESULT state; + HGLOBAL hMem = HGlobalFromMemblock(blockPtr, blockSize); + if (hMem == NULL) return E_OUTOFMEMORY; + medium->tymed = TYMED_ISTREAM; + pfc::com_ptr_t stream; + if (FAILED( state = CreateStreamOnHGlobal(hMem,TRUE,stream.receive_ptr()) ) ) { + GlobalFree(hMem); + return state; + } + { + LARGE_INTEGER wtf = {}; + if (FAILED( state = stream->Seek(wtf,STREAM_SEEK_END,NULL) ) ) { + return state; + } + } + medium->pstm = stream.detach(); + medium->pUnkForRelease = NULL; + return S_OK; + } + return DV_E_TYMED; + } + } catch(pfc::exception_not_implemented) { + return E_NOTIMPL; + } catch(std::bad_alloc) { + return E_OUTOFMEMORY; + } catch(...) { + return E_UNEXPECTED; + } +} + + +HGLOBAL IDataObjectUtils::HGlobalFromMemblock(const void * ptr,t_size size) { + HGLOBAL handle = GlobalAlloc(GMEM_MOVEABLE,size); + if (handle != NULL) { + void * destptr = GlobalLock(handle); + if (destptr == NULL) { + GlobalFree(handle); + handle = NULL; + } else { + memcpy(destptr,ptr,size); + GlobalUnlock(handle); + } + } + return handle; +} + +HRESULT IDataObjectUtils::ExtractDataObjectContent(pfc::com_ptr_t obj, UINT format, DWORD aspect, LONG index, pfc::array_t & out) { + FORMATETC fmt = {}; + fmt.cfFormat = format; fmt.dwAspect = aspect; fmt.lindex = index; + fmt.tymed = TYMED_HGLOBAL /* | TYMED_ISTREAM*/; + + STGMEDIUM med = {}; + HRESULT state; + if (FAILED( state = obj->GetData(&fmt,&med) ) ) return state; + ReleaseStgMediumScope relScope(&med); + return STGMEDIUMToDataBlock(med, out); +} + +HRESULT IDataObjectUtils::STGMEDIUMToDataBlock(const STGMEDIUM & med, pfc::array_t & out) { + switch(med.tymed) { + case TYMED_HGLOBAL: + { + CGlobalLockScope lock(med.hGlobal); + out.set_data_fromptr( (const t_uint8*) lock.GetPtr(), lock.GetSize() ); + } + return S_OK; + case TYMED_ISTREAM: + { + HRESULT state; + IStream * stream = med.pstm; + LARGE_INTEGER offset = {}; + STATSTG stats = {}; + if (FAILED( state = stream->Stat(&stats,STATFLAG_NONAME ) ) ) return state; + t_size toRead = pfc::downcast_guarded(stats.cbSize.QuadPart); + out.set_size(toRead); + if (FAILED( state = stream->Seek(offset,STREAM_SEEK_SET,NULL) ) ) return state; + ULONG cbRead = 0; + if (FAILED( state = stream->Read(out.get_ptr(), pfc::downcast_guarded(toRead), &cbRead) ) ) return state; + if (cbRead != toRead) return E_UNEXPECTED; + } + return S_OK; + default: + return DV_E_TYMED; + } +} + +HRESULT IDataObjectUtils::ExtractDataObjectContent(pfc::com_ptr_t obj, UINT format, pfc::array_t & out) { + return ExtractDataObjectContent(obj, format, DVASPECT_CONTENT, -1, out); +} + +HRESULT IDataObjectUtils::ExtractDataObjectContentTest(pfc::com_ptr_t obj, UINT format, DWORD aspect, LONG index) { + FORMATETC fmt = {}; + fmt.cfFormat = format; fmt.dwAspect = aspect; fmt.lindex = index; + for(t_uint32 walk = 0; walk < 32; ++walk) { + const DWORD tymed = 1 << walk; + if ((ExtractDataObjectContent_SupportedTymeds & tymed) != 0) { + fmt.tymed = tymed; + HRESULT state = obj->QueryGetData(&fmt); + if (SUCCEEDED(state)) { + if (state == S_OK) return S_OK; + } else { + if (state != DV_E_TYMED) return state; + } + } + } + return E_FAIL; +} + +HRESULT IDataObjectUtils::ExtractDataObjectContentTest(pfc::com_ptr_t obj, UINT format) { + return ExtractDataObjectContentTest(obj,format,DVASPECT_CONTENT,-1); +} + +HRESULT IDataObjectUtils::ExtractDataObjectString(pfc::com_ptr_t obj, pfc::string_base & out) { + pfc::array_t data; + HRESULT state; + state = ExtractDataObjectContent(obj,CF_UNICODETEXT,data); + if (SUCCEEDED(state)) { + out = pfc::stringcvt::string_utf8_from_os_ex( (const wchar_t*) data.get_ptr(), data.get_size() / sizeof(wchar_t) ); + return S_OK; + } + state = ExtractDataObjectContent(obj,CF_TEXT,data); + if (SUCCEEDED(state)) { + out = pfc::stringcvt::string_utf8_from_os_ex( (const char*) data.get_ptr(), data.get_size() / sizeof(char) ); + return S_OK; + } + return E_FAIL; +} + +HRESULT IDataObjectUtils::SetDataObjectContent(pfc::com_ptr_t obj, UINT format, DWORD aspect, LONG index, const void * data, t_size dataSize) { + STGMEDIUM med = {}; + FORMATETC fmt = {}; + fmt.cfFormat = format; fmt.dwAspect = aspect; fmt.lindex = index; fmt.tymed = TYMED_HGLOBAL; + HRESULT state; + if (FAILED(state = DataBlockToSTGMEDIUM(data,dataSize,&med,TYMED_HGLOBAL,false))) return state; + return obj->SetData(&fmt,&med,TRUE); +} + +HRESULT IDataObjectUtils::SetDataObjectString(pfc::com_ptr_t obj, const char * str) { + pfc::stringcvt::string_wide_from_utf8 s(str); + return SetDataObjectContent(obj,CF_UNICODETEXT,DVASPECT_CONTENT,-1,s.get_ptr(), (s.length()+1) * sizeof(s[0])); +} + +HRESULT IDataObjectUtils::ExtractDataObjectDWORD(pfc::com_ptr_t obj, UINT format, DWORD & val) { + HRESULT state; + pfc::array_t buffer; + if (FAILED( state = ExtractDataObjectContent(obj, format, DVASPECT_CONTENT, -1, buffer) ) ) return state; + if (buffer.get_size() < sizeof(val)) return E_UNEXPECTED; + val = *(DWORD*) buffer.get_ptr(); + return S_OK; +} +HRESULT IDataObjectUtils::SetDataObjectDWORD(pfc::com_ptr_t obj, UINT format, DWORD val) { + return SetDataObjectContent(obj,format,DVASPECT_CONTENT,-1,&val,sizeof(val)); +} +HRESULT IDataObjectUtils::PasteSucceeded(pfc::com_ptr_t obj, DWORD effect) { + return SetDataObjectDWORD(obj, RegisterClipboardFormat(CFSTR_PASTESUCCEEDED), effect); +} + +#endif // _WIN32 diff --git a/SDK/foobar2000/helpers/IDataObjectUtils.h b/SDK/foobar2000/helpers/IDataObjectUtils.h new file mode 100644 index 0000000..84fc80f --- /dev/null +++ b/SDK/foobar2000/helpers/IDataObjectUtils.h @@ -0,0 +1,183 @@ +#ifdef _WIN32 +#include + +namespace IDataObjectUtils { + + class ReleaseStgMediumScope { + public: + ReleaseStgMediumScope(STGMEDIUM * medium) : m_medium(medium) {} + ~ReleaseStgMediumScope() {if (m_medium != NULL) ReleaseStgMedium(m_medium);} + private: + STGMEDIUM * m_medium; + + PFC_CLASS_NOT_COPYABLE_EX(ReleaseStgMediumScope) + }; + + static const DWORD DataBlockToSTGMEDIUM_SupportedTymeds = TYMED_ISTREAM | TYMED_HGLOBAL; + static const DWORD ExtractDataObjectContent_SupportedTymeds = TYMED_ISTREAM | TYMED_HGLOBAL; + + HRESULT DataBlockToSTGMEDIUM(const void * blockPtr, t_size blockSize, STGMEDIUM * medium, DWORD tymed, bool bHere) throw(); + + HGLOBAL HGlobalFromMemblock(const void * ptr,t_size size); + + HRESULT ExtractDataObjectContent(pfc::com_ptr_t obj, UINT format, DWORD aspect, LONG index, pfc::array_t & out); + HRESULT ExtractDataObjectContent(pfc::com_ptr_t obj, UINT format, pfc::array_t & out); + + HRESULT ExtractDataObjectContentTest(pfc::com_ptr_t obj, UINT format, DWORD aspect, LONG index); + HRESULT ExtractDataObjectContentTest(pfc::com_ptr_t obj, UINT format); + + HRESULT ExtractDataObjectString(pfc::com_ptr_t obj, pfc::string_base & out); + HRESULT SetDataObjectString(pfc::com_ptr_t obj, const char * str); + + HRESULT SetDataObjectContent(pfc::com_ptr_t obj, UINT format, DWORD aspect, LONG index, const void * data, t_size dataSize); + + HRESULT STGMEDIUMToDataBlock(const STGMEDIUM & med, pfc::array_t & out); + + HRESULT ExtractDataObjectDWORD(pfc::com_ptr_t obj, UINT format, DWORD & val); + HRESULT SetDataObjectDWORD(pfc::com_ptr_t obj, UINT format, DWORD val); + + HRESULT PasteSucceeded(pfc::com_ptr_t obj, DWORD effect); + + class comparator_FORMATETC { + public: + static int compare(const FORMATETC & v1, const FORMATETC & v2) { + int val; + val = pfc::compare_t(v1.cfFormat,v2.cfFormat); if (val != 0) return val; + val = pfc::compare_t(v1.dwAspect,v2.dwAspect); if (val != 0) return val; + val = pfc::compare_t(v1.lindex, v2.lindex ); if (val != 0) return val; + return 0; + } + }; + + class CDataObjectBase : public IDataObject { + public: + COM_QI_SIMPLE(IDataObject) + + HRESULT STDMETHODCALLTYPE GetData(FORMATETC * formatetc, STGMEDIUM * medium) { + return GetData_internal(formatetc,medium,false); + } + + HRESULT STDMETHODCALLTYPE GetDataHere(FORMATETC * formatetc, STGMEDIUM * medium) { + return GetData_internal(formatetc,medium,true); + } + + HRESULT STDMETHODCALLTYPE QueryGetData(FORMATETC * formatetc) { + if (formatetc == NULL) return E_INVALIDARG; + + if ((DataBlockToSTGMEDIUM_SupportedTymeds & formatetc->tymed) == 0) return DV_E_TYMED; + + try { + return RenderDataTest(formatetc->cfFormat,formatetc->dwAspect,formatetc->lindex); + } FB2K_COM_CATCH; + } + + + HRESULT STDMETHODCALLTYPE GetCanonicalFormatEtc(FORMATETC * in, FORMATETC * out) { + //check this again + if (in == NULL || out == NULL) + return E_INVALIDARG; + *out = *in; + return DATA_S_SAMEFORMATETC; + } + + HRESULT STDMETHODCALLTYPE EnumFormatEtc(DWORD dwDirection,IEnumFORMATETC ** ppenumFormatetc) { + if (dwDirection == DATADIR_GET) { + if (ppenumFormatetc == NULL) return E_INVALIDARG; + return CreateIEnumFORMATETC(ppenumFormatetc); + } else if (dwDirection == DATADIR_SET) { + return E_NOTIMPL; + } else { + return E_INVALIDARG; + } + } + + HRESULT STDMETHODCALLTYPE SetData(FORMATETC * pFormatetc, STGMEDIUM * pmedium, BOOL fRelease) { + try { + ReleaseStgMediumScope relScope(fRelease ? pmedium : NULL); + if (pFormatetc == NULL || pmedium == NULL) return E_INVALIDARG; + + /*TCHAR buf[256]; + if (GetClipboardFormatName(pFormatetc->cfFormat,buf,PFC_TABSIZE(buf)) > 0) { + buf[PFC_TABSIZE(buf)-1] = 0; + OutputDebugString(TEXT("SetData: ")); OutputDebugString(buf); OutputDebugString(TEXT("\n")); + } else { + OutputDebugString(TEXT("SetData: unknown clipboard format.\n")); + }*/ + + pfc::array_t temp; + HRESULT state = STGMEDIUMToDataBlock(*pmedium,temp); + if (FAILED(state)) return state; + m_entries.set(*pFormatetc,temp); + return S_OK; + } FB2K_COM_CATCH; + } + HRESULT STDMETHODCALLTYPE DAdvise(FORMATETC * pFormatetc, DWORD advf, IAdviseSink * pAdvSink, DWORD * pdwConnection) {return OLE_E_ADVISENOTSUPPORTED;} + HRESULT STDMETHODCALLTYPE DUnadvise(DWORD dwConnection) {return OLE_E_ADVISENOTSUPPORTED;} + HRESULT STDMETHODCALLTYPE EnumDAdvise(IEnumSTATDATA ** ppenumAdvise) {return OLE_E_ADVISENOTSUPPORTED;} + protected: + virtual HRESULT RenderData(UINT format,DWORD aspect,LONG dataIndex,stream_writer_formatter<> & out) const { + FORMATETC fmt = {}; + fmt.cfFormat = format; fmt.dwAspect = aspect; fmt.lindex = dataIndex; + const pfc::array_t * entry = m_entries.query_ptr(fmt); + if (entry != NULL) { + out.write_raw(entry->get_ptr(), entry->get_size()); + return S_OK; + } + return DV_E_FORMATETC; + } + virtual HRESULT RenderDataTest(UINT format,DWORD aspect, LONG dataIndex) const { + FORMATETC fmt = {}; + fmt.cfFormat = format; fmt.dwAspect = aspect; fmt.lindex = dataIndex; + if (m_entries.have_item(fmt)) return S_OK; + return DV_E_FORMATETC; + } + typedef pfc::list_base_t TFormatList; + + static void AddFormat(TFormatList & out,UINT code) { + FORMATETC fmt = {}; + fmt.dwAspect = DVASPECT_CONTENT; + fmt.lindex = -1; + fmt.cfFormat = code; + for(t_size medWalk = 0; medWalk < 32; ++medWalk) { + const DWORD med = 1 << medWalk; + if ((DataBlockToSTGMEDIUM_SupportedTymeds & med) != 0) { + fmt.tymed = med; + out.add_item(fmt); + } + } + } + + virtual void EnumFormats(TFormatList & out) const { + pfc::avltree_t formats; + for(t_entries::const_iterator walk = m_entries.first(); walk.is_valid(); ++walk) { + formats.add_item( walk->m_key.cfFormat ); + } + for(pfc::const_iterator walk = formats.first(); walk.is_valid(); ++walk) { + AddFormat(out, *walk); + } + } + HRESULT CreateIEnumFORMATETC(IEnumFORMATETC ** outptr) const throw() { + try { + pfc::list_t out; + EnumFormats(out); + return SHCreateStdEnumFmtEtc((UINT)out.get_count(), out.get_ptr(), outptr); + } FB2K_COM_CATCH; + } + private: + HRESULT GetData_internal(FORMATETC * formatetc, STGMEDIUM * medium,bool bHere) { + if (formatetc == NULL || medium == NULL) return E_INVALIDARG; + + try { + stream_writer_formatter_simple<> out; + HRESULT hr = RenderData(formatetc->cfFormat,formatetc->dwAspect,formatetc->lindex,out); + if (FAILED(hr)) return hr; + return DataBlockToSTGMEDIUM(out.m_buffer.get_ptr(),out.m_buffer.get_size(),medium,formatetc->tymed,bHere); + } FB2K_COM_CATCH; + } + + typedef pfc::map_t, comparator_FORMATETC> t_entries; + t_entries m_entries; + }; +} + +#endif // _WIN32 diff --git a/SDK/foobar2000/helpers/ProcessUtils.h b/SDK/foobar2000/helpers/ProcessUtils.h new file mode 100644 index 0000000..7d0f71e --- /dev/null +++ b/SDK/foobar2000/helpers/ProcessUtils.h @@ -0,0 +1,275 @@ +#ifdef _WIN32 + +namespace ProcessUtils { + class PipeIO : public stream_reader, public stream_writer { + public: + PFC_DECLARE_EXCEPTION(timeout, exception_io, "Timeout"); + PipeIO(HANDLE handle, HANDLE hEvent, bool processMessages, DWORD timeOut = INFINITE) : m_handle(handle), m_event(hEvent), m_processMessages(processMessages), m_timeOut(timeOut) { + } + ~PipeIO() { + } + + void write(const void * p_buffer,size_t p_bytes, abort_callback & abort) { + if (p_bytes == 0) return; + OVERLAPPED ol = {}; + ol.hEvent = m_event; + ResetEvent(m_event); + DWORD bytesWritten; + SetLastError(NO_ERROR); + if (WriteFile( m_handle, p_buffer, pfc::downcast_guarded(p_bytes), &bytesWritten, &ol)) { + // succeeded already? + if (bytesWritten != p_bytes) throw exception_io(); + return; + } + + { + const DWORD code = GetLastError(); + if (code != ERROR_IO_PENDING) exception_io_from_win32(code); + } + const HANDLE handles[] = {m_event, abort.get_abort_event()}; + SetLastError(NO_ERROR); + DWORD state = myWait(_countof(handles), handles); + if (state == WAIT_OBJECT_0) { + try { + WIN32_IO_OP( GetOverlappedResult(m_handle,&ol,&bytesWritten,TRUE) ); + } catch(...) { + _cancel(ol); + throw; + } + if (bytesWritten != p_bytes) throw exception_io(); + return; + } + _cancel(ol); + abort.check(); + throw timeout(); + } + size_t read(void * p_buffer,size_t p_bytes, abort_callback & abort) { + uint8_t * ptr = (uint8_t*) p_buffer; + size_t done = 0; + while(done < p_bytes) { + abort.check(); + size_t delta = readPass(ptr + done, p_bytes - done, abort); + if (delta == 0) break; + done += delta; + } + return done; + } + size_t readPass(void * p_buffer,size_t p_bytes, abort_callback & abort) { + if (p_bytes == 0) return 0; + OVERLAPPED ol = {}; + ol.hEvent = m_event; + ResetEvent(m_event); + DWORD bytesDone; + SetLastError(NO_ERROR); + if (ReadFile( m_handle, p_buffer, pfc::downcast_guarded(p_bytes), &bytesDone, &ol)) { + // succeeded already? + return bytesDone; + } + + { + const DWORD code = GetLastError(); + switch(code) { + case ERROR_HANDLE_EOF: + return 0; + case ERROR_IO_PENDING: + break; // continue + default: + exception_io_from_win32(code); + }; + } + + const HANDLE handles[] = {m_event, abort.get_abort_event()}; + SetLastError(NO_ERROR); + DWORD state = myWait(_countof(handles), handles); + if (state == WAIT_OBJECT_0) { + SetLastError(NO_ERROR); + if (!GetOverlappedResult(m_handle,&ol,&bytesDone,TRUE)) { + const DWORD code = GetLastError(); + if (code == ERROR_HANDLE_EOF) bytesDone = 0; + else { + _cancel(ol); + exception_io_from_win32(code); + } + } + return bytesDone; + } + _cancel(ol); + abort.check(); + throw timeout(); + } + private: + DWORD myWait(DWORD count, const HANDLE * handles) { + if (m_processMessages) { + for(;;) { + DWORD state = MsgWaitForMultipleObjects(count, handles, FALSE, m_timeOut, QS_ALLINPUT); + if (state == WAIT_OBJECT_0 + count) { + ProcessPendingMessages(); + } else { + return state; + } + } + } else { + return WaitForMultipleObjects(count, handles, FALSE, m_timeOut); + } + } + void _cancel(OVERLAPPED & ol) { + #if _WIN32_WINNT >= 0x600 + CancelIoEx(m_handle,&ol); + #else + CancelIo(m_handle); + #endif + } + static void ProcessPendingMessages() { + MSG msg = {}; + while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) DispatchMessage(&msg); + } + + HANDLE m_handle; + HANDLE m_event; + const DWORD m_timeOut; + const bool m_processMessages; + }; + + class SubProcess : public stream_reader, public stream_writer { + public: + PFC_DECLARE_EXCEPTION(failure, std::exception, "Unexpected failure"); + + SubProcess(const char * exePath, DWORD timeOutMS = 60*1000) : ExePath(exePath), hStdIn(), hStdOut(), hProcess(), ProcessMessages(false), TimeOutMS(timeOutMS) { + HANDLE ev; + WIN32_OP( (ev = CreateEvent(NULL, TRUE, FALSE, NULL)) != NULL ); + hEventRead = ev; + WIN32_OP( (ev = CreateEvent(NULL, TRUE, FALSE, NULL)) != NULL ); + hEventWrite = ev; + Restart(); + } + void Restart() { + CleanUp(); + STARTUPINFO si = {}; + try { + si.cb = sizeof(si); + si.dwFlags = STARTF_USESTDHANDLES | STARTF_FORCEOFFFEEDBACK; + //si.wShowWindow = SW_HIDE; + + myCreatePipeOut(si.hStdInput, hStdIn); + myCreatePipeIn(hStdOut, si.hStdOutput); + si.hStdError = GetStdHandle(STD_ERROR_HANDLE); + + PROCESS_INFORMATION pi = {}; + try { + WIN32_OP( CreateProcess(pfc::stringcvt::string_os_from_utf8(ExePath), NULL, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi) ); + } catch(std::exception const & e) { + throw failure(pfc::string_formatter() << "Could not start the worker process - " << e); + } + hProcess = pi.hProcess; _Close(pi.hThread); + } catch(...) { + _Close(si.hStdInput); + _Close(si.hStdOutput); + CleanUp(); throw; + } + _Close(si.hStdInput); + _Close(si.hStdOutput); + } + ~SubProcess() { + CleanUp(); + CloseHandle(hEventRead); + CloseHandle(hEventWrite); + } + + bool IsRunning() const { + return hProcess != NULL; + } + void Detach() { + CleanUp(true); + } + bool ProcessMessages; + DWORD TimeOutMS; + + + void write(const void * p_buffer,size_t p_bytes, abort_callback & abort) { + PipeIO writer(hStdIn, hEventWrite, ProcessMessages, TimeOutMS); + writer.write(p_buffer, p_bytes, abort); + } + size_t read(void * p_buffer,size_t p_bytes, abort_callback & abort) { + PipeIO reader(hStdOut, hEventRead, ProcessMessages, TimeOutMS); + return reader.read(p_buffer, p_bytes, abort); + } + void SetPriority(DWORD val) { + SetPriorityClass(hProcess, val); + } + protected: + HANDLE hStdIn, hStdOut, hProcess, hEventRead, hEventWrite; + const pfc::string8 ExePath; + + void CleanUp(bool bDetach = false) { + _Close(hStdIn); _Close(hStdOut); + if (hProcess != NULL) { + if (!bDetach) { + if (WaitForSingleObject(hProcess, TimeOutMS) != WAIT_OBJECT_0) { + //PFC_ASSERT( !"Should not get here - worker stuck" ); + console::formatter() << pfc::string_filename_ext(ExePath) << " unresponsive - terminating"; + TerminateProcess(hProcess, -1); + } + } + _Close(hProcess); + } + } + private: + static void _Close(HANDLE & h) { + if (h != NULL) {CloseHandle(h); h = NULL;} + } + + static void myCreatePipe(HANDLE & in, HANDLE & out) { + SECURITY_ATTRIBUTES Attributes = { sizeof(SECURITY_ATTRIBUTES), 0, true }; + WIN32_OP( CreatePipe( &in, &out, &Attributes, 0 ) ); + } + + static pfc::string_formatter makePipeName() { + GUID id; + CoCreateGuid (&id); + return pfc::string_formatter() << "\\\\.\\pipe\\" << pfc::print_guid(id); + } + + static void myCreatePipeOut(HANDLE & in, HANDLE & out) { + SECURITY_ATTRIBUTES Attributes = { sizeof(SECURITY_ATTRIBUTES), 0, true }; + const pfc::stringcvt::string_os_from_utf8 pipeName( makePipeName() ); + SetLastError(NO_ERROR); + HANDLE pipe = CreateNamedPipe( + pipeName, + FILE_FLAG_FIRST_PIPE_INSTANCE | PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, + 1, + 1024*64, + 1024*64, + NMPWAIT_USE_DEFAULT_WAIT,&Attributes); + if (pipe == INVALID_HANDLE_VALUE) throw exception_win32(GetLastError()); + + in = CreateFile(pipeName,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&Attributes,OPEN_EXISTING,0,NULL); + DuplicateHandle ( GetCurrentProcess(), pipe, GetCurrentProcess(), &out, 0, FALSE, DUPLICATE_SAME_ACCESS ); + CloseHandle(pipe); + } + + static void myCreatePipeIn(HANDLE & in, HANDLE & out) { + SECURITY_ATTRIBUTES Attributes = { sizeof(SECURITY_ATTRIBUTES), 0, true }; + const pfc::stringcvt::string_os_from_utf8 pipeName( makePipeName() ); + SetLastError(NO_ERROR); + HANDLE pipe = CreateNamedPipe( + pipeName, + FILE_FLAG_FIRST_PIPE_INSTANCE | PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, + 1, + 1024*64, + 1024*64, + NMPWAIT_USE_DEFAULT_WAIT,&Attributes); + if (pipe == INVALID_HANDLE_VALUE) throw exception_win32(GetLastError()); + + out = CreateFile(pipeName,GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,&Attributes,OPEN_EXISTING,0,NULL); + DuplicateHandle ( GetCurrentProcess(), pipe, GetCurrentProcess(), &in, 0, FALSE, DUPLICATE_SAME_ACCESS ); + CloseHandle(pipe); + } + + PFC_CLASS_NOT_COPYABLE_EX(SubProcess) + }; +} + +#endif // _WIN32 + diff --git a/SDK/foobar2000/helpers/ProfileCache.h b/SDK/foobar2000/helpers/ProfileCache.h new file mode 100644 index 0000000..e76124a --- /dev/null +++ b/SDK/foobar2000/helpers/ProfileCache.h @@ -0,0 +1,44 @@ +namespace ProfileCache { + inline file::ptr FetchFile(const char * context, const char * name, const char * webURL, t_filetimestamp acceptableAge, abort_callback & abort) { + const double timeoutVal = 5; + + pfc::string_formatter path ( core_api::get_profile_path() ); + path.fix_dir_separator('\\'); + path << context; + try { + filesystem::g_create_directory(path, abort); + } catch(exception_io_already_exists) {} + path << "\\" << name; + + bool fetch = false; + file::ptr fLocal; + + try { + filesystem::g_open_timeout(fLocal, path, filesystem::open_mode_write_existing, timeoutVal, abort); + fetch = fLocal->get_timestamp(abort) < filetimestamp_from_system_timer() - acceptableAge; + } catch(exception_io_not_found) { + filesystem::g_open_timeout(fLocal, path, filesystem::open_mode_write_new, timeoutVal, abort); + fetch = true; + } + if (fetch) { + fLocal->resize(0, abort); + file::ptr fRemote; + try { + filesystem::g_open(fRemote, webURL, filesystem::open_mode_read, abort); + } catch(exception_io_not_found) { + fLocal.release(); + try { filesystem::g_remove_timeout(path, timeoutVal, abort); } catch(...) {} + throw; + } + pfc::array_t buffer; buffer.set_size(64*1024); + for(;;) { + t_size delta = buffer.get_size(); + delta = fRemote->read(buffer.get_ptr(), delta, abort); + fLocal->write(buffer.get_ptr(), delta, abort); + if (delta < buffer.get_size()) break; + } + fLocal->seek(0, abort); + } + return fLocal; + } +}; diff --git a/SDK/foobar2000/helpers/StdAfx.cpp b/SDK/foobar2000/helpers/StdAfx.cpp new file mode 100644 index 0000000..095ce4d --- /dev/null +++ b/SDK/foobar2000/helpers/StdAfx.cpp @@ -0,0 +1,6 @@ +// stdafx.cpp : source file that includes just the standard includes +// foobar2000_sdk_helpers.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + diff --git a/SDK/foobar2000/helpers/StdAfx.h b/SDK/foobar2000/helpers/StdAfx.h new file mode 100644 index 0000000..1ef0bfe --- /dev/null +++ b/SDK/foobar2000/helpers/StdAfx.h @@ -0,0 +1,22 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#if !defined(AFX_STDAFX_H__6356EC2B_6DD1_4BE8_935C_87ECBA8697E4__INCLUDED_) +#define AFX_STDAFX_H__6356EC2B_6DD1_4BE8_935C_87ECBA8697E4__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + + +#include "../SDK/foobar2000.h" +#include "helpers.h" + +// TODO: reference additional headers your program requires here + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_STDAFX_H__6356EC2B_6DD1_4BE8_935C_87ECBA8697E4__INCLUDED_) diff --git a/SDK/foobar2000/helpers/ThreadUtils.h b/SDK/foobar2000/helpers/ThreadUtils.h new file mode 100644 index 0000000..d4b0308 --- /dev/null +++ b/SDK/foobar2000/helpers/ThreadUtils.h @@ -0,0 +1,263 @@ +namespace ThreadUtils { + static bool WaitAbortable(HANDLE ev, abort_callback & abort, DWORD timeout = INFINITE) { + const HANDLE handles[2] = {ev, abort.get_abort_event()}; + SetLastError(0); + const DWORD status = WaitForMultipleObjects(2, handles, FALSE, timeout); + switch(status) { + case WAIT_TIMEOUT: + PFC_ASSERT( timeout != INFINITE ); + return false; + case WAIT_OBJECT_0: + return true; + case WAIT_OBJECT_0 + 1: + throw exception_aborted(); + case WAIT_FAILED: + WIN32_OP_FAIL(); + default: + uBugCheck(); + } + } + + static void ProcessPendingMessages() { + MSG msg = {}; + while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { + DispatchMessage(&msg); + } + } + + + static void WaitAbortable_MsgLoop(HANDLE ev, abort_callback & abort) { + const HANDLE handles[2] = {ev, abort.get_abort_event()}; + for(;;) { + SetLastError(0); + const DWORD status = MsgWaitForMultipleObjects(2, handles, FALSE, INFINITE, QS_ALLINPUT); + switch(status) { + case WAIT_TIMEOUT: + PFC_ASSERT(!"How did we get here?"); + uBugCheck(); + case WAIT_OBJECT_0: + return; + case WAIT_OBJECT_0 + 1: + throw exception_aborted(); + case WAIT_OBJECT_0 + 2: + ProcessPendingMessages(); + break; + case WAIT_FAILED: + WIN32_OP_FAIL(); + default: + uBugCheck(); + } + } + } + + static t_size MultiWaitAbortable_MsgLoop(const HANDLE * ev, t_size evCount, abort_callback & abort) { + pfc::array_t handles; handles.set_size(evCount + 1); + handles[0] = abort.get_abort_event(); + pfc::memcpy_t(handles.get_ptr() + 1, ev, evCount); + for(;;) { + SetLastError(0); + const DWORD status = MsgWaitForMultipleObjects(handles.get_count(), handles.get_ptr(), FALSE, INFINITE, QS_ALLINPUT); + switch(status) { + case WAIT_TIMEOUT: + PFC_ASSERT(!"How did we get here?"); + uBugCheck(); + case WAIT_OBJECT_0: + throw exception_aborted(); + case WAIT_FAILED: + WIN32_OP_FAIL(); + default: + { + t_size index = (t_size)(status - (WAIT_OBJECT_0 + 1)); + if (index == evCount) { + ProcessPendingMessages(); + } else if (index < evCount) { + return index; + } else { + uBugCheck(); + } + } + } + } + } + + static void SleepAbortable_MsgLoop(abort_callback & abort, DWORD timeout /*must not be INFINITE*/) { + PFC_ASSERT( timeout != INFINITE ); + const DWORD entry = GetTickCount(); + const HANDLE handles[1] = {abort.get_abort_event()}; + for(;;) { + const DWORD done = GetTickCount() - entry; + if (done >= timeout) return; + SetLastError(0); + const DWORD status = MsgWaitForMultipleObjects(1, handles, FALSE, timeout - done, QS_ALLINPUT); + switch(status) { + case WAIT_TIMEOUT: + return; + case WAIT_OBJECT_0: + throw exception_aborted(); + case WAIT_OBJECT_0 + 1: + ProcessPendingMessages(); + default: + throw exception_win32(GetLastError()); + } + } + } + + static bool WaitAbortable_MsgLoop(HANDLE ev, abort_callback & abort, DWORD timeout /*must not be INFINITE*/) { + PFC_ASSERT( timeout != INFINITE ); + const DWORD entry = GetTickCount(); + const HANDLE handles[2] = {ev, abort.get_abort_event()}; + for(;;) { + const DWORD done = GetTickCount() - entry; + if (done >= timeout) return false; + SetLastError(0); + const DWORD status = MsgWaitForMultipleObjects(2, handles, FALSE, timeout - done, QS_ALLINPUT); + switch(status) { + case WAIT_TIMEOUT: + return false; + case WAIT_OBJECT_0: + return true; + case WAIT_OBJECT_0 + 1: + throw exception_aborted(); + case WAIT_OBJECT_0 + 2: + ProcessPendingMessages(); + break; + case WAIT_FAILED: + WIN32_OP_FAIL(); + default: + uBugCheck(); + } + } + } + + template + class CObjectQueue { + public: + CObjectQueue() { m_event.create(true,false); } + + template void Add(const TSource & source) { + insync(m_sync); + m_content.add_item(source); + if (m_content.get_count() == 1) m_event.set_state(true); + } + template void Get(TDestination & out, abort_callback & abort) { + WaitAbortable(m_event.get(), abort); + _Get(out); + } + + template void Get_MsgLoop(TDestination & out, abort_callback & abort) { + WaitAbortable_MsgLoop(m_event.get(), abort); + _Get(out); + } + + private: + template void _Get(TDestination & out) { + insync(m_sync); + pfc::const_iterator iter = m_content.first(); + FB2K_DYNAMIC_ASSERT( iter.is_valid() ); + out = *iter; + m_content.remove(iter); + if (m_content.get_count() == 0) m_event.set_state(false); + } + win32_event m_event; + critical_section m_sync; + pfc::chain_list_v2_t m_content; + }; + + + template + class CSingleThreadWrapper : protected CVerySimpleThread { + private: + enum status { + success, + fail, + fail_io, + fail_io_data, + fail_abort, + }; + protected: + class command { + protected: + command() : m_status(success), m_abort(), m_completionEvent() {} + virtual void executeImpl(TBase &) {} + virtual ~command() {} + public: + void execute(TBase & obj) { + try { + executeImpl(obj); + m_status = success; + } catch(exception_aborted const & e) { + m_status = fail_abort; m_statusMsg = e.what(); + } catch(exception_io_data const & e) { + m_status = fail_io_data; m_statusMsg = e.what(); + } catch(exception_io const & e) { + m_status = fail_io; m_statusMsg = e.what(); + } catch(std::exception const & e) { + m_status = fail; m_statusMsg = e.what(); + } + SetEvent(m_completionEvent); + } + void rethrow() const { + switch(m_status) { + case fail: + throw pfc::exception(m_statusMsg); + case fail_io: + throw exception_io(m_statusMsg); + case fail_io_data: + throw exception_io_data(m_statusMsg); + case fail_abort: + throw exception_aborted(); + case success: + break; + default: + uBugCheck(); + } + } + status m_status; + pfc::string8 m_statusMsg; + HANDLE m_completionEvent; + abort_callback * m_abort; + }; + + typedef pfc::rcptr_t command_ptr; + + CSingleThreadWrapper() { + m_completionEvent.create(true,false); + this->StartThread(); + //start(); + } + + ~CSingleThreadWrapper() { + m_threadAbort.abort(); + this->WaitTillThreadDone(); + } + + void invokeCommand(command_ptr cmd, abort_callback & abort) { + abort.check(); + m_completionEvent.set_state(false); + pfc::vartoggle_t abortToggle(cmd->m_abort, &abort); + pfc::vartoggle_t eventToggle(cmd->m_completionEvent, m_completionEvent.get() ); + m_commands.Add(cmd); + m_completionEvent.wait_for(-1); + //WaitAbortable(m_completionEvent.get(), abort); + cmd->rethrow(); + } + + private: + void ThreadProc() { + TRACK_CALL_TEXT("CSingleThreadWrapper entry"); + try { + TBase instance; + for(;;) { + command_ptr cmd; + if (processMsgs) m_commands.Get_MsgLoop(cmd, m_threadAbort); + else m_commands.Get(cmd, m_threadAbort); + cmd->execute(instance); + } + } catch(...) {} + if (processMsgs) ProcessPendingMessages(); + } + win32_event m_completionEvent; + CObjectQueue m_commands; + abort_callback_impl m_threadAbort; + }; +} diff --git a/SDK/foobar2000/helpers/VisUtils.cpp b/SDK/foobar2000/helpers/VisUtils.cpp new file mode 100644 index 0000000..237c166 --- /dev/null +++ b/SDK/foobar2000/helpers/VisUtils.cpp @@ -0,0 +1,36 @@ +#include "stdafx.h" + +namespace VisUtils { + void PrepareFFTChunk(audio_chunk const & source, audio_chunk & out, double centerOffset) { + const t_uint32 channels = source.get_channel_count(); + const t_uint32 sampleRate = source.get_sample_rate(); + FB2K_DYNAMIC_ASSERT( sampleRate > 0 ); + out.set_channels(channels, source.get_channel_config()); + out.set_sample_rate(sampleRate); + const t_size inSize = source.get_sample_count(); + const t_size fftSize = MatchFFTSize(inSize); + out.set_sample_count(fftSize); + out.set_data_size(fftSize * channels); + if (fftSize >= inSize) { //rare case with *REALLY* small input + pfc::memcpy_t( out.get_data(), source.get_data(), inSize * channels ); + pfc::memset_null_t( out.get_data() + inSize * channels, (fftSize - inSize) * channels ); + } else { //inSize > fftSize, we're using a subset of source chunk for the job, pick a subset around centerOffset. + const double baseOffset = pfc::max_t(0, centerOffset - 0.5 * (double)fftSize / (double)sampleRate); + const t_size baseSample = pfc::min_t( (t_size) audio_math::time_to_samples(baseOffset, sampleRate), inSize - fftSize); + pfc::memcpy_t( out.get_data(), source.get_data() + baseSample * channels, fftSize * channels); + } + } + + bool IsValidFFTSize(t_size p_size) { + return p_size >= 2 && (p_size & (p_size - 1)) == 0; + } + + t_size MatchFFTSize(t_size samples) { + if (samples <= 2) return 2; + t_size mask = 1; + while(!IsValidFFTSize(samples)) { + samples &= ~mask; mask <<= 1; + } + return samples; + } +}; diff --git a/SDK/foobar2000/helpers/VisUtils.h b/SDK/foobar2000/helpers/VisUtils.h new file mode 100644 index 0000000..15654b2 --- /dev/null +++ b/SDK/foobar2000/helpers/VisUtils.h @@ -0,0 +1,8 @@ +namespace VisUtils { + //! Turns an arbitrary audio_chunk into a valid chunk to run FFT on, with proper sample count etc. + //! @param centerOffset Time offset (in seconds) inside the source chunk to center the output on, in case the FFT window is smaller than input data. + void PrepareFFTChunk(audio_chunk const & source, audio_chunk & out, double centerOffset); + + bool IsValidFFTSize(t_size size); + t_size MatchFFTSize(t_size samples); +}; diff --git a/SDK/foobar2000/helpers/bitreader_helper.h b/SDK/foobar2000/helpers/bitreader_helper.h new file mode 100644 index 0000000..3a5e152 --- /dev/null +++ b/SDK/foobar2000/helpers/bitreader_helper.h @@ -0,0 +1,122 @@ +namespace bitreader_helper { + + inline static size_t extract_bit(const t_uint8 * p_stream,size_t p_offset) { + return (p_stream[p_offset>>3] >> (7-(p_offset&7)))&1; + } + + inline static size_t extract_int(const t_uint8 * p_stream,size_t p_base,size_t p_width) { + size_t ret = 0; + size_t offset = p_base; + for(size_t bit=0;bit + t_ret read_t(t_size p_bits) { + t_ret ret = 0; + for(t_size bit=0;bit>3] >> (7-(m_bitptr&7)))&1; + m_bitptr++; + } + return ret; + } + + t_size read(t_size p_bits) {return read_t(p_bits);} + + inline t_size get_bitptr() const {return m_bitptr;} + + inline bool read_bit() { + bool state = ( (m_ptr[m_bitptr>>3] >> (7-(m_bitptr&7)))&1 ) != 0; + m_bitptr++; + return state; + } + +private: + + const t_uint8 * m_ptr; + t_size m_bitptr; +}; + +class bitreader_fromfile +{ +public: + inline bitreader_fromfile(service_ptr_t const& p_file) : m_file(p_file), m_buffer_ptr(0) {} + + t_size read(t_size p_bits,abort_callback & p_abort) { + t_size ret = 0; + for(t_size bit=0;bitread_object(&m_buffer,1,p_abort); + + ret <<= 1; + ret |= (m_buffer >> (7-m_buffer_ptr))&1; + m_buffer_ptr = (m_buffer_ptr+1) & 7; + } + return ret; + } + + void skip(t_size p_bits,abort_callback & p_abort) { + for(t_size bit=0;bitread_object(&m_buffer,1,p_abort); + m_buffer_ptr = (m_buffer_ptr+1) & 7; + } + } + + inline void byte_align() {m_buffer_ptr = 0;} + +private: + service_ptr_t m_file; + t_size m_buffer_ptr; + t_uint8 m_buffer; +}; + +class bitreader_limited +{ +public: + inline bitreader_limited(const t_uint8 * p_ptr,t_size p_base,t_size p_remaining) : m_reader(p_ptr,p_base), m_remaining(p_remaining) {} + + inline t_size get_bitptr() const {return m_reader.get_bitptr();} + + inline t_size get_remaining() const {return m_remaining;} + + inline void skip(t_size p_bits) { + if (p_bits > m_remaining) throw exception_io_data_truncation(); + m_remaining -= p_bits; + m_reader.skip(p_bits); + } + + t_size read(t_size p_bits) + { + if (p_bits > m_remaining) throw exception_io_data_truncation(); + m_remaining -= p_bits; + return m_reader.read(p_bits); + } + +private: + bitreader m_reader; + t_size m_remaining; +}; + +inline static t_size extract_bits(const t_uint8 * p_buffer,t_size p_base,t_size p_count) { + return bitreader(p_buffer,p_base).read(p_count); +} + +} \ No newline at end of file diff --git a/SDK/foobar2000/helpers/cfg_guidlist.h b/SDK/foobar2000/helpers/cfg_guidlist.h new file mode 100644 index 0000000..b12a6d5 --- /dev/null +++ b/SDK/foobar2000/helpers/cfg_guidlist.h @@ -0,0 +1,29 @@ +class cfg_guidlist : public cfg_var, public pfc::list_t +{ +public: + void get_data_raw(stream_writer * p_stream,abort_callback & p_abort) { + t_uint32 n, m = pfc::downcast_guarded(get_count()); + p_stream->write_lendian_t(m,p_abort); + for(n=0;nwrite_lendian_t(get_item(n),p_abort); + } + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) { + t_uint32 n,count; + p_stream->read_lendian_t(count,p_abort); + m_buffer.set_size(count); + for(n=0;nread_lendian_t(m_buffer[n],p_abort); + } catch(...) {m_buffer.set_size(0); throw;} + } + } + + void sort() {sort_t(pfc::guid_compare);} + + bool have_item_bsearch(const GUID & p_item) { + t_size dummy; + return bsearch_t(pfc::guid_compare,p_item,dummy); + } + +public: + cfg_guidlist(const GUID & p_guid) : cfg_var(p_guid) {} +}; diff --git a/SDK/foobar2000/helpers/clipboard.cpp b/SDK/foobar2000/helpers/clipboard.cpp new file mode 100644 index 0000000..f4f9987 --- /dev/null +++ b/SDK/foobar2000/helpers/clipboard.cpp @@ -0,0 +1,41 @@ +#include "stdafx.h" + +#ifdef _WIN32 + +#ifdef UNICODE +#define CF_TCHAR CF_UNICODETEXT +#else +#define CF_TCHAR CF_TEXT +#endif + +namespace ClipboardHelper { + void SetRaw(UINT format,const void * data, t_size size) { + HANDLE buffer = GlobalAlloc(GMEM_DDESHARE,size); + if (buffer == NULL) throw std::bad_alloc(); + try { + CGlobalLockScope lock(buffer); + PFC_ASSERT(lock.GetSize() == size); + memcpy(lock.GetPtr(),data,size); + } catch(...) { + GlobalFree(buffer); throw; + } + + WIN32_OP(SetClipboardData(format,buffer) != NULL); + } + void SetString(const char * in) { + pfc::stringcvt::string_os_from_utf8 temp(in); + SetRaw(CF_TCHAR,temp.get_ptr(),(temp.length() + 1) * sizeof(TCHAR)); + } + + bool GetString(pfc::string_base & out) { + pfc::array_t temp; + if (!GetRaw(CF_TCHAR,temp)) return false; + out = pfc::stringcvt::string_utf8_from_os(reinterpret_cast(temp.get_ptr()),temp.get_size() / sizeof(TCHAR)); + return true; + } + bool IsTextAvailable() { + return IsClipboardFormatAvailable(CF_TCHAR) == TRUE; + } +} + +#endif // _WIN32 diff --git a/SDK/foobar2000/helpers/clipboard.h b/SDK/foobar2000/helpers/clipboard.h new file mode 100644 index 0000000..ddfa56c --- /dev/null +++ b/SDK/foobar2000/helpers/clipboard.h @@ -0,0 +1,42 @@ +#ifdef _WIN32 +namespace ClipboardHelper { + + class OpenScope { + public: + OpenScope() : m_open(false) {} + ~OpenScope() {Close();} + void Open(HWND p_owner) { + Close(); + WIN32_OP(OpenClipboard(p_owner)); + m_open = true; + } + void Close() { + if (m_open) { + m_open = false; + CloseClipboard(); + } + } + private: + bool m_open; + + PFC_CLASS_NOT_COPYABLE_EX(OpenScope) + }; + + void SetRaw(UINT format,const void * buffer, t_size size); + void SetString(const char * in); + + bool GetString(pfc::string_base & out); + + template + bool GetRaw(UINT format,TArray & out) { + pfc::assert_byte_type(); + HANDLE data = GetClipboardData(format); + if (data == NULL) return false; + CGlobalLockScope lock(data); + out.set_size( lock.GetSize() ); + memcpy(out.get_ptr(), lock.GetPtr(), lock.GetSize() ); + return true; + } + bool IsTextAvailable(); +}; +#endif // _WIN32 diff --git a/SDK/foobar2000/helpers/create_directory_helper.cpp b/SDK/foobar2000/helpers/create_directory_helper.cpp new file mode 100644 index 0000000..9d2c660 --- /dev/null +++ b/SDK/foobar2000/helpers/create_directory_helper.cpp @@ -0,0 +1,168 @@ +#include "stdafx.h" + +namespace create_directory_helper +{ + static void create_path_internal(const char * p_path,t_size p_base,abort_callback & p_abort) { + pfc::string8_fastalloc temp; + for(t_size walk = p_base; p_path[walk]; walk++) { + if (p_path[walk] == '\\') { + temp.set_string(p_path,walk); + try {filesystem::g_create_directory(temp.get_ptr(),p_abort);} catch(exception_io_already_exists) {} + } + } + } + + static bool is_valid_netpath_char(char p_char) { + return pfc::char_is_ascii_alphanumeric(p_char) || p_char == '_' || p_char == '-' || p_char == '.'; + } + + static bool test_localpath(const char * p_path) { + if (pfc::strcmp_partial(p_path,"file://") == 0) p_path += strlen("file://"); + return pfc::char_is_ascii_alpha(p_path[0]) && + p_path[1] == ':' && + p_path[2] == '\\'; + } + static bool test_netpath(const char * p_path) { + if (pfc::strcmp_partial(p_path,"file://") == 0) p_path += strlen("file://"); + if (*p_path != '\\') return false; + p_path++; + if (*p_path != '\\') return false; + p_path++; + if (!is_valid_netpath_char(*p_path)) return false; + p_path++; + while(is_valid_netpath_char(*p_path)) p_path++; + if (*p_path != '\\') return false; + return true; + } + + void create_path(const char * p_path,abort_callback & p_abort) { + if (test_localpath(p_path)) { + t_size walk = 0; + if (pfc::strcmp_partial(p_path,"file://") == 0) walk += strlen("file://"); + create_path_internal(p_path,walk + 3,p_abort); + } else if (test_netpath(p_path)) { + t_size walk = 0; + if (pfc::strcmp_partial(p_path,"file://") == 0) walk += strlen("file://"); + while(p_path[walk] == '\\') walk++; + while(p_path[walk] != 0 && p_path[walk] != '\\') walk++; + while(p_path[walk] == '\\') walk++; + while(p_path[walk] != 0 && p_path[walk] != '\\') walk++; + while(p_path[walk] == '\\') walk++; + create_path_internal(p_path,walk,p_abort); + } else { + pfc::throw_exception_with_message< exception_io > ("Could not create directory structure; unknown path format"); + } + } + +#ifdef _WIN32 + static bool is_bad_dirchar(char c) + { + return c==' ' || c=='.'; + } +#endif + + void make_path(const char * parent,const char * filename,const char * extension,bool allow_new_dirs,pfc::string8 & out,bool really_create_dirs,abort_callback & p_abort) + { + out.reset(); + if (parent && *parent) + { + out = parent; + out.fix_dir_separator('\\'); + } + bool last_char_is_dir_sep = true; + while(*filename) + { +#ifdef WIN32 + if (allow_new_dirs && is_bad_dirchar(*filename)) + { + const char * ptr = filename+1; + while(is_bad_dirchar(*ptr)) ptr++; + if (*ptr!='\\' && *ptr!='/') out.add_string(filename,ptr-filename); + filename = ptr; + if (*filename==0) break; + } +#endif + if (pfc::is_path_bad_char(*filename)) + { + if (allow_new_dirs && (*filename=='\\' || *filename=='/')) + { + if (!last_char_is_dir_sep) + { + if (really_create_dirs) try{filesystem::g_create_directory(out,p_abort);}catch(exception_io_already_exists){} + out.add_char('\\'); + last_char_is_dir_sep = true; + } + } + else + out.add_char('_'); + } + else + { + out.add_byte(*filename); + last_char_is_dir_sep = false; + } + filename++; + } + if (out.length()>0 && out[out.length()-1]=='\\') + { + out.add_string("noname"); + } + if (extension && *extension) + { + out.add_char('.'); + out.add_string(extension); + } + } +} + +pfc::string create_directory_helper::sanitize_formatted_path(pfc::stringp formatted, bool allowWC) { + pfc::string out; + t_size curSegBase = 0; + for(t_size walk = 0; ; ++walk) { + const char c = formatted[walk]; + if (c == 0 || pfc::io::path::isSeparator(c)) { + if (curSegBase < walk) { + pfc::string seg( formatted + curSegBase, walk - curSegBase ); + out = pfc::io::path::combine(out, pfc::io::path::validateFileName(seg, allowWC)); + } + if (c == 0) break; + curSegBase = walk + 1; + } + } + return out; +}; + +void create_directory_helper::format_filename_ex(const metadb_handle_ptr & handle,titleformat_hook * p_hook,titleformat_object::ptr spec,const char * suffix, pfc::string_base & out) { + pfc::string_formatter formatted; + titleformat_text_filter_myimpl filter; + handle->format_title(p_hook,formatted,spec,&filter); + formatted << suffix; + out = sanitize_formatted_path(formatted).ptr(); +} +void create_directory_helper::format_filename(const metadb_handle_ptr & handle,titleformat_hook * p_hook,titleformat_object::ptr spec,pfc::string_base & out) { + format_filename_ex(handle, p_hook, spec, "", out); +} +void create_directory_helper::format_filename(const metadb_handle_ptr & handle,titleformat_hook * p_hook,const char * spec,pfc::string_base & out) +{ + service_ptr_t script; + if (static_api_ptr_t()->compile(script,spec)) { + format_filename(handle, p_hook, script, out); + } else { + out.reset(); + } +} + +void create_directory_helper::titleformat_text_filter_myimpl::write(const GUID & p_inputType,pfc::string_receiver & p_out,const char * p_data,t_size p_dataLength) { + if (p_inputType == titleformat_inputtypes::meta) { + pfc::string_formatter temp; + for(t_size walk = 0; walk < p_dataLength; ++walk) { + char c = p_data[walk]; + if (c == 0) break; + if (pfc::io::path::isSeparator(c)) { + c = '-'; + } + temp.add_byte(c); + } + p_out.add_string(temp); + } else p_out.add_string(p_data,p_dataLength); +} diff --git a/SDK/foobar2000/helpers/create_directory_helper.h b/SDK/foobar2000/helpers/create_directory_helper.h new file mode 100644 index 0000000..0fe5954 --- /dev/null +++ b/SDK/foobar2000/helpers/create_directory_helper.h @@ -0,0 +1,20 @@ +#ifndef _CREATE_DIRECTORY_HELPER_H_ +#define _CREATE_DIRECTORY_HELPER_H_ + +namespace create_directory_helper { + void create_path(const char * p_path,abort_callback & p_abort); + void make_path(const char * parent,const char * filename,const char * extension,bool allow_new_dirs,pfc::string8 & out,bool b_really_create_dirs,abort_callback & p_dir_create_abort); + void format_filename(const metadb_handle_ptr & handle,titleformat_hook * p_hook,const char * spec,pfc::string_base & out); + void format_filename(const metadb_handle_ptr & handle,titleformat_hook * p_hook,titleformat_object::ptr spec,pfc::string_base & out); + void format_filename_ex(const metadb_handle_ptr & handle,titleformat_hook * p_hook,titleformat_object::ptr spec,const char * suffix, pfc::string_base & out); + + pfc::string sanitize_formatted_path(pfc::stringp str, bool allowWC = false); + + class titleformat_text_filter_myimpl : public titleformat_text_filter { + public: + void write(const GUID & p_inputType,pfc::string_receiver & p_out,const char * p_data,t_size p_dataLength); + }; + +}; + +#endif//_CREATE_DIRECTORY_HELPER_H_ \ No newline at end of file diff --git a/SDK/foobar2000/helpers/cue_creator.cpp b/SDK/foobar2000/helpers/cue_creator.cpp new file mode 100644 index 0000000..fc2d92c --- /dev/null +++ b/SDK/foobar2000/helpers/cue_creator.cpp @@ -0,0 +1,177 @@ +#include "stdafx.h" + + +namespace { + + class format_meta + { + public: + format_meta(const file_info & p_source,const char * p_name,bool p_allow_space = true) + { + p_source.meta_format(p_name,m_buffer); + m_buffer.replace_byte('\"','\''); + uReplaceString(m_buffer,pfc::string8(m_buffer),pfc_infinite,"\x0d\x0a",2,"\\",1,false); + if (!p_allow_space) m_buffer.replace_byte(' ','_'); + m_buffer.replace_nontext_chars(); + } + inline operator const char*() const {return m_buffer;} + private: + pfc::string8_fastalloc m_buffer; + }; +} + +static bool is_meta_same_everywhere(const cue_creator::t_entry_list & p_list,const char * p_meta) +{ + pfc::string8_fastalloc reference,temp; + + cue_creator::t_entry_list::const_iterator iter; + iter = p_list.first(); + if (!iter.is_valid()) return false; + if (!iter->m_infos.meta_format(p_meta,reference)) return false; + for(;iter.is_valid();++iter) + { + if (!iter->m_infos.meta_format(p_meta,temp)) return false; + if (strcmp(temp,reference)!=0) return false; + } + return true; +} + +static const char g_eol[] = "\r\n"; + + +namespace cue_creator +{ + void create(pfc::string_formatter & p_out,const t_entry_list & p_data) + { + if (p_data.get_count() == 0) return; + bool album_artist_global = is_meta_same_everywhere(p_data,"album artist"), + artist_global = is_meta_same_everywhere(p_data,"artist"), + album_global = is_meta_same_everywhere(p_data,"album"), + genre_global = is_meta_same_everywhere(p_data,"genre"), + date_global = is_meta_same_everywhere(p_data,"date"), + discid_global = is_meta_same_everywhere(p_data,"discid"), + comment_global = is_meta_same_everywhere(p_data,"comment"), + catalog_global = is_meta_same_everywhere(p_data,"catalog"), + songwriter_global = is_meta_same_everywhere(p_data,"songwriter"); + + if (genre_global) { + p_out << "REM GENRE " << format_meta(p_data.first()->m_infos,"genre") << g_eol; + } + if (date_global) { + p_out << "REM DATE " << format_meta(p_data.first()->m_infos,"date") << g_eol; + } + if (discid_global) { + p_out << "REM DISCID " << format_meta(p_data.first()->m_infos,"discid") << g_eol; + } + if (comment_global) { + p_out << "REM COMMENT " << format_meta(p_data.first()->m_infos,"comment") << g_eol; + } + if (catalog_global) { + p_out << "CATALOG " << format_meta(p_data.first()->m_infos,"catalog") << g_eol; + } + if (songwriter_global) { + p_out << "SONGWRITER \"" << format_meta(p_data.first()->m_infos,"songwriter") << "\"" << g_eol; + } + + if (album_artist_global) + { + p_out << "PERFORMER \"" << format_meta(p_data.first()->m_infos,"album artist") << "\"" << g_eol; + artist_global = false; + } + else if (artist_global) + { + p_out << "PERFORMER \"" << format_meta(p_data.first()->m_infos,"artist") << "\"" << g_eol; + } + if (album_global) + { + p_out << "TITLE \"" << format_meta(p_data.first()->m_infos,"album") << "\"" << g_eol; + } + + { + replaygain_info::t_text_buffer rgbuffer; + replaygain_info rg = p_data.first()->m_infos.get_replaygain(); + if (rg.format_album_gain(rgbuffer)) + p_out << "REM REPLAYGAIN_ALBUM_GAIN " << rgbuffer << g_eol; + if (rg.format_album_peak(rgbuffer)) + p_out << "REM REPLAYGAIN_ALBUM_PEAK " << rgbuffer << g_eol; + } + + pfc::string8 last_file; + + for(t_entry_list::const_iterator iter = p_data.first();iter.is_valid();++iter) + { + if (strcmp(last_file,iter->m_file) != 0) + { + p_out << "FILE \"" << iter->m_file << "\" WAVE" << g_eol; + last_file = iter->m_file; + } + + p_out << " TRACK " << pfc::format_int(iter->m_track_number,2) << " AUDIO" << g_eol; + + if (iter->m_infos.meta_find("title") != pfc_infinite) + p_out << " TITLE \"" << format_meta(iter->m_infos,"title") << "\"" << g_eol; + + if (!artist_global && iter->m_infos.meta_find("artist") != pfc_infinite) + p_out << " PERFORMER \"" << format_meta(iter->m_infos,"artist") << "\"" << g_eol; + + if (!songwriter_global && iter->m_infos.meta_find("songwriter") != pfc_infinite) { + p_out << " SONGWRITER \"" << format_meta(iter->m_infos,"songwriter") << "\"" << g_eol; + } + + if (iter->m_infos.meta_find("isrc") != pfc_infinite) { + p_out << " ISRC " << format_meta(iter->m_infos,"isrc") << g_eol; + } + + if (!date_global && iter->m_infos.meta_find("date") != pfc_infinite) { + p_out << " REM DATE " << format_meta(iter->m_infos,"date") << g_eol; + } + + + + { + replaygain_info::t_text_buffer rgbuffer; + replaygain_info rg = iter->m_infos.get_replaygain(); + if (rg.format_track_gain(rgbuffer)) + p_out << " REM REPLAYGAIN_TRACK_GAIN " << rgbuffer << g_eol; + if (rg.format_track_peak(rgbuffer)) + p_out << " REM REPLAYGAIN_TRACK_PEAK " << rgbuffer << g_eol; + } + + if (!iter->m_flags.is_empty()) { + p_out << " FLAGS " << iter->m_flags << g_eol; + } + + if (iter->m_index_list.m_positions[0] < iter->m_index_list.m_positions[1]) + { + if (iter->m_index_list.m_positions[0] < 0) + p_out << " PREGAP " << cuesheet_format_index_time(iter->m_index_list.m_positions[1] - iter->m_index_list.m_positions[0]) << g_eol; + else + p_out << " INDEX 00 " << cuesheet_format_index_time(iter->m_index_list.m_positions[0]) << g_eol; + } + + p_out << " INDEX 01 " << cuesheet_format_index_time(iter->m_index_list.m_positions[1]) << g_eol; + + for(unsigned n=2;nm_index_list.m_positions[n] > 0;n++) + { + p_out << " INDEX " << pfc::format_uint(n,2) << " " << cuesheet_format_index_time(iter->m_index_list.m_positions[n]) << g_eol; + } + + // p_out << " INDEX 01 " << cuesheet_format_index_time(iter->m_offset) << g_eol; + } + } + + + void t_entry::set_simple_index(double p_time) + { + m_index_list.reset(); + m_index_list.m_positions[0] = m_index_list.m_positions[1] = p_time; + } + void t_entry::set_index01(double index0, double index1) { + PFC_ASSERT( index0 <= index1 ); + m_index_list.reset(); + m_index_list.m_positions[0] = index0; + m_index_list.m_positions[1] = index1; + } + +} + diff --git a/SDK/foobar2000/helpers/cue_creator.h b/SDK/foobar2000/helpers/cue_creator.h new file mode 100644 index 0000000..397fd4f --- /dev/null +++ b/SDK/foobar2000/helpers/cue_creator.h @@ -0,0 +1,18 @@ +namespace cue_creator +{ + struct t_entry + { + file_info_impl m_infos; + pfc::string8 m_file,m_flags; + unsigned m_track_number; + + t_cuesheet_index_list m_index_list; + + void set_simple_index(double p_time); + void set_index01(double index0, double index1); + }; + + typedef pfc::chain_list_v2_t t_entry_list; + + void create(pfc::string_formatter & p_out,const t_entry_list & p_list); +}; \ No newline at end of file diff --git a/SDK/foobar2000/helpers/cue_parser.cpp b/SDK/foobar2000/helpers/cue_parser.cpp new file mode 100644 index 0000000..682d342 --- /dev/null +++ b/SDK/foobar2000/helpers/cue_parser.cpp @@ -0,0 +1,764 @@ +#include "stdafx.h" + +namespace { + PFC_DECLARE_EXCEPTION(exception_cue,pfc::exception,"Invalid cuesheet"); +} + +static bool is_numeric(char c) {return c>='0' && c<='9';} + + +static bool is_spacing(char c) +{ + return c == ' ' || c == '\t'; +} + +static bool is_linebreak(char c) +{ + return c == '\n' || c == '\r'; +} + +static void validate_file_type(const char * p_type,t_size p_type_length) { + if ( + //standard types + stricmp_utf8_ex(p_type,p_type_length,"WAVE",pfc_infinite) != 0 && + stricmp_utf8_ex(p_type,p_type_length,"MP3",pfc_infinite) != 0 && + stricmp_utf8_ex(p_type,p_type_length,"AIFF",pfc_infinite) != 0 && + //common user-entered types + stricmp_utf8_ex(p_type,p_type_length,"APE",pfc_infinite) != 0 && + stricmp_utf8_ex(p_type,p_type_length,"FLAC",pfc_infinite) != 0 && + stricmp_utf8_ex(p_type,p_type_length,"WV",pfc_infinite) != 0 && + stricmp_utf8_ex(p_type,p_type_length,"WAVPACK",pfc_infinite) != 0 + ) + pfc::throw_exception_with_message< exception_cue >(PFC_string_formatter() << "expected WAVE, MP3 or AIFF, got : \"" << pfc::string_part(p_type,p_type_length) << "\""); +} + +namespace { + + class NOVTABLE cue_parser_callback + { + public: + virtual void on_file(const char * p_file,t_size p_file_length,const char * p_type,t_size p_type_length) = 0; + virtual void on_track(unsigned p_index,const char * p_type,t_size p_type_length) = 0; + virtual void on_pregap(unsigned p_value) = 0; + virtual void on_index(unsigned p_index,unsigned p_value) = 0; + virtual void on_title(const char * p_title,t_size p_title_length) = 0; + virtual void on_performer(const char * p_performer,t_size p_performer_length) = 0; + virtual void on_songwriter(const char * p_songwriter,t_size p_songwriter_length) = 0; + virtual void on_isrc(const char * p_isrc,t_size p_isrc_length) = 0; + virtual void on_catalog(const char * p_catalog,t_size p_catalog_length) = 0; + virtual void on_comment(const char * p_comment,t_size p_comment_length) = 0; + virtual void on_flags(const char * p_flags,t_size p_flags_length) = 0; + }; + + class NOVTABLE cue_parser_callback_meta : public cue_parser_callback + { + public: + virtual void on_file(const char * p_file,t_size p_file_length,const char * p_type,t_size p_type_length) = 0; + virtual void on_track(unsigned p_index,const char * p_type,t_size p_type_length) = 0; + virtual void on_pregap(unsigned p_value) = 0; + virtual void on_index(unsigned p_index,unsigned p_value) = 0; + virtual void on_meta(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) = 0; + protected: + static bool is_known_meta(const char * p_name,t_size p_length) + { + static const char * metas[] = {"genre","date","discid","comment","replaygain_track_gain","replaygain_track_peak","replaygain_album_gain","replaygain_album_peak"}; + for(t_size n=0;n("invalid REM syntax"); + if (ptr > value_base) on_meta(p_comment,name_length,p_comment + value_base,ptr - value_base); + } + else + { + unsigned value_base = ptr; + while(ptr < p_comment_length /*&& !is_spacing(p_comment[ptr])*/) ptr++; + if (ptr > value_base) on_meta(p_comment,name_length,p_comment + value_base,ptr - value_base); + } + } + } + } + void on_title(const char * p_title,t_size p_title_length) + { + on_meta("title",pfc_infinite,p_title,p_title_length); + } + void on_songwriter(const char * p_songwriter,t_size p_songwriter_length) { + on_meta("songwriter",pfc_infinite,p_songwriter,p_songwriter_length); + } + void on_performer(const char * p_performer,t_size p_performer_length) + { + on_meta("artist",pfc_infinite,p_performer,p_performer_length); + } + + void on_isrc(const char * p_isrc,t_size p_isrc_length) + { + on_meta("isrc",pfc_infinite,p_isrc,p_isrc_length); + } + void on_catalog(const char * p_catalog,t_size p_catalog_length) + { + on_meta("catalog",pfc_infinite,p_catalog,p_catalog_length); + } + void on_flags(const char * p_flags,t_size p_flags_length) {} + }; + + + class cue_parser_callback_retrievelist : public cue_parser_callback + { + public: + cue_parser_callback_retrievelist(cue_parser::t_cue_entry_list & p_out) : m_out(p_out), m_track(0), m_pregap(0), m_index0_set(false), m_index1_set(false) + { + } + + void on_file(const char * p_file,t_size p_file_length,const char * p_type,t_size p_type_length) + { + validate_file_type(p_type,p_type_length); + m_file.set_string(p_file,p_file_length); + } + + void on_track(unsigned p_index,const char * p_type,t_size p_type_length) + { + if (stricmp_utf8_ex(p_type,p_type_length,"audio",pfc_infinite)) pfc::throw_exception_with_message("only tracks of type AUDIO supported"); + //if (p_index != m_track + 1) throw exception_cue("cuesheet tracks out of order"); + if (m_track != 0) finalize_track(); + if (m_file.is_empty()) pfc::throw_exception_with_message("declaring a track with no file set"); + m_trackfile = m_file; + m_track = p_index; + } + + void on_pregap(unsigned p_value) {m_pregap = (double) p_value / 75.0;} + + void on_index(unsigned p_index,unsigned p_value) + { + if (p_index < t_cuesheet_index_list::count) + { + switch(p_index) + { + case 0: m_index0_set = true; break; + case 1: m_index1_set = true; break; + } + m_index_list.m_positions[p_index] = (double) p_value / 75.0; + } + } + + void on_title(const char * p_title,t_size p_title_length) {} + void on_performer(const char * p_performer,t_size p_performer_length) {} + void on_songwriter(const char * p_songwriter,t_size p_songwriter_length) {} + void on_isrc(const char * p_isrc,t_size p_isrc_length) {} + void on_catalog(const char * p_catalog,t_size p_catalog_length) {} + void on_comment(const char * p_comment,t_size p_comment_length) {} + void on_flags(const char * p_flags,t_size p_flags_length) {} + + void finalize() + { + if (m_track != 0) + { + finalize_track(); + m_track = 0; + } + } + + private: + void finalize_track() + { + if (!m_index1_set) pfc::throw_exception_with_message< exception_cue > ("INDEX 01 not set"); + if (!m_index0_set) m_index_list.m_positions[0] = m_index_list.m_positions[1] - m_pregap; + if (!m_index_list.is_valid()) pfc::throw_exception_with_message< exception_cue > ("invalid index list"); + + cue_parser::t_cue_entry_list::iterator iter; + iter = m_out.insert_last(); + if (m_trackfile.is_empty()) pfc::throw_exception_with_message< exception_cue > ("track has no file assigned"); + iter->m_file = m_trackfile; + iter->m_track_number = m_track; + iter->m_indexes = m_index_list; + + m_index_list.reset(); + m_index0_set = false; + m_index1_set = false; + m_pregap = 0; + } + + bool m_index0_set,m_index1_set; + t_cuesheet_index_list m_index_list; + double m_pregap; + unsigned m_track; + pfc::string8 m_file,m_trackfile; + cue_parser::t_cue_entry_list & m_out; + }; + + class cue_parser_callback_retrieveinfo : public cue_parser_callback_meta + { + public: + cue_parser_callback_retrieveinfo(file_info & p_out,unsigned p_wanted_track) : m_out(p_out), m_wanted_track(p_wanted_track), m_track(0), m_is_va(false), m_index0_set(false), m_index1_set(false), m_pregap(0), m_totaltracks(0) {} + + void on_file(const char * p_file,t_size p_file_length,const char * p_type,t_size p_type_length) {} + + void on_track(unsigned p_index,const char * p_type,t_size p_type_length) + { + if (p_index == 0) pfc::throw_exception_with_message< exception_cue > ("invalid TRACK index"); + if (p_index == m_wanted_track) + { + if (stricmp_utf8_ex(p_type,p_type_length,"audio",pfc_infinite)) pfc::throw_exception_with_message< exception_cue > ("only tracks of type AUDIO supported"); + } + m_track = p_index; + m_totaltracks++; + } + + void on_pregap(unsigned p_value) {if (m_track == m_wanted_track) m_pregap = (double) p_value / 75.0;} + + void on_index(unsigned p_index,unsigned p_value) + { + if (m_track == m_wanted_track && p_index < t_cuesheet_index_list::count) + { + switch(p_index) + { + case 0: m_index0_set = true; break; + case 1: m_index1_set = true; break; + } + m_indexes.m_positions[p_index] = (double) p_value / 75.0; + } + } + + + void on_meta(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) + { + t_meta_list::iterator iter; + if (m_track == 0) //globals + { + //convert global title to album + if (!stricmp_utf8_ex(p_name,p_name_length,"title",pfc_infinite)) + { + p_name = "album"; + p_name_length = 5; + } + else if (!stricmp_utf8_ex(p_name,p_name_length,"artist",pfc_infinite)) + { + m_album_artist.set_string(p_value,p_value_length); + } + + iter = m_globals.insert_last(); + } + else + { + if (!m_is_va) + { + if (!stricmp_utf8_ex(p_name,p_name_length,"artist",pfc_infinite)) + { + if (!m_album_artist.is_empty()) + { + if (stricmp_utf8_ex(p_value,p_value_length,m_album_artist,m_album_artist.length())) m_is_va = true; + } + } + } + + if (m_track == m_wanted_track) //locals + { + iter = m_locals.insert_last(); + } + } + if (iter.is_valid()) + { + iter->m_name.set_string(p_name,p_name_length); + iter->m_value.set_string(p_value,p_value_length); + } + } + + void finalize() + { + if (!m_index1_set) pfc::throw_exception_with_message< exception_cue > ("INDEX 01 not set"); + if (!m_index0_set) m_indexes.m_positions[0] = m_indexes.m_positions[1] - m_pregap; + m_indexes.to_infos(m_out); + + replaygain_info rg; + rg.reset(); + t_meta_list::const_iterator iter; + + if (m_is_va) + { + //clean up VA mess + + t_meta_list::const_iterator iter_global,iter_local; + + iter_global = find_first_field(m_globals,"artist"); + iter_local = find_first_field(m_locals,"artist"); + if (iter_global.is_valid()) + { + m_out.meta_set("album artist",iter_global->m_value); + if (iter_local.is_valid()) m_out.meta_set("artist",iter_local->m_value); + else m_out.meta_set("artist",iter_global->m_value); + } + else + { + if (iter_local.is_valid()) m_out.meta_set("artist",iter_local->m_value); + } + + + wipe_field(m_globals,"artist"); + wipe_field(m_locals,"artist"); + + } + + for(iter=m_globals.first();iter.is_valid();iter++) + { + if (!rg.set_from_meta(iter->m_name,iter->m_value)) + m_out.meta_set(iter->m_name,iter->m_value); + } + for(iter=m_locals.first();iter.is_valid();iter++) + { + if (!rg.set_from_meta(iter->m_name,iter->m_value)) + m_out.meta_set(iter->m_name,iter->m_value); + } + m_out.meta_set("tracknumber",PFC_string_formatter() << m_wanted_track); + m_out.meta_set("totaltracks", PFC_string_formatter() << m_totaltracks); + m_out.set_replaygain(rg); + + } + private: + struct t_meta_entry { + pfc::string8 m_name,m_value; + }; + typedef pfc::chain_list_v2_t t_meta_list; + + static t_meta_list::const_iterator find_first_field(t_meta_list const & p_list,const char * p_field) + { + t_meta_list::const_iterator iter; + for(iter=p_list.first();iter.is_valid();++iter) + { + if (!stricmp_utf8(p_field,iter->m_name)) return iter; + } + return t_meta_list::const_iterator();//null iterator + } + + static void wipe_field(t_meta_list & p_list,const char * p_field) + { + t_meta_list::iterator iter; + for(iter=p_list.first();iter.is_valid();) + { + if (!stricmp_utf8(p_field,iter->m_name)) + { + t_meta_list::iterator temp = iter; + ++temp; + p_list.remove_single(iter); + iter = temp; + } + else + { + ++iter; + } + } + } + + t_meta_list m_globals,m_locals; + file_info & m_out; + unsigned m_wanted_track, m_track,m_totaltracks; + pfc::string8 m_album_artist; + bool m_is_va; + t_cuesheet_index_list m_indexes; + bool m_index0_set,m_index1_set; + double m_pregap; + }; + +}; + + +static void g_parse_cue_line(const char * p_line,t_size p_line_length,cue_parser_callback & p_callback) +{ + t_size ptr = 0; + while(ptr < p_line_length && !is_spacing(p_line[ptr])) ptr++; + if (!stricmp_utf8_ex(p_line,ptr,"file",pfc_infinite)) + { + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + t_size file_base,file_length, type_base,type_length; + + if (p_line[ptr] == '\"') + { + ptr++; + file_base = ptr; + while(ptr < p_line_length && p_line[ptr] != '\"') ptr++; + if (ptr == p_line_length) pfc::throw_exception_with_message< exception_cue > ("invalid FILE syntax"); + file_length = ptr - file_base; + ptr++; + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + } + else + { + file_base = ptr; + while(ptr < p_line_length && !is_spacing(p_line[ptr])) ptr++; + file_length = ptr - file_base; + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + } + + type_base = ptr; + while(ptr < p_line_length && !is_spacing(p_line[ptr])) ptr++; + type_length = ptr - type_base; + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + + if (ptr != p_line_length || file_length == 0 || type_length == 0) pfc::throw_exception_with_message< exception_cue > ("invalid FILE syntax"); + + p_callback.on_file(p_line + file_base, file_length, p_line + type_base, type_length); + } + else if (!stricmp_utf8_ex(p_line,ptr,"track",pfc_infinite)) + { + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + + t_size track_base = ptr, track_length; + while(ptr < p_line_length && !is_spacing(p_line[ptr])) + { + if (!is_numeric(p_line[ptr])) pfc::throw_exception_with_message< exception_cue > ("invalid TRACK syntax"); + ptr++; + } + track_length = ptr - track_base; + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + + t_size type_base = ptr, type_length; + while(ptr < p_line_length && !is_spacing(p_line[ptr])) ptr++; + type_length = ptr - type_base; + + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + if (ptr != p_line_length || type_length == 0) pfc::throw_exception_with_message< exception_cue > ("invalid TRACK syntax"); + unsigned track = pfc::atoui_ex(p_line+track_base,track_length); + if (track < 1 || track > 99) pfc::throw_exception_with_message< exception_cue > ("invalid track number"); + + p_callback.on_track(track,p_line + type_base, type_length); + } + else if (!stricmp_utf8_ex(p_line,ptr,"index",pfc_infinite)) + { + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + + t_size index_base,index_length, time_base,time_length; + index_base = ptr; + while(ptr < p_line_length && !is_spacing(p_line[ptr])) + { + if (!is_numeric(p_line[ptr])) pfc::throw_exception_with_message< exception_cue > ("invalid INDEX syntax" ); + ptr++; + } + index_length = ptr - index_base; + + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + time_base = ptr; + while(ptr < p_line_length && !is_spacing(p_line[ptr])) + { + if (!is_numeric(p_line[ptr]) && p_line[ptr] != ':') + pfc::throw_exception_with_message< exception_cue > ("invalid INDEX syntax"); + ptr++; + } + time_length = ptr - time_base; + + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + + if (ptr != p_line_length || index_length == 0 || time_length == 0) + pfc::throw_exception_with_message< exception_cue > ("invalid INDEX syntax"); + + unsigned index = pfc::atoui_ex(p_line+index_base,index_length); + if (index > 99) pfc::throw_exception_with_message< exception_cue > ("invalid INDEX syntax"); + unsigned time = cuesheet_parse_index_time_ticks_e(p_line + time_base,time_length); + + p_callback.on_index(index,time); + } + else if (!stricmp_utf8_ex(p_line,ptr,"pregap",pfc_infinite)) + { + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + + t_size time_base, time_length; + time_base = ptr; + while(ptr < p_line_length && !is_spacing(p_line[ptr])) + { + if (!is_numeric(p_line[ptr]) && p_line[ptr] != ':') + pfc::throw_exception_with_message< exception_cue > ("invalid PREGAP syntax"); + ptr++; + } + time_length = ptr - time_base; + + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + + if (ptr != p_line_length || time_length == 0) + pfc::throw_exception_with_message< exception_cue > ("invalid PREGAP syntax"); + + unsigned time = cuesheet_parse_index_time_ticks_e(p_line + time_base,time_length); + + p_callback.on_pregap(time); + } + else if (!stricmp_utf8_ex(p_line,ptr,"title",pfc_infinite)) + { + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + if (ptr == p_line_length) pfc::throw_exception_with_message< exception_cue > ("invalid TITLE syntax"); + if (p_line[ptr] == '\"') + { + ptr++; + t_size base = ptr; + while(ptr < p_line_length && p_line[ptr] != '\"') ptr++; + if (ptr == p_line_length) pfc::throw_exception_with_message< exception_cue > ("invalid TITLE syntax"); + t_size length = ptr-base; + ptr++; + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + if (ptr != p_line_length) pfc::throw_exception_with_message< exception_cue > ("invalid TITLE syntax"); + p_callback.on_title(p_line+base,length); + } + else + { + p_callback.on_title(p_line+ptr,p_line_length-ptr); + } + } + else if (!stricmp_utf8_ex(p_line,ptr,"performer",pfc_infinite)) + { + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + if (ptr == p_line_length) pfc::throw_exception_with_message< exception_cue > ("invalid PERFORMER syntax"); + if (p_line[ptr] == '\"') + { + ptr++; + t_size base = ptr; + while(ptr < p_line_length && p_line[ptr] != '\"') ptr++; + if (ptr == p_line_length) pfc::throw_exception_with_message< exception_cue > ("invalid PERFORMER syntax"); + t_size length = ptr-base; + ptr++; + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + if (ptr != p_line_length) pfc::throw_exception_with_message< exception_cue > ("invalid PERFORMER syntax"); + p_callback.on_performer(p_line+base,length); + } + else + { + p_callback.on_performer(p_line+ptr,p_line_length-ptr); + } + } + else if (!stricmp_utf8_ex(p_line,ptr,"songwriter",pfc_infinite)) + { + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + if (ptr == p_line_length) pfc::throw_exception_with_message< exception_cue > ("invalid SONGWRITER syntax"); + if (p_line[ptr] == '\"') + { + ptr++; + t_size base = ptr; + while(ptr < p_line_length && p_line[ptr] != '\"') ptr++; + if (ptr == p_line_length) pfc::throw_exception_with_message< exception_cue > ("invalid SONGWRITER syntax"); + t_size length = ptr-base; + ptr++; + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + if (ptr != p_line_length) pfc::throw_exception_with_message< exception_cue > ("invalid SONGWRITER syntax"); + p_callback.on_songwriter(p_line+base,length); + } + else + { + p_callback.on_songwriter(p_line+ptr,p_line_length-ptr); + } + } + else if (!stricmp_utf8_ex(p_line,ptr,"isrc",pfc_infinite)) + { + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + t_size length = p_line_length - ptr; + if (length == 0) pfc::throw_exception_with_message< exception_cue > ("invalid ISRC syntax"); + p_callback.on_isrc(p_line+ptr,length); + } + else if (!stricmp_utf8_ex(p_line,ptr,"catalog",pfc_infinite)) + { + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + t_size length = p_line_length - ptr; + if (length == 0) pfc::throw_exception_with_message< exception_cue > ("invalid CATALOG syntax"); + p_callback.on_catalog(p_line+ptr,length); + } + else if (!stricmp_utf8_ex(p_line,ptr,"flags",pfc_infinite)) + { + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + if (ptr < p_line_length) + p_callback.on_flags(p_line + ptr, p_line_length - ptr); + } + else if (!stricmp_utf8_ex(p_line,ptr,"rem",pfc_infinite)) + { + while(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++; + if (ptr < p_line_length) + p_callback.on_comment(p_line + ptr, p_line_length - ptr); + } + else if (!stricmp_utf8_ex(p_line,ptr,"postgap",pfc_infinite)) { + pfc::throw_exception_with_message< exception_cue > ("POSTGAP is not supported"); + } else if (!stricmp_utf8_ex(p_line,ptr,"cdtextfile",pfc_infinite)) { + //do nothing + } + else pfc::throw_exception_with_message< exception_cue > ("unknown cuesheet item"); +} + +static void g_parse_cue(const char * p_cuesheet,cue_parser_callback & p_callback) +{ + const char * parseptr = p_cuesheet; + t_size lineidx = 1; + while(*parseptr) + { + while(is_spacing(*parseptr)) parseptr++; + if (*parseptr) + { + t_size length = 0; + while(parseptr[length] && !is_linebreak(parseptr[length])) length++; + if (length > 0) { + try { + g_parse_cue_line(parseptr,length,p_callback); + } catch(exception_cue const & e) {//rethrow with line info + pfc::throw_exception_with_message< exception_cue > (PFC_string_formatter() << e.what() << " (line " << (unsigned)lineidx << ")"); + } + } + parseptr += length; + while(is_linebreak(*parseptr)) { + if (*parseptr == '\n') lineidx++; + parseptr++; + } + } + } +} + +void cue_parser::parse(const char *p_cuesheet,t_cue_entry_list & p_out) { + try { + cue_parser_callback_retrievelist callback(p_out); + g_parse_cue(p_cuesheet,callback); + callback.finalize(); + } catch(exception_cue const & e) { + pfc::throw_exception_with_message(PFC_string_formatter() << "Error parsing cuesheet: " << e.what()); + } +} +void cue_parser::parse_info(const char * p_cuesheet,file_info & p_info,unsigned p_index) { + try { + cue_parser_callback_retrieveinfo callback(p_info,p_index); + g_parse_cue(p_cuesheet,callback); + callback.finalize(); + } catch(exception_cue const & e) { + pfc::throw_exception_with_message< exception_bad_cuesheet > (PFC_string_formatter() << "Error parsing cuesheet: " << e.what()); + } +} + +namespace { + + class cue_parser_callback_retrievecount : public cue_parser_callback + { + public: + cue_parser_callback_retrievecount() : m_count(0) {} + unsigned get_count() const {return m_count;} + void on_file(const char * p_file,t_size p_file_length,const char * p_type,t_size p_type_length) {} + void on_track(unsigned p_index,const char * p_type,t_size p_type_length) {m_count++;} + void on_pregap(unsigned p_value) {} + void on_index(unsigned p_index,unsigned p_value) {} + void on_title(const char * p_title,t_size p_title_length) {} + void on_performer(const char * p_performer,t_size p_performer_length) {} + void on_isrc(const char * p_isrc,t_size p_isrc_length) {} + void on_catalog(const char * p_catalog,t_size p_catalog_length) {} + void on_comment(const char * p_comment,t_size p_comment_length) {} + void on_flags(const char * p_flags,t_size p_flags_length) {} + private: + unsigned m_count; + }; + + class cue_parser_callback_retrievecreatorentries : public cue_parser_callback + { + public: + cue_parser_callback_retrievecreatorentries(cue_creator::t_entry_list & p_out) : m_out(p_out), m_track(0), m_pregap(0), m_index0_set(false), m_index1_set(false) {} + + void on_file(const char * p_file,t_size p_file_length,const char * p_type,t_size p_type_length) { + validate_file_type(p_type,p_type_length); + m_file.set_string(p_file,p_file_length); + } + + void on_track(unsigned p_index,const char * p_type,t_size p_type_length) + { + if (stricmp_utf8_ex(p_type,p_type_length,"audio",pfc_infinite)) pfc::throw_exception_with_message< exception_cue > ("only tracks of type AUDIO supported"); + //if (p_index != m_track + 1) throw exception_cue("cuesheet tracks out of order",0); + if (m_track != 0) finalize_track(); + if (m_file.is_empty()) pfc::throw_exception_with_message< exception_cue > ("declaring a track with no file set"); + m_trackfile = m_file; + m_track = p_index; + } + + void on_pregap(unsigned p_value) + { + m_pregap = (double) p_value / 75.0; + } + + void on_index(unsigned p_index,unsigned p_value) + { + if (p_index < t_cuesheet_index_list::count) + { + switch(p_index) + { + case 0: m_index0_set = true; break; + case 1: m_index1_set = true; break; + } + m_indexes.m_positions[p_index] = (double) p_value / 75.0; + } + } + void on_title(const char * p_title,t_size p_title_length) {} + void on_performer(const char * p_performer,t_size p_performer_length) {} + void on_songwriter(const char * p_performer,t_size p_performer_length) {} + void on_isrc(const char * p_isrc,t_size p_isrc_length) {} + void on_catalog(const char * p_catalog,t_size p_catalog_length) {} + void on_comment(const char * p_comment,t_size p_comment_length) {} + void finalize() + { + if (m_track != 0) + { + finalize_track(); + m_track = 0; + } + } + void on_flags(const char * p_flags,t_size p_flags_length) { + m_flags.set_string(p_flags,p_flags_length); + } + private: + void finalize_track() + { + if (m_track < 1 || m_track > 99) pfc::throw_exception_with_message< exception_cue > ("track number out of range"); + if (!m_index1_set) pfc::throw_exception_with_message< exception_cue > ("INDEX 01 not set"); + if (!m_index0_set) m_indexes.m_positions[0] = m_indexes.m_positions[1] - m_pregap; + if (!m_indexes.is_valid()) pfc::throw_exception_with_message< exception_cue > ("invalid index list"); + + cue_creator::t_entry_list::iterator iter; + iter = m_out.insert_last(); + iter->m_track_number = m_track; + iter->m_file = m_trackfile; + iter->m_index_list = m_indexes; + iter->m_flags = m_flags; + m_pregap = 0; + m_indexes.reset(); + m_index0_set = m_index1_set = false; + m_flags.reset(); + } + + bool m_index0_set,m_index1_set; + double m_pregap; + unsigned m_track; + cue_creator::t_entry_list & m_out; + pfc::string8 m_file,m_trackfile,m_flags; + t_cuesheet_index_list m_indexes; + }; +} + +void cue_parser::parse_full(const char * p_cuesheet,cue_creator::t_entry_list & p_out) { + try { + { + cue_parser_callback_retrievecreatorentries callback(p_out); + g_parse_cue(p_cuesheet,callback); + callback.finalize(); + } + + { + cue_creator::t_entry_list::iterator iter; + for(iter=p_out.first();iter.is_valid();++iter) + { + cue_parser_callback_retrieveinfo callback(iter->m_infos,iter->m_track_number); + g_parse_cue(p_cuesheet,callback); + callback.finalize(); + } + } + } catch(exception_cue const & e) { + pfc::throw_exception_with_message< exception_bad_cuesheet > (PFC_string_formatter() << "Error parsing cuesheet: " << e.what()); + } +} diff --git a/SDK/foobar2000/helpers/cue_parser.h b/SDK/foobar2000/helpers/cue_parser.h new file mode 100644 index 0000000..1e57ff7 --- /dev/null +++ b/SDK/foobar2000/helpers/cue_parser.h @@ -0,0 +1,411 @@ +//HINT: for info on how to generate an embedded cuesheet enabled input, see the end of this header. + +//to be moved somewhere else later +namespace file_info_record_helper { + + class __file_info_record__info__enumerator { + public: + __file_info_record__info__enumerator(file_info & p_out) : m_out(p_out) {} + void operator() (const char * p_name,const char * p_value) {m_out.__info_add_unsafe(p_name,p_value);} + private: + file_info & m_out; + }; + + class __file_info_record__meta__enumerator { + public: + __file_info_record__meta__enumerator(file_info & p_out) : m_out(p_out) {} + template void operator() (const char * p_name,const t_value & p_value) { + t_size index = ~0; + for(typename t_value::const_iterator iter = p_value.first(); iter.is_valid(); ++iter) { + if (index == ~0) index = m_out.__meta_add_unsafe(p_name,*iter); + else m_out.meta_add_value(index,*iter); + } + } + private: + file_info & m_out; + }; + + class file_info_record { + public: + typedef pfc::chain_list_v2_t t_meta_value; + typedef pfc::map_t t_meta_map; + typedef pfc::map_t t_info_map; + + file_info_record() : m_replaygain(replaygain_info_invalid), m_length(0) {} + + replaygain_info get_replaygain() const {return m_replaygain;} + void set_replaygain(const replaygain_info & p_replaygain) {m_replaygain = p_replaygain;} + double get_length() const {return m_length;} + void set_length(double p_length) {m_length = p_length;} + + void reset() { + m_meta.remove_all(); m_info.remove_all(); + m_length = 0; + m_replaygain = replaygain_info_invalid; + } + + void from_info_overwrite_info(const file_info & p_info) { + for(t_size infowalk = 0, infocount = p_info.info_get_count(); infowalk < infocount; ++infowalk) { + m_info.set(p_info.info_enum_name(infowalk),p_info.info_enum_value(infowalk)); + } + } + void from_info_overwrite_meta(const file_info & p_info) { + for(t_size metawalk = 0, metacount = p_info.meta_get_count(); metawalk < metacount; ++metawalk) { + const t_size valuecount = p_info.meta_enum_value_count(metawalk); + if (valuecount > 0) { + t_meta_value & entry = m_meta.find_or_add(p_info.meta_enum_name(metawalk)); + entry.remove_all(); + for(t_size valuewalk = 0; valuewalk < valuecount; ++valuewalk) { + entry.add_item(p_info.meta_enum_value(metawalk,valuewalk)); + } + } + } + } + + void from_info_overwrite_rg(const file_info & p_info) { + m_replaygain = replaygain_info::g_merge(m_replaygain,p_info.get_replaygain()); + } + + template + void overwrite_meta(const t_source & p_meta) { + m_meta.overwrite(p_meta); + } + template + void overwrite_info(const t_source & p_info) { + m_info.overwrite(p_info); + } + + void merge_overwrite(const file_info & p_info) { + from_info_overwrite_info(p_info); + from_info_overwrite_meta(p_info); + from_info_overwrite_rg(p_info); + } + + void transfer_meta_entry(const char * p_name,const file_info & p_info,t_size p_index) { + const t_size count = p_info.meta_enum_value_count(p_index); + if (count == 0) { + m_meta.remove(p_name); + } else { + t_meta_value & val = m_meta.find_or_add(p_name); + val.remove_all(); + for(t_size walk = 0; walk < count; ++walk) { + val.add_item(p_info.meta_enum_value(p_index,walk)); + } + } + } + + void meta_set(const char * p_name,const char * p_value) { + m_meta.find_or_add(p_name).set_single(p_value); + } + + const t_meta_value * meta_query_ptr(const char * p_name) const { + return m_meta.query_ptr(p_name); + } + + + void from_info_set_meta(const file_info & p_info) { + m_meta.remove_all(); + from_info_overwrite_meta(p_info); + } + + void from_info(const file_info & p_info) { + reset(); + m_length = p_info.get_length(); + m_replaygain = p_info.get_replaygain(); + from_info_overwrite_meta(p_info); + from_info_overwrite_info(p_info); + } + void to_info(file_info & p_info) const { + p_info.reset(); + p_info.set_length(m_length); + p_info.set_replaygain(m_replaygain); + + { + __file_info_record__info__enumerator e(p_info); + m_info.enumerate( e ); + } + { + __file_info_record__meta__enumerator e(p_info); + m_meta.enumerate( e ); + } + } + + template void enumerate_meta(t_callback & p_callback) const {m_meta.enumerate(p_callback);} + template void enumerate_meta(t_callback & p_callback) {m_meta.enumerate(p_callback);} + + //private: + t_meta_map m_meta; + t_info_map m_info; + replaygain_info m_replaygain; + double m_length; + }; + +}//namespace file_info_record_helper + + +namespace cue_parser +{ + struct cue_entry { + pfc::string8 m_file; + unsigned m_track_number; + t_cuesheet_index_list m_indexes; + }; + + typedef pfc::chain_list_v2_t t_cue_entry_list; + + + PFC_DECLARE_EXCEPTION(exception_bad_cuesheet,exception_io_data,"Invalid cuesheet"); + + //! Throws exception_bad_cuesheet on failure. + void parse(const char *p_cuesheet,t_cue_entry_list & p_out); + //! Throws exception_bad_cuesheet on failure. + void parse_info(const char *p_cuesheet,file_info & p_info,unsigned p_index); + //! Throws exception_bad_cuesheet on failure. + void parse_full(const char * p_cuesheet,cue_creator::t_entry_list & p_out); + + + + struct track_record { + file_info_record_helper::file_info_record m_info; + pfc::string8 m_file,m_flags; + t_cuesheet_index_list m_index_list; + }; + + typedef pfc::map_t track_record_list; + + class embeddedcue_metadata_manager { + public: + void get_tag(file_info & p_info) const; + void set_tag(file_info const & p_info); + + void get_track_info(unsigned p_track,file_info & p_info) const; + void set_track_info(unsigned p_track,file_info const & p_info); + void query_track_offsets(unsigned p_track,double & p_begin,double & p_length) const; + bool have_cuesheet() const; + unsigned remap_trackno(unsigned p_index) const; + t_size get_cue_track_count() const; + private: + track_record_list m_content; + }; + + + + + + template + class input_wrapper_cue_t { + public: + input_wrapper_cue_t() {} + ~input_wrapper_cue_t() {} + + void open(service_ptr_t p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort) { + m_impl.open( p_filehint, p_path, p_reason, p_abort ); + file_info_impl info; + m_impl.get_info(info,p_abort); + m_meta.set_tag(info); + } + + t_uint32 get_subsong_count() { + return m_meta.have_cuesheet() ? (uint32_t) m_meta.get_cue_track_count() : 1; + } + + t_uint32 get_subsong(t_uint32 p_index) { + return m_meta.have_cuesheet() ? m_meta.remap_trackno(p_index) : 0; + } + + void get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort) { + if (p_subsong == 0) { + m_meta.get_tag(p_info); + } else { + m_meta.get_track_info(p_subsong,p_info); + } + } + + t_filestats get_file_stats(abort_callback & p_abort) {return m_impl.get_file_stats(p_abort);} + + void decode_initialize(t_uint32 p_subsong,unsigned p_flags,abort_callback & p_abort) { + if (p_subsong == 0) { + m_impl.decode_initialize(p_flags, p_abort); + m_decodeFrom = 0; m_decodeLength = -1; m_decodePos = 0; + } else { + double start, length; + m_meta.query_track_offsets(p_subsong,start,length); + unsigned flags2 = p_flags; + if (start > 0) flags2 &= ~input_flag_no_seeking; + m_impl.decode_initialize(flags2, p_abort); + m_impl.decode_seek(start, p_abort); + m_decodeFrom = start; m_decodeLength = length; m_decodePos = 0; + } + } + + bool decode_run(audio_chunk & p_chunk,abort_callback & p_abort) { + return _run(p_chunk, NULL, p_abort); + } + + void decode_seek(double p_seconds,abort_callback & p_abort) { + if (this->m_decodeLength >= 0 && p_seconds > m_decodeLength) p_seconds = m_decodeLength; + m_impl.decode_seek(m_decodeFrom + p_seconds,p_abort); + m_decodePos = p_seconds; + } + + bool decode_can_seek() {return m_impl.decode_can_seek();} + + bool decode_run_raw(audio_chunk & p_chunk, mem_block_container & p_raw, abort_callback & p_abort) { + return _run(p_chunk, &p_raw, p_abort); + } + void set_logger(event_logger::ptr ptr) { + m_impl.set_logger(ptr); + } + + bool decode_get_dynamic_info(file_info & p_out, double & p_timestamp_delta) { + return m_impl.decode_get_dynamic_info(p_out, p_timestamp_delta); + } + + bool decode_get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) { + return m_impl.decode_get_dynamic_info_track(p_out, p_timestamp_delta); + } + + void decode_on_idle(abort_callback & p_abort) { + m_impl.decode_on_idle(p_abort); + } + + void retag_set_info(t_uint32 p_subsong,const file_info & p_info,abort_callback & p_abort) { + if (p_subsong == 0) { + m_meta.set_tag(p_info); + } else { + m_meta.set_track_info(p_subsong,p_info); + } + } + + void retag_commit(abort_callback & p_abort) { + file_info_impl info; + m_meta.get_tag(info); + m_impl.retag(pfc::implicit_cast(info), p_abort); + info.reset(); + m_impl.get_info(info, p_abort); + m_meta.set_tag( info ); + } + + inline static bool g_is_our_content_type(const char * p_content_type) {return t_base::g_is_our_content_type(p_content_type);} + inline static bool g_is_our_path(const char * p_path,const char * p_extension) {return t_base::g_is_our_path(p_path,p_extension);} + + private: + bool _run(audio_chunk & chunk, mem_block_container * raw, abort_callback & aborter) { + if (m_decodeLength >= 0 && m_decodePos >= m_decodeLength) return false; + if (raw == NULL) { + if (!m_impl.decode_run(chunk, aborter)) return false; + } else { + if (!m_impl.decode_run_raw(chunk, *raw, aborter)) return false; + } + + if (m_decodeLength >= 0) { + const uint64_t remaining = audio_math::time_to_samples( m_decodeLength - m_decodePos, chunk.get_sample_rate() ); + const size_t samplesGot = chunk.get_sample_count(); + if (remaining < samplesGot) { + m_decodePos = m_decodeLength; + if (remaining == 0) { // rare but possible as a result of rounding SNAFU - we're EOF but we didn't notice earlier + return false; + } + + chunk.set_sample_count( (size_t) remaining ); + if (raw != NULL) { + const t_size rawSize = raw->get_size(); + PFC_ASSERT( rawSize % samplesGot == 0 ); + raw->set_size( (t_size) ( (t_uint64) rawSize * remaining / samplesGot ) ); + } + } else { + m_decodePos += chunk.get_duration(); + } + } else { + m_decodePos += chunk.get_duration(); + } + return true; + } + t_base m_impl; + double m_decodeFrom, m_decodeLength, m_decodePos; + + embeddedcue_metadata_manager m_meta; + }; +#ifndef APP_IS_BOOM + template + class chapterizer_impl_t : public chapterizer + { + public: + bool is_our_path(const char * p_path) { + return I::g_is_our_path(p_path, pfc::string_extension(p_path)); + } + + void set_chapters(const char * p_path,chapter_list const & p_list,abort_callback & p_abort) { + input_wrapper_cue_t instance; + instance.open(0,p_path,input_open_info_write,p_abort); + + //stamp the cuesheet first + { + file_info_impl info; + instance.get_info(0,info,p_abort); + + pfc::string_formatter cuesheet; + + { + cue_creator::t_entry_list entries; + t_size n, m = p_list.get_chapter_count(); + const double pregap = p_list.get_pregap(); + double offset_acc = pregap; + for(n=0;nm_infos = p_list.get_info(n); + entry->m_file = "CDImage.wav"; + entry->m_track_number = (unsigned)(n+1); + entry->m_index_list.from_infos(entry->m_infos,offset_acc); + if (n == 0) entry->m_index_list.m_positions[0] = 0; + offset_acc += entry->m_infos.get_length(); + } + cue_creator::create(cuesheet,entries); + } + + info.meta_set("cuesheet",cuesheet); + + instance.retag_set_info(0,info,p_abort); + } + //stamp per-chapter infos + for(t_size walk = 0, total = p_list.get_chapter_count(); walk < total; ++walk) { + instance.retag_set_info( (uint32_t)( walk + 1 ), p_list.get_info(walk),p_abort); + } + + instance.retag_commit(p_abort); + } + + void get_chapters(const char * p_path,chapter_list & p_list,abort_callback & p_abort) { + + input_wrapper_cue_t instance; + instance.open(0,p_path,input_open_info_read,p_abort); + const t_uint32 total = instance.get_subsong_count(); + + p_list.set_chapter_count(total); + for(t_uint32 walk = 0; walk < total; ++walk) { + file_info_impl info; + instance.get_info(instance.get_subsong(walk),info,p_abort); + p_list.set_info(walk,info); + } + } + + bool supports_pregaps() { + return true; + } + }; +#endif +}; + +//! Wrapper template for generating embedded cuesheet enabled inputs. +//! t_input_impl is a singletrack input implementation (see input_singletrack_impl for method declarations). +//! To declare an embedded cuesheet enabled input, change your input declaration from input_singletrack_factory_t to input_cuesheet_factory_t. +template +class input_cuesheet_factory_t { +public: + input_factory_ex_t,t_flags,input_decoder_v2> m_input_factory; +#ifndef APP_IS_BOOM + service_factory_single_t > m_chapterizer_factory; +#endif +}; \ No newline at end of file diff --git a/SDK/foobar2000/helpers/cue_parser_embedding.cpp b/SDK/foobar2000/helpers/cue_parser_embedding.cpp new file mode 100644 index 0000000..3bb1b1d --- /dev/null +++ b/SDK/foobar2000/helpers/cue_parser_embedding.cpp @@ -0,0 +1,371 @@ +#include "stdafx.h" + +using namespace cue_parser; +using namespace file_info_record_helper; +static void build_cue_meta_name(const char * p_name,unsigned p_tracknumber,pfc::string_base & p_out) { + p_out.reset(); + p_out << "cue_track" << pfc::format_uint(p_tracknumber % 100,2) << "_" << p_name; +} + +static bool is_reserved_meta_entry(const char * p_name) { + return file_info::field_name_comparator::compare(p_name,"cuesheet") == 0; +} + +static bool is_global_meta_entry(const char * p_name) { + static const char header[] = "cue_track"; + return pfc::stricmp_ascii_ex(p_name,strlen(header),header,~0) != 0; +} +static bool is_allowed_field(const char * p_name) { + return !is_reserved_meta_entry(p_name) && is_global_meta_entry(p_name); +} +namespace { + class __get_tag_cue_track_list_builder { + public: + __get_tag_cue_track_list_builder(cue_creator::t_entry_list & p_entries) : m_entries(p_entries) {} + void operator() (unsigned p_trackno,const track_record & p_record) { + if (p_trackno > 0) { + cue_creator::t_entry_list::iterator iter = m_entries.insert_last(); + iter->m_file = p_record.m_file; + iter->m_flags = p_record.m_flags; + iter->m_index_list = p_record.m_index_list; + iter->m_track_number = p_trackno; + p_record.m_info.to_info(iter->m_infos); + } + } + private: + cue_creator::t_entry_list & m_entries; + }; + + typedef pfc::avltree_t field_name_list; + + class __get_tag__enum_fields_enumerator { + public: + __get_tag__enum_fields_enumerator(field_name_list & p_out) : m_out(p_out) {} + void operator() (unsigned p_trackno,const track_record & p_record) { + if (p_trackno > 0) p_record.m_info.enumerate_meta(*this); + } + template void operator() (const char * p_name,const t_value & p_value) { + m_out.add(p_name); + } + private: + field_name_list & m_out; + }; + + + class __get_tag__is_field_global_check { + private: + typedef file_info_record::t_meta_value t_value; + public: + __get_tag__is_field_global_check(const char * p_field) : m_field(p_field), m_value(NULL), m_state(true) {} + + void operator() (unsigned p_trackno,const track_record & p_record) { + if (p_trackno > 0 && m_state) { + const t_value * val = p_record.m_info.meta_query_ptr(m_field); + if (val == NULL) {m_state = false; return;} + if (m_value == NULL) { + m_value = val; + } else { + if (pfc::comparator_list::compare(*m_value,*val) != 0) { + m_state = false; return; + } + } + } + } + void finalize(file_info_record::t_meta_map & p_globals) { + if (m_state && m_value != NULL) { + p_globals.set(m_field,*m_value); + } + } + private: + const char * const m_field; + const t_value * m_value; + bool m_state; + }; + + class __get_tag__filter_globals { + public: + __get_tag__filter_globals(track_record_list const & p_tracks,file_info_record::t_meta_map & p_globals) : m_tracks(p_tracks), m_globals(p_globals) {} + + void operator() (const char * p_field) { + if (is_allowed_field(p_field)) { + __get_tag__is_field_global_check wrapper(p_field); + m_tracks.enumerate(wrapper); + wrapper.finalize(m_globals); + } + } + private: + const track_record_list & m_tracks; + file_info_record::t_meta_map & m_globals; + }; + + class __get_tag__local_field_filter { + public: + __get_tag__local_field_filter(const file_info_record::t_meta_map & p_globals,file_info_record::t_meta_map & p_output) : m_globals(p_globals), m_output(p_output), m_currenttrack(0) {} + void operator() (unsigned p_trackno,const track_record & p_track) { + if (p_trackno > 0) { + m_currenttrack = p_trackno; + p_track.m_info.enumerate_meta(*this); + } + } + void operator() (const char * p_name,const file_info_record::t_meta_value & p_value) { + PFC_ASSERT(m_currenttrack > 0); + if (!m_globals.have_item(p_name)) { + build_cue_meta_name(p_name,m_currenttrack,m_buffer); + m_output.set(m_buffer,p_value); + } + } + private: + unsigned m_currenttrack; + pfc::string8_fastalloc m_buffer; + const file_info_record::t_meta_map & m_globals; + file_info_record::t_meta_map & m_output; + }; +}; + +static void strip_redundant_track_meta(unsigned p_tracknumber,const file_info & p_cueinfo,file_info_record::t_meta_map & p_meta,const char * p_metaname) { + t_size metaindex = p_cueinfo.meta_find(p_metaname); + if (metaindex == ~0) return; + pfc::string_formatter namelocal; + build_cue_meta_name(p_metaname,p_tracknumber,namelocal); + { + const file_info_record::t_meta_value * val = p_meta.query_ptr(namelocal); + if (val == NULL) return; + file_info_record::t_meta_value::const_iterator iter = val->first(); + for(t_size valwalk = 0, valcount = p_cueinfo.meta_enum_value_count(metaindex); valwalk < valcount; ++valwalk) { + if (iter.is_empty()) return; + if (strcmp(*iter,p_cueinfo.meta_enum_value(metaindex,valwalk)) != 0) return; + ++iter; + } + if (!iter.is_empty()) return; + } + //success + p_meta.remove(namelocal); +} + +void embeddedcue_metadata_manager::get_tag(file_info & p_info) const { + if (!have_cuesheet()) { + m_content.query_ptr((unsigned)0)->m_info.to_info(p_info); + p_info.meta_remove_field("cuesheet"); + } else { + cue_creator::t_entry_list entries; + { + __get_tag_cue_track_list_builder e(entries); + m_content.enumerate(e); + } + pfc::string_formatter cuesheet; + cue_creator::create(cuesheet,entries); + entries.remove_all(); + //parse it back to see what info got stored in the cuesheet and what needs to be stored outside cuesheet in the tags + cue_parser::parse_full(cuesheet,entries); + file_info_record output; + + + + + { + file_info_record::t_meta_map globals; + //1. find global infos and forward them + { + field_name_list fields; + { __get_tag__enum_fields_enumerator e(fields); m_content.enumerate(e);} + { __get_tag__filter_globals e(m_content,globals); fields.enumerate(e); } + } + + output.overwrite_meta(globals); + + //2. find local infos + {__get_tag__local_field_filter e(globals,output.m_meta); m_content.enumerate(e);} + } + + + //strip redundant titles and tracknumbers that the cuesheet already contains + for(cue_creator::t_entry_list::const_iterator iter = entries.first(); iter.is_valid(); ++iter) { + strip_redundant_track_meta(iter->m_track_number,iter->m_infos,output.m_meta,"tracknumber"); + strip_redundant_track_meta(iter->m_track_number,iter->m_infos,output.m_meta,"title"); + } + + + //add tech infos etc + + { + const track_record * rec = m_content.query_ptr((unsigned)0); + if (rec != NULL) { + output.set_length(rec->m_info.get_length()); + output.set_replaygain(rec->m_info.get_replaygain()); + output.overwrite_info(rec->m_info.m_info); + } + } + output.meta_set("cuesheet",cuesheet); + output.to_info(p_info); + } +} + +static bool resolve_cue_meta_name(const char * p_name,pfc::string_base & p_outname,unsigned & p_tracknumber) { + //"cue_trackNN_fieldname" + static const char header[] = "cue_track"; + if (pfc::stricmp_ascii_ex(p_name,strlen(header),header,~0) != 0) return false; + p_name += strlen(header); + if (!pfc::char_is_numeric(p_name[0]) || !pfc::char_is_numeric(p_name[1]) || p_name[2] != '_') return false; + unsigned tracknumber = pfc::atoui_ex(p_name,2); + if (tracknumber == 0) return false; + p_name += 3; + p_tracknumber = tracknumber; + p_outname = p_name; + return true; +} + + +namespace { + class __set_tag_global_field_relay { + public: + __set_tag_global_field_relay(const file_info & p_info,t_size p_index) : m_info(p_info), m_index(p_index) {} + void operator() (unsigned p_trackno,track_record & p_record) { + if (p_trackno > 0) { + p_record.m_info.transfer_meta_entry(m_info.meta_enum_name(m_index),m_info,m_index); + } + } + private: + const file_info & m_info; + const t_size m_index; + }; +} + +void embeddedcue_metadata_manager::set_tag(file_info const & p_info) { + m_content.remove_all(); + + { + track_record & track0 = m_content.find_or_add((unsigned)0); + track0.m_info.from_info(p_info); + track0.m_info.m_info.set("cue_embedded","no"); + } + + + + const char * cuesheet = p_info.meta_get("cuesheet",0); + if (cuesheet == NULL) { + return; + } + + //processing order + //1. cuesheet content + //2. overwrite with global metadata from the tag + //3. overwrite with local metadata from the tag + + { + cue_creator::t_entry_list entries; + try { + cue_parser::parse_full(cuesheet,entries); + } catch(exception_io_data const & e) { + console::complain("Attempting to embed an invalid cuesheet", e.what()); + return; + } + + { + const double length = p_info.get_length(); + for(cue_creator::t_entry_list::const_iterator iter = entries.first(); iter.is_valid(); ++iter ) { + if (iter->m_index_list.start() > length) { + console::info("Invalid cuesheet - index outside allowed range"); + return; + } + } + } + + for(cue_creator::t_entry_list::const_iterator iter = entries.first(); iter.is_valid(); ) { + cue_creator::t_entry_list::const_iterator next = iter; + ++next; + track_record & entry = m_content.find_or_add(iter->m_track_number); + entry.m_file = iter->m_file; + entry.m_flags = iter->m_flags; + entry.m_index_list = iter->m_index_list; + entry.m_info.from_info(iter->m_infos); + entry.m_info.from_info_overwrite_info(p_info); + entry.m_info.m_info.set("cue_embedded","yes"); + double begin = entry.m_index_list.start(), end = next.is_valid() ? next->m_index_list.start() : p_info.get_length(); + if (end <= begin) throw exception_io_data(); + entry.m_info.set_length(end - begin); + iter = next; + } + } + + for(t_size metawalk = 0, metacount = p_info.meta_get_count(); metawalk < metacount; ++metawalk) { + const char * name = p_info.meta_enum_name(metawalk); + const t_size valuecount = p_info.meta_enum_value_count(metawalk); + if (valuecount > 0 && !is_reserved_meta_entry(name) && is_global_meta_entry(name)) { + __set_tag_global_field_relay relay(p_info,metawalk); + m_content.enumerate(relay); + } + } + + { + pfc::string8_fastalloc namebuffer; + for(t_size metawalk = 0, metacount = p_info.meta_get_count(); metawalk < metacount; ++metawalk) { + const char * name = p_info.meta_enum_name(metawalk); + const t_size valuecount = p_info.meta_enum_value_count(metawalk); + unsigned trackno; + if (valuecount > 0 && !is_reserved_meta_entry(name) && resolve_cue_meta_name(name,namebuffer,trackno)) { + track_record * rec = m_content.query_ptr(trackno); + if (rec != NULL) { + rec->m_info.transfer_meta_entry(namebuffer,p_info,metawalk); + } + } + } + } +} + +void embeddedcue_metadata_manager::get_track_info(unsigned p_track,file_info & p_info) const { + const track_record * rec = m_content.query_ptr(p_track); + if (rec == NULL) throw exception_io_data(); + rec->m_info.to_info(p_info); +} + +void embeddedcue_metadata_manager::set_track_info(unsigned p_track,file_info const & p_info) { + track_record * rec = m_content.query_ptr(p_track); + if (rec == NULL) throw exception_io_data(); + rec->m_info.from_info_set_meta(p_info); + rec->m_info.set_replaygain(p_info.get_replaygain()); +} + +void embeddedcue_metadata_manager::query_track_offsets(unsigned p_track,double & p_begin,double & p_length) const { + const track_record * rec = m_content.query_ptr(p_track); + if (rec == NULL) throw exception_io_data(); + p_begin = rec->m_index_list.start(); + p_length = rec->m_info.get_length(); +} + +bool embeddedcue_metadata_manager::have_cuesheet() const { + return m_content.get_count() > 1; +} + +namespace { + class __remap_trackno_enumerator { + public: + __remap_trackno_enumerator(unsigned p_index) : m_countdown(p_index), m_result(0) {} + template void operator() (unsigned p_trackno,const t_blah&) { + if (p_trackno > 0 && m_result == 0) { + if (m_countdown == 0) { + m_result = p_trackno; + } else { + --m_countdown; + } + } + } + unsigned result() const {return m_result;} + private: + unsigned m_countdown; + unsigned m_result; + }; +}; + +unsigned embeddedcue_metadata_manager::remap_trackno(unsigned p_index) const { + if (have_cuesheet()) { + __remap_trackno_enumerator wrapper(p_index); + m_content.enumerate(wrapper); + return wrapper.result(); + } else { + return 0; + } +} + +t_size embeddedcue_metadata_manager::get_cue_track_count() const { + return m_content.get_count() - 1; +} \ No newline at end of file diff --git a/SDK/foobar2000/helpers/cuesheet_index_list.cpp b/SDK/foobar2000/helpers/cuesheet_index_list.cpp new file mode 100644 index 0000000..cdd59c7 --- /dev/null +++ b/SDK/foobar2000/helpers/cuesheet_index_list.cpp @@ -0,0 +1,77 @@ +#include "stdafx.h" + +#ifndef _MSC_VER +#define sprintf_s sprintf +#endif + +bool t_cuesheet_index_list::is_valid() const { + if (m_positions[1] < m_positions[0]) return false; + for(t_size n = 2; n < count && m_positions[n] > 0; n++) { + if (m_positions[n] < m_positions[n-1]) return false; + } + return true; +} + +void t_cuesheet_index_list::to_infos(file_info & p_out) const +{ + double base = m_positions[1]; + + if (base > 0) { + p_out.info_set("referenced_offset",cuesheet_format_index_time(base)); + } + + if (m_positions[0] < base) + p_out.info_set("pregap",cuesheet_format_index_time(base - m_positions[0])); + else + p_out.info_remove("pregap"); + + p_out.info_remove("index 00"); + p_out.info_remove("index 01"); + + for(unsigned n=2;n 0) + p_out.info_set(namebuffer,cuesheet_format_index_time(position)); + else + p_out.info_remove(namebuffer); + } +} + +static bool parse_value(const char * p_name,double & p_out) +{ + if (p_name == NULL) return false; + try { + p_out = cuesheet_parse_index_time_e(p_name,strlen(p_name)); + } catch(std::exception const &) {return false;} + return true; +} + +bool t_cuesheet_index_list::from_infos(file_info const & p_in,double p_base) +{ + double pregap; + bool found = false; + if (!parse_value(p_in.info_get("pregap"),pregap)) pregap = 0; + else found = true; + m_positions[0] = p_base - pregap; + m_positions[1] = p_base; + for(unsigned n=2;nptMaxTrackSize.x = r.right - r.left; + info->ptMaxTrackSize.y = r.bottom - r.top; + } + if (min_x && min_y) + { + r.left = 0; r.right = min_x; + r.top = 0; r.bottom = min_y; + MapDialogRect(hWnd,&r); + AdjustWindowRectEx(&r, dwStyle, FALSE, dwExStyle); + info->ptMinTrackSize.x = r.right - r.left; + info->ptMinTrackSize.y = r.bottom - r.top; + } + } + lResult = 0; + return TRUE; + case WM_INITDIALOG: + set_parent(hWnd); + { + t_size n; + for(n=0;n rects; + RECT orig_client; + HWND parent; + HWND sizegrip; + unsigned min_x,min_y,max_x,max_y; + +public: + struct param { + unsigned short id; + unsigned short flags; + }; +private: + pfc::array_t m_table; + + void set_parent(HWND wnd); + void reset(); + void on_wm_size(); +public: + inline void set_min_size(unsigned x,unsigned y) {min_x = x; min_y = y;} + inline void set_max_size(unsigned x,unsigned y) {max_x = x; max_y = y;} + void add_sizegrip(); + + enum { + X_MOVE = 1, X_SIZE = 2, Y_MOVE = 4, Y_SIZE = 8, + XY_MOVE = X_MOVE|Y_MOVE, XY_SIZE = X_SIZE|Y_SIZE, + X_MOVE_Y_SIZE = X_MOVE|Y_SIZE, X_SIZE_Y_MOVE = X_SIZE|Y_MOVE, + }; + //the old way + bool process_message(HWND wnd,UINT msg,WPARAM wp,LPARAM lp); + + //ATL-compatible + BOOL ProcessWindowMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& lResult); + + dialog_resize_helper(const param * src,unsigned count,unsigned p_min_x,unsigned p_min_y,unsigned p_max_x,unsigned p_max_y); + + ~dialog_resize_helper(); + + PFC_CLASS_NOT_COPYABLE_EX(dialog_resize_helper); +}; + +#endif // _DIALOG_RESIZE_HELPER_H_ + +#endif // _WIN32 \ No newline at end of file diff --git a/SDK/foobar2000/helpers/dropdown_helper.cpp b/SDK/foobar2000/helpers/dropdown_helper.cpp new file mode 100644 index 0000000..25b3c78 --- /dev/null +++ b/SDK/foobar2000/helpers/dropdown_helper.cpp @@ -0,0 +1,163 @@ +#include "stdafx.h" +#include "dropdown_helper.h" + +#ifdef _WIN32 + +void _cfg_dropdown_history_base::build_list(pfc::ptr_list_t & out) +{ + pfc::string8 temp; get_state(temp); + const char * src = temp; + while(*src) + { + int ptr = 0; + while(src[ptr] && src[ptr]!=separator) ptr++; + if (ptr>0) + { + out.add_item(pfc::strdup_n(src,ptr)); + src += ptr; + } + while(*src==separator) src++; + } +} + +void _cfg_dropdown_history_base::parse_list(const pfc::ptr_list_t & src) +{ + t_size n; + pfc::string8_fastalloc temp; + for(n=0;n & list) +{ + t_size n, m = list.get_count(); + uSendMessage(wnd,CB_RESETCONTENT,0,0); + for(n=0;n list; + build_list(list); + g_setup_dropdown_fromlist(wnd,list); + list.free_all(); +} + +bool _cfg_dropdown_history_base::add_item(const char * item) +{ + if (!item || !*item) return false; + pfc::string8 meh; + if (strchr(item,separator)) + { + uReplaceChar(meh,item,-1,separator,'|',false); + item = meh; + } + pfc::ptr_list_t list; + build_list(list); + unsigned n; + bool found = false; + for(n=0;n m_max) list.delete_by_idx(list.get_count()-1); + list.insert_item(_strdup(item),0); + } + parse_list(list); + list.free_all(); + return found; +} + +bool _cfg_dropdown_history_base::add_item(const char *item, HWND combobox) { + const bool state = add_item(item); + if (state) uSendMessageText(combobox, CB_ADDSTRING, 0, item); + return state; +} + +bool _cfg_dropdown_history_base::is_empty() +{ + pfc::string8 temp; get_state(temp); + const char * src = temp; + while(*src) + { + if (*src!=separator) return false; + src++; + } + return true; +} + +bool _cfg_dropdown_history_base::on_context(HWND wnd,LPARAM coords) { + try { + int coords_x = (short)LOWORD(coords), coords_y = (short)HIWORD(coords); + if (coords_x == -1 && coords_y == -1) + { + RECT asdf; + GetWindowRect(wnd,&asdf); + coords_x = (asdf.left + asdf.right) / 2; + coords_y = (asdf.top + asdf.bottom) / 2; + } + enum {ID_ERASE_ALL = 1, ID_ERASE_ONE }; + HMENU menu = CreatePopupMenu(); + uAppendMenu(menu,MF_STRING,ID_ERASE_ALL,"Wipe history"); + { + pfc::string8 tempvalue; + uGetWindowText(wnd,tempvalue); + if (!tempvalue.is_empty()) + uAppendMenu(menu,MF_STRING,ID_ERASE_ONE,"Remove this history item"); + } + int cmd = TrackPopupMenu(menu,TPM_RIGHTBUTTON|TPM_NONOTIFY|TPM_RETURNCMD,coords_x,coords_y,0,wnd,0); + DestroyMenu(menu); + switch(cmd) + { + case ID_ERASE_ALL: + { + set_state(""); + pfc::string8 value;//preserve old value while wiping dropdown list + uGetWindowText(wnd,value); + uSendMessage(wnd,CB_RESETCONTENT,0,0); + uSetWindowText(wnd,value); + return true; + } + case ID_ERASE_ONE: + { + pfc::string8 value; + uGetWindowText(wnd,value); + + pfc::ptr_list_t list; + build_list(list); + bool found = false; + for(t_size n=0;n & out); + void parse_list(const pfc::ptr_list_t & src); +public: + enum {separator = '\n'}; + virtual void set_state(const char * val) = 0; + virtual void get_state(pfc::string_base & out) const = 0; + _cfg_dropdown_history_base(unsigned p_max) : m_max(p_max) {} + void on_init(HWND ctrl, const char * initVal) { + add_item(initVal); setup_dropdown(ctrl); uSetWindowText(ctrl, initVal); + } + void setup_dropdown(HWND wnd); + void setup_dropdown(HWND wnd,UINT id) {setup_dropdown(GetDlgItem(wnd,id));} + bool add_item(const char * item); //returns true when the content has changed, false when not (the item was already on the list) + bool add_item(const char * item, HWND combobox); //immediately adds the item to the combobox + bool is_empty(); + bool on_context(HWND wnd,LPARAM coords); //returns true when the content has changed +}; + +class cfg_dropdown_history : public _cfg_dropdown_history_base { +public: + cfg_dropdown_history(const GUID & p_guid,unsigned p_max = 10,const char * init_vals = "") : _cfg_dropdown_history_base(p_max), m_state(p_guid, init_vals) {} + void set_state(const char * val) {m_state = val;} + void get_state(pfc::string_base & out) const {out = m_state;} +private: + cfg_string m_state; +}; + +class cfg_dropdown_history_mt : public _cfg_dropdown_history_base { +public: + cfg_dropdown_history_mt(const GUID & p_guid,unsigned p_max = 10,const char * init_vals = "") : _cfg_dropdown_history_base(p_max), m_state(p_guid, init_vals) {} + void set_state(const char * val) {m_state.set(val);} + void get_state(pfc::string_base & out) const {m_state.get(out);} +private: + cfg_string_mt m_state; +}; + +// ATL-compatible message map entry macro for installing dropdown list context menus. +#define DROPDOWN_HISTORY_HANDLER(ctrlID,var) \ + if(uMsg == WM_CONTEXTMENU) { \ + const HWND source = (HWND) wParam; \ + if (source != NULL && source == CWindow(hWnd).GetDlgItem(ctrlID)) { \ + var.on_context(source,lParam); \ + lResult = 0; \ + return TRUE; \ + } \ + } + +#endif //_DROPDOWN_HELPER_H_ + +#endif // _WIN32 \ No newline at end of file diff --git a/SDK/foobar2000/helpers/dynamic_bitrate_helper.cpp b/SDK/foobar2000/helpers/dynamic_bitrate_helper.cpp new file mode 100644 index 0000000..1274ace --- /dev/null +++ b/SDK/foobar2000/helpers/dynamic_bitrate_helper.cpp @@ -0,0 +1,74 @@ +#include "stdafx.h" + +static unsigned g_query_settings() +{ + t_int32 temp; + try { + config_object::g_get_data_int32(standard_config_objects::int32_dynamic_bitrate_display_rate,temp); + } catch(std::exception const &) {return 9;} + if (temp < 0) return 0; + return (unsigned) temp; +} + +dynamic_bitrate_helper::dynamic_bitrate_helper() +{ + reset(); +} + +void dynamic_bitrate_helper::init() +{ + if (!m_inited) + { + m_inited = true; + unsigned temp = g_query_settings(); + if (temp > 0) {m_enabled = true; m_update_interval = 1.0 / (double) temp; } + else {m_enabled = false; m_update_interval = 0; } + m_last_duration = 0; + m_update_bits = 0; + m_update_time = 0; + + } +} + +void dynamic_bitrate_helper::on_frame(double p_duration,t_size p_bits) +{ + init(); + m_last_duration = p_duration; + m_update_time += p_duration; + m_update_bits += p_bits; +} + +bool dynamic_bitrate_helper::on_update(file_info & p_out, double & p_timestamp_delta) +{ + init(); + + bool ret = false; + if (m_enabled) + { + if (m_update_time > m_update_interval) + { + int val = (int) ( ((double)m_update_bits / m_update_time + 500.0) / 1000.0 ); + if (val != p_out.info_get_bitrate_vbr()) + { + p_timestamp_delta = - (m_update_time - m_last_duration); //relative to last frame beginning; + p_out.info_set_bitrate_vbr(val); + ret = true; + } + m_update_bits = 0; + m_update_time = 0; + } + } + else + { + m_update_bits = 0; + m_update_time = 0; + } + + return ret; + +} + +void dynamic_bitrate_helper::reset() +{ + m_inited = false; +} diff --git a/SDK/foobar2000/helpers/dynamic_bitrate_helper.h b/SDK/foobar2000/helpers/dynamic_bitrate_helper.h new file mode 100644 index 0000000..40ef0fa --- /dev/null +++ b/SDK/foobar2000/helpers/dynamic_bitrate_helper.h @@ -0,0 +1,15 @@ +class dynamic_bitrate_helper +{ +public: + dynamic_bitrate_helper(); + void on_frame(double p_duration,t_size p_bits); + bool on_update(file_info & p_out, double & p_timestamp_delta); + void reset(); +private: + void init(); + double m_last_duration; + t_size m_update_bits; + double m_update_time; + double m_update_interval; + bool m_inited, m_enabled; +}; \ No newline at end of file diff --git a/SDK/foobar2000/helpers/fb2k_threads.h b/SDK/foobar2000/helpers/fb2k_threads.h new file mode 100644 index 0000000..c91ebd9 --- /dev/null +++ b/SDK/foobar2000/helpers/fb2k_threads.h @@ -0,0 +1,86 @@ +inline static t_size GetOptimalWorkerThreadCount() throw() { + return pfc::getOptimalWorkerThreadCount(); +} + +//! IMPORTANT: all classes derived from CVerySimpleThread must call WaitTillThreadDone() in their destructor, to avoid object destruction during a virtual function call! +class CVerySimpleThread : private pfc::thread { +public: + void StartThread(int priority) { + this->pfc::thread::startWithPriority( priority ); + } + void StartThread() { + this->StartThread( pfc::thread::currentPriority() ); + } + + bool IsThreadActive() const { + return this->pfc::thread::isActive(); + } + void WaitTillThreadDone() { + this->pfc::thread::waitTillDone(); + } +protected: + CVerySimpleThread() {} + virtual void ThreadProc() = 0; +private: + + void threadProc() { + this->ThreadProc(); + } + + PFC_CLASS_NOT_COPYABLE_EX(CVerySimpleThread) +}; + +//! IMPORTANT: all classes derived from CSimpleThread must call AbortThread()/WaitTillThreadDone() in their destructors, to avoid object destruction during a virtual function call! +class CSimpleThread : private completion_notify_receiver, private pfc::thread { +public: + void StartThread(int priority) { + AbortThread(); + m_abort.reset(); + m_ownNotify = create_task(0); + this->pfc::thread::startWithPriority( priority ); + } + void StartThread() { + this->StartThread( pfc::thread::currentPriority () ); + } + void AbortThread() { + m_abort.abort(); + CloseThread(); + } + bool IsThreadActive() const { + return this->pfc::thread::isActive(); + } + void WaitTillThreadDone() { + CloseThread(); + } +protected: + CSimpleThread() {} + ~CSimpleThread() {AbortThread();} + + virtual unsigned ThreadProc(abort_callback & p_abort) = 0; + //! Called when the thread has completed normally, with p_code equal to ThreadProc retval. Not called when AbortThread() or WaitTillThreadDone() was used to abort the thread / wait for the thread to finish. + virtual void ThreadDone(unsigned p_code) {}; +private: + void CloseThread() { + this->pfc::thread::waitTillDone(); + orphan_all_tasks(); + } + + void on_task_completion(unsigned p_id,unsigned p_status) { + if (IsThreadActive()) { + CloseThread(); + ThreadDone(p_status); + } + } + void threadProc() { + unsigned code = ~0; + try { + code = ThreadProc(m_abort); + } catch(...) {} + if (!m_abort.is_aborting()) m_ownNotify->on_completion_async(code); + } + abort_callback_impl m_abort; + completion_notify_ptr m_ownNotify; + + PFC_CLASS_NOT_COPYABLE_EX(CSimpleThread); +}; + diff --git a/SDK/foobar2000/helpers/file_cached.h b/SDK/foobar2000/helpers/file_cached.h new file mode 100644 index 0000000..cc60fe8 --- /dev/null +++ b/SDK/foobar2000/helpers/file_cached.h @@ -0,0 +1 @@ +// obsolete, moved to SDK \ No newline at end of file diff --git a/SDK/foobar2000/helpers/file_info_const_impl.cpp b/SDK/foobar2000/helpers/file_info_const_impl.cpp new file mode 100644 index 0000000..a923a25 --- /dev/null +++ b/SDK/foobar2000/helpers/file_info_const_impl.cpp @@ -0,0 +1,284 @@ +#include "stdafx.h" + +// presorted - do not change without a proper strcmp resort +static const char * const standard_fieldnames[] = { + "ALBUM","ALBUM ARTIST","ARTIST","Album","Album Artist","Artist","COMMENT","Comment","DATE","DISCNUMBER","Date", + "Discnumber","GENRE","Genre","TITLE","TOTALTRACKS","TRACKNUMBER","Title","TotalTracks","Totaltracks","TrackNumber", + "Tracknumber","album","album artist","artist","comment","date","discnumber","genre","title","totaltracks","tracknumber", +}; + +// presorted - do not change without a proper strcmp resort +static const char * const standard_infonames[] = { + "bitrate","bitspersample","channels","codec","codec_profile","encoding","samplerate","tagtype","tool", +}; + +static const char * optimize_fieldname(const char * p_string) { + t_size index; + if (!pfc::binarySearch::run(standard_fieldnames,0,PFC_TABSIZE(standard_fieldnames),p_string,index)) return NULL; + return standard_fieldnames[index]; +} + +static const char * optimize_infoname(const char * p_string) { + t_size index; + if (!pfc::binarySearch::run(standard_infonames,0,PFC_TABSIZE(standard_infonames),p_string,index)) return NULL; + return standard_infonames[index]; +} + +/* +order of things + + meta entries + meta value map + info entries + string buffer + +*/ + +inline static char* stringbuffer_append(char * & buffer,const char * value) +{ + char * ret = buffer; + while(*value) *(buffer++) = *(value++); + *(buffer++) = 0; + return ret; +} + +#ifdef __file_info_const_impl_have_hintmap__ + +namespace { + class sort_callback_hintmap_impl : public pfc::sort_callback + { + public: + sort_callback_hintmap_impl(const file_info_const_impl::meta_entry * p_meta,file_info_const_impl::t_index * p_hintmap) + : m_meta(p_meta), m_hintmap(p_hintmap) + { + } + + int compare(t_size p_index1, t_size p_index2) const + { +// profiler(sort_callback_hintmap_impl_compare); + return pfc::stricmp_ascii(m_meta[m_hintmap[p_index1]].m_name,m_meta[m_hintmap[p_index2]].m_name); + } + + void swap(t_size p_index1, t_size p_index2) + { + pfc::swap_t(m_hintmap[p_index1],m_hintmap[p_index2]); + } + private: + const file_info_const_impl::meta_entry * m_meta; + file_info_const_impl::t_index * m_hintmap; + }; + + class bsearch_callback_hintmap_impl// : public pfc::bsearch_callback + { + public: + bsearch_callback_hintmap_impl( + const file_info_const_impl::meta_entry * p_meta, + const file_info_const_impl::t_index * p_hintmap, + const char * p_name, + t_size p_name_length) + : m_meta(p_meta), m_hintmap(p_hintmap), m_name(p_name), m_name_length(p_name_length) + { + } + + inline int test(t_size p_index) const + { + return pfc::stricmp_ascii_ex(m_meta[m_hintmap[p_index]].m_name,~0,m_name,m_name_length); + } + + private: + const file_info_const_impl::meta_entry * m_meta; + const file_info_const_impl::t_index * m_hintmap; + const char * m_name; + t_size m_name_length; + }; +} + +#endif//__file_info_const_impl_have_hintmap__ + +void file_info_const_impl::copy(const file_info & p_source) +{ +// profiler(file_info_const_impl__copy); + t_size meta_size = 0; + t_size info_size = 0; + t_size valuemap_size = 0; + t_size stringbuffer_size = 0; +#ifdef __file_info_const_impl_have_hintmap__ + t_size hintmap_size = 0; +#endif + + const char * optbuf[64]; + size_t optwalk = 0; + + { +// profiler(file_info_const_impl__copy__pass1); + t_size index; + m_meta_count = pfc::downcast_guarded(p_source.meta_get_count()); + meta_size = m_meta_count * sizeof(meta_entry); +#ifdef __file_info_const_impl_have_hintmap__ + hintmap_size = (m_meta_count > hintmap_cutoff) ? m_meta_count * sizeof(t_index) : 0; +#endif//__file_info_const_impl_have_hintmap__ + for(index = 0; index < m_meta_count; index++ ) + { + { + const char * name = p_source.meta_enum_name(index); + const char * opt = optimize_fieldname(name); + if (optwalk < _countof(optbuf)) optbuf[optwalk++] = opt; + if (opt == NULL) stringbuffer_size += strlen(name) + 1; + } + + t_size val; const t_size val_max = p_source.meta_enum_value_count(index); + + if (val_max == 1) + { + stringbuffer_size += strlen(p_source.meta_enum_value(index,0)) + 1; + } + else + { + valuemap_size += val_max * sizeof(char*); + + for(val = 0; val < val_max; val++ ) + { + stringbuffer_size += strlen(p_source.meta_enum_value(index,val)) + 1; + } + } + } + + m_info_count = pfc::downcast_guarded(p_source.info_get_count()); + info_size = m_info_count * sizeof(info_entry); + for(index = 0; index < m_info_count; index++ ) + { + const char * name = p_source.info_enum_name(index); + const char * opt = optimize_infoname(name); + if (optwalk < _countof(optbuf)) optbuf[optwalk++] = opt; + if (opt == NULL) stringbuffer_size += strlen(name) + 1; + stringbuffer_size += strlen(p_source.info_enum_value(index)) + 1; + } + } + + + { +// profiler(file_info_const_impl__copy__alloc); + m_buffer.set_size( +#ifdef __file_info_const_impl_have_hintmap__ + hintmap_size + +#endif + meta_size + info_size + valuemap_size + stringbuffer_size); + } + + char * walk = m_buffer.get_ptr(); + +#ifdef __file_info_const_impl_have_hintmap__ + t_index* hintmap = (hintmap_size > 0) ? (t_index*) walk : NULL; + walk += hintmap_size; +#endif + meta_entry * meta = (meta_entry*) walk; + walk += meta_size; + char ** valuemap = (char**) walk; + walk += valuemap_size; + info_entry * info = (info_entry*) walk; + walk += info_size; + char * stringbuffer = walk; + + m_meta = meta; + m_info = info; +#ifdef __file_info_const_impl_have_hintmap__ + m_hintmap = hintmap; +#endif + + optwalk = 0; + { +// profiler(file_info_const_impl__copy__pass2); + t_size index; + for( index = 0; index < m_meta_count; index ++ ) + { + t_size val; const t_size val_max = p_source.meta_enum_value_count(index); + + { + const char * name = p_source.meta_enum_name(index); + const char * name_opt; + + if (optwalk < _countof(optbuf)) name_opt = optbuf[optwalk++]; + else name_opt = optimize_fieldname(name); + + if (name_opt == NULL) + meta[index].m_name = stringbuffer_append(stringbuffer, name ); + else + meta[index].m_name = name_opt; + } + + meta[index].m_valuecount = val_max; + + if (val_max == 1) + { + meta[index].m_valuemap = reinterpret_cast(stringbuffer_append(stringbuffer, p_source.meta_enum_value(index,0) )); + } + else + { + meta[index].m_valuemap = valuemap; + for( val = 0; val < val_max ; val ++ ) + *(valuemap ++ ) = stringbuffer_append(stringbuffer, p_source.meta_enum_value(index,val) ); + } + } + + for( index = 0; index < m_info_count; index ++ ) + { + const char * name = p_source.info_enum_name(index); + const char * name_opt; + + if (optwalk < _countof(optbuf)) name_opt = optbuf[optwalk++]; + else name_opt = optimize_infoname(name); + + if (name_opt == NULL) + info[index].m_name = stringbuffer_append(stringbuffer, name ); + else + info[index].m_name = name_opt; + info[index].m_value = stringbuffer_append(stringbuffer, p_source.info_enum_value(index) ); + } + } + + m_length = p_source.get_length(); + m_replaygain = p_source.get_replaygain(); +#ifdef __file_info_const_impl_have_hintmap__ + if (hintmap != NULL) { +// profiler(file_info_const_impl__copy__hintmap); + for(t_size n=0;n(entry.m_valuemap); + else + return entry.m_valuemap[p_value_number]; +} diff --git a/SDK/foobar2000/helpers/file_info_const_impl.h b/SDK/foobar2000/helpers/file_info_const_impl.h new file mode 100644 index 0000000..42df645 --- /dev/null +++ b/SDK/foobar2000/helpers/file_info_const_impl.h @@ -0,0 +1,78 @@ +#define __file_info_const_impl_have_hintmap__ + +//! Special implementation of file_info that implements only const and copy methods. The difference between this and regular file_info_impl is amount of resources used and speed of the copy operation. +class file_info_const_impl : public file_info +{ +public: + file_info_const_impl(const file_info & p_source) {copy(p_source);} + file_info_const_impl(const file_info_const_impl & p_source) {copy(p_source);} + file_info_const_impl() {m_meta_count = m_info_count = 0; m_length = 0; m_replaygain.reset();} + + double get_length() const {return m_length;} + + t_size meta_get_count() const {return m_meta_count;} + const char* meta_enum_name(t_size p_index) const {return m_meta[p_index].m_name;} + t_size meta_enum_value_count(t_size p_index) const; + const char* meta_enum_value(t_size p_index,t_size p_value_number) const; + t_size meta_find_ex(const char * p_name,t_size p_name_length) const; + + t_size info_get_count() const {return m_info_count;} + const char* info_enum_name(t_size p_index) const {return m_info[p_index].m_name;} + const char* info_enum_value(t_size p_index) const {return m_info[p_index].m_value;} + + + const file_info_const_impl & operator=(const file_info & p_source) {copy(p_source); return *this;} + const file_info_const_impl & operator=(const file_info_const_impl & p_source) {copy(p_source); return *this;} + void copy(const file_info & p_source); + void reset(); + + replaygain_info get_replaygain() const {return m_replaygain;} + +private: + void set_length(double p_length) {uBugCheck();} + + t_size meta_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) {uBugCheck();} + void meta_insert_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length) {uBugCheck();} + void meta_remove_mask(const bit_array & p_mask) {uBugCheck();} + void meta_reorder(const t_size * p_order) {uBugCheck();} + void meta_remove_values(t_size p_index,const bit_array & p_mask) {uBugCheck();} + void meta_modify_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length) {uBugCheck();} + + t_size info_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) {uBugCheck();} + void info_remove_mask(const bit_array & p_mask) {uBugCheck();} + + void set_replaygain(const replaygain_info & p_info) {uBugCheck();} + + t_size meta_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) {uBugCheck();} + t_size info_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) {uBugCheck();} +public: + struct meta_entry { + const char * m_name; + t_size m_valuecount; + const char * const * m_valuemap; + }; + + struct info_entry { + const char * m_name; + const char * m_value; + }; + +#ifdef __file_info_const_impl_have_hintmap__ + typedef t_uint32 t_index; + enum {hintmap_cutoff = 20}; +#endif//__file_info_const_impl_have_hintmap__ +private: + pfc::array_t m_buffer; + t_index m_meta_count; + t_index m_info_count; + + const meta_entry * m_meta; + const info_entry * m_info; + +#ifdef __file_info_const_impl_have_hintmap__ + const t_index * m_hintmap; +#endif + + double m_length; + replaygain_info m_replaygain; +}; diff --git a/SDK/foobar2000/helpers/file_list_helper.cpp b/SDK/foobar2000/helpers/file_list_helper.cpp new file mode 100644 index 0000000..e4baf6a --- /dev/null +++ b/SDK/foobar2000/helpers/file_list_helper.cpp @@ -0,0 +1,74 @@ +#include "stdafx.h" + +#ifndef _MSC_VER +#define _strdup strdup +#endif + +static void file_list_remove_duplicates(pfc::ptr_list_t & out) +{ + t_size n, m = out.get_count(); + out.sort_t(metadb::path_compare); + bit_array_bittable mask(m); + t_size duplicates = 0; + for(n=1;n0) { + out.free_mask(mask); + } +} + + +namespace file_list_helper +{ + t_size file_list_from_metadb_handle_list::g_get_count(metadb_handle_list_cref data, t_size max) { + pfc::avltree_t content; + const t_size inCount = data.get_size(); + for(t_size walk = 0; walk < inCount && content.get_count() < max; ++walk) { + content += data[walk]->get_path(); + } + return content.get_count(); + } + void file_list_from_metadb_handle_list::__add(const char * p_what) { + char * temp = _strdup(p_what); + if (temp == NULL) throw std::bad_alloc(); + try {m_data.add_item(temp); } catch(...) {free(temp); throw;} + } + + void file_list_from_metadb_handle_list::init_from_list(const list_base_const_t & p_list) + { + m_data.free_all(); + + t_size n, m = p_list.get_count(); + for(n=0;nget_path() ); + } + file_list_remove_duplicates(m_data); + } + + void file_list_from_metadb_handle_list::init_from_list_display(const list_base_const_t & p_list) + { + m_data.free_all(); + + pfc::string8_fastalloc temp; + + t_size n, m = p_list.get_count(); + for(n=0;nget_path(),temp); + __add(temp); + } + file_list_remove_duplicates(m_data); + + + } + + t_size file_list_from_metadb_handle_list::get_count() const {return m_data.get_count();} + void file_list_from_metadb_handle_list::get_item_ex(const char * & p_out,t_size n) const {p_out = m_data.get_item(n);} + + file_list_from_metadb_handle_list::~file_list_from_metadb_handle_list() + { + m_data.free_all(); + } + +} \ No newline at end of file diff --git a/SDK/foobar2000/helpers/file_list_helper.h b/SDK/foobar2000/helpers/file_list_helper.h new file mode 100644 index 0000000..5779a2f --- /dev/null +++ b/SDK/foobar2000/helpers/file_list_helper.h @@ -0,0 +1,30 @@ +#ifndef _foobar2000_helpers_file_list_helper_ +#define _foobar2000_helpers_file_list_helper_ + + +namespace file_list_helper +{ + //list guaranteed to be sorted by metadb::path_compare + class file_list_from_metadb_handle_list : public pfc::list_base_const_t { + public: + + static t_size g_get_count(const list_base_const_t & p_list, t_size max = ~0); + + void init_from_list(const list_base_const_t & p_list); + void init_from_list_display(const list_base_const_t & p_list); + + t_size get_count() const; + void get_item_ex(const char * & p_out,t_size n) const; + + ~file_list_from_metadb_handle_list(); + + private: + void __add(const char * p_what); + pfc::ptr_list_t m_data; + }; + + +}; + + +#endif //_foobar2000_helpers_file_list_helper_ \ No newline at end of file diff --git a/SDK/foobar2000/helpers/file_move_helper.cpp b/SDK/foobar2000/helpers/file_move_helper.cpp new file mode 100644 index 0000000..a15bb67 --- /dev/null +++ b/SDK/foobar2000/helpers/file_move_helper.cpp @@ -0,0 +1,38 @@ +#include "stdafx.h" + +bool file_move_helper::g_on_deleted(const pfc::list_base_const_t & p_files) +{ + file_operation_callback::g_on_files_deleted(p_files); + return true; +} + +t_size file_move_helper::g_filter_dead_files_sorted_make_mask(pfc::list_base_t & p_data,const pfc::list_base_const_t & p_dead,bit_array_var & p_mask) +{ + t_size n, m = p_data.get_count(); + t_size found = 0; + for(n=0;nget_path(),dummy); + if (dead) found++; + p_mask.set(n,dead); + } + return found; +} + +t_size file_move_helper::g_filter_dead_files_sorted(pfc::list_base_t & p_data,const pfc::list_base_const_t & p_dead) +{ + bit_array_bittable mask(p_data.get_count()); + t_size found = g_filter_dead_files_sorted_make_mask(p_data,p_dead,mask); + if (found > 0) p_data.remove_mask(mask); + return found; +} + +t_size file_move_helper::g_filter_dead_files(pfc::list_base_t & p_data,const pfc::list_base_const_t & p_dead) +{ + pfc::ptr_list_t temp; + temp.add_items(p_dead); + temp.sort_t(metadb::path_compare); + return g_filter_dead_files_sorted(p_data,temp); +} + diff --git a/SDK/foobar2000/helpers/file_move_helper.h b/SDK/foobar2000/helpers/file_move_helper.h new file mode 100644 index 0000000..42f9a4b --- /dev/null +++ b/SDK/foobar2000/helpers/file_move_helper.h @@ -0,0 +1,8 @@ +class file_move_helper { +public: + static bool g_on_deleted(const pfc::list_base_const_t & p_files); + + static t_size g_filter_dead_files_sorted_make_mask(pfc::list_base_t & p_data,const pfc::list_base_const_t & p_dead,bit_array_var & p_mask); + static t_size g_filter_dead_files_sorted(pfc::list_base_t & p_data,const pfc::list_base_const_t & p_dead); + static t_size g_filter_dead_files(pfc::list_base_t & p_data,const pfc::list_base_const_t & p_dead); +}; diff --git a/SDK/foobar2000/helpers/file_win32_wrapper.cpp b/SDK/foobar2000/helpers/file_win32_wrapper.cpp new file mode 100644 index 0000000..c996a62 --- /dev/null +++ b/SDK/foobar2000/helpers/file_win32_wrapper.cpp @@ -0,0 +1,240 @@ +#include "stdafx.h" + +#ifdef _WIN32 +namespace file_win32_helpers { + t_filesize get_size(HANDLE p_handle) { + union { + t_uint64 val64; + t_uint32 val32[2]; + } u; + + u.val64 = 0; + SetLastError(NO_ERROR); + u.val32[0] = GetFileSize(p_handle,reinterpret_cast(&u.val32[1])); + if (GetLastError()!=NO_ERROR) exception_io_from_win32(GetLastError()); + return u.val64; + } + void seek(HANDLE p_handle,t_sfilesize p_position,file::t_seek_mode p_mode) { + union { + t_int64 temp64; + struct { + DWORD temp_lo; + LONG temp_hi; + }; + }; + + temp64 = p_position; + SetLastError(ERROR_SUCCESS); + temp_lo = SetFilePointer(p_handle,temp_lo,&temp_hi,(DWORD)p_mode); + if (GetLastError() != ERROR_SUCCESS) exception_io_from_win32(GetLastError()); + } + + void fillOverlapped(OVERLAPPED & ol, HANDLE myEvent, t_filesize s) { + ol.hEvent = myEvent; + ol.Offset = (DWORD)( s & 0xFFFFFFFF ); + ol.OffsetHigh = (DWORD)(s >> 32); + } + + void writeOverlappedPass(HANDLE handle, HANDLE myEvent, t_filesize position, const void * in,DWORD inBytes, abort_callback & abort) { + abort.check(); + if (inBytes == 0) return; + OVERLAPPED ol = {}; + fillOverlapped(ol, myEvent, position); + ResetEvent(myEvent); + DWORD bytesWritten; + SetLastError(NO_ERROR); + if (WriteFile( handle, in, inBytes, &bytesWritten, &ol)) { + // succeeded already? + if (bytesWritten != inBytes) throw exception_io(); + return; + } + + { + const DWORD code = GetLastError(); + if (code != ERROR_IO_PENDING) exception_io_from_win32(code); + } + const HANDLE handles[] = {myEvent, abort.get_abort_event()}; + SetLastError(NO_ERROR); + DWORD state = WaitForMultipleObjects(_countof(handles), handles, FALSE, INFINITE); + if (state == WAIT_OBJECT_0) { + try { + WIN32_IO_OP( GetOverlappedResult(handle,&ol,&bytesWritten,TRUE) ); + } catch(...) { + CancelIo(handle); + throw; + } + if (bytesWritten != inBytes) throw exception_io(); + return; + } + CancelIo(handle); + throw exception_aborted(); + } + + void writeOverlapped(HANDLE handle, HANDLE myEvent, t_filesize & position, const void * in, size_t inBytes, abort_callback & abort) { + const enum {writeMAX = 16*1024*1024}; + size_t done = 0; + while(done < inBytes) { + size_t delta = inBytes - done; + if (delta > writeMAX) delta = writeMAX; + writeOverlappedPass(handle, myEvent, position, (const BYTE*)in + done, (DWORD) delta, abort); + done += delta; + position += delta; + } + } + void writeStreamOverlapped(HANDLE handle, HANDLE myEvent, const void * in, size_t inBytes, abort_callback & abort) { + const enum {writeMAX = 16*1024*1024}; + size_t done = 0; + while(done < inBytes) { + size_t delta = inBytes - done; + if (delta > writeMAX) delta = writeMAX; + writeOverlappedPass(handle, myEvent, 0, (const BYTE*)in + done, (DWORD) delta, abort); + done += delta; + } + } + + DWORD readOverlappedPass(HANDLE handle, HANDLE myEvent, t_filesize position, void * out, DWORD outBytes, abort_callback & abort) { + abort.check(); + if (outBytes == 0) return 0; + OVERLAPPED ol = {}; + fillOverlapped(ol, myEvent, position); + ResetEvent(myEvent); + DWORD bytesDone; + SetLastError(NO_ERROR); + if (ReadFile( handle, out, outBytes, &bytesDone, &ol)) { + // succeeded already? + return bytesDone; + } + + { + const DWORD code = GetLastError(); + switch(code) { + case ERROR_HANDLE_EOF: + case ERROR_BROKEN_PIPE: + return 0; + case ERROR_IO_PENDING: + break; // continue + default: + exception_io_from_win32(code); + }; + } + + const HANDLE handles[] = {myEvent, abort.get_abort_event()}; + SetLastError(NO_ERROR); + DWORD state = WaitForMultipleObjects(_countof(handles), handles, FALSE, INFINITE); + if (state == WAIT_OBJECT_0) { + SetLastError(NO_ERROR); + if (!GetOverlappedResult(handle,&ol,&bytesDone,TRUE)) { + const DWORD code = GetLastError(); + if (code == ERROR_HANDLE_EOF || code == ERROR_BROKEN_PIPE) bytesDone = 0; + else { + CancelIo(handle); + exception_io_from_win32(code); + } + } + return bytesDone; + } + CancelIo(handle); + throw exception_aborted(); + } + size_t readOverlapped(HANDLE handle, HANDLE myEvent, t_filesize & position, void * out, size_t outBytes, abort_callback & abort) { + const enum {readMAX = 16*1024*1024}; + size_t done = 0; + while(done < outBytes) { + size_t delta = outBytes - done; + if (delta > readMAX) delta = readMAX; + delta = readOverlappedPass(handle, myEvent, position, (BYTE*) out + done, (DWORD) delta, abort); + if (delta == 0) break; + done += delta; + position += delta; + } + return done; + } + + size_t readStreamOverlapped(HANDLE handle, HANDLE myEvent, void * out, size_t outBytes, abort_callback & abort) { + const enum {readMAX = 16*1024*1024}; + size_t done = 0; + while(done < outBytes) { + size_t delta = outBytes - done; + if (delta > readMAX) delta = readMAX; + delta = readOverlappedPass(handle, myEvent, 0, (BYTE*) out + done, (DWORD) delta, abort); + if (delta == 0) break; + done += delta; + } + return done; + } + + typedef BOOL (WINAPI * pCancelSynchronousIo_t)(HANDLE hThread); + + + struct createFileData_t { + LPCTSTR lpFileName; + DWORD dwDesiredAccess; + DWORD dwShareMode; + LPSECURITY_ATTRIBUTES lpSecurityAttributes; + DWORD dwCreationDisposition; + DWORD dwFlagsAndAttributes; + HANDLE hTemplateFile; + HANDLE hResult; + DWORD dwErrorCode; + }; + + static unsigned CALLBACK createFileProc(void * data) { + createFileData_t * cfd = (createFileData_t*)data; + SetLastError(0); + cfd->hResult = CreateFile(cfd->lpFileName, cfd->dwDesiredAccess, cfd->dwShareMode, cfd->lpSecurityAttributes, cfd->dwCreationDisposition, cfd->dwFlagsAndAttributes, cfd->hTemplateFile); + cfd->dwErrorCode = GetLastError(); + return 0; + } + + HANDLE createFile(LPCTSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile, abort_callback & abort) { + abort.check(); + + return CreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); + + // CancelSynchronousIo() doesn't fucking work. Useless. +#if 0 + pCancelSynchronousIo_t pCancelSynchronousIo = (pCancelSynchronousIo_t) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "CancelSynchronousIo"); + if (pCancelSynchronousIo == NULL) { +#ifdef _DEBUG + uDebugLog() << "Async CreateFile unavailable - using regular"; +#endif + return CreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); + } else { +#ifdef _DEBUG + uDebugLog() << "Starting async CreateFile..."; + pfc::hires_timer t; t.start(); +#endif + createFileData_t data = {lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile, NULL, 0}; + HANDLE hThread = (HANDLE) _beginthreadex(NULL, 0, createFileProc, &data, 0, NULL); + HANDLE waitHandles[2] = {hThread, abort.get_abort_event()}; + switch(WaitForMultipleObjects(2, waitHandles, FALSE, INFINITE)) { + case WAIT_OBJECT_0: // succeeded + break; + case WAIT_OBJECT_0 + 1: // abort +#ifdef _DEBUG + uDebugLog() << "Aborting async CreateFile..."; +#endif + pCancelSynchronousIo(hThread); + WaitForSingleObject(hThread, INFINITE); + break; + default: + uBugCheck(); + } + CloseHandle(hThread); + SetLastError(data.dwErrorCode); +#ifdef _DEBUG + uDebugLog() << "Async CreateFile completed in " << pfc::format_time_ex(t.query(), 6) << ", status: " << (uint32_t) data.dwErrorCode; +#endif + if (abort.is_aborting()) { + if (data.hResult != INVALID_HANDLE_VALUE) CloseHandle(data.hResult); + throw exception_aborted(); + } + return data.hResult; + } +#endif + } + +} + +#endif // _WIN32 + diff --git a/SDK/foobar2000/helpers/file_win32_wrapper.h b/SDK/foobar2000/helpers/file_win32_wrapper.h new file mode 100644 index 0000000..a4e0194 --- /dev/null +++ b/SDK/foobar2000/helpers/file_win32_wrapper.h @@ -0,0 +1,239 @@ +namespace file_win32_helpers { + t_filesize get_size(HANDLE p_handle); + void seek(HANDLE p_handle,t_sfilesize p_position,file::t_seek_mode p_mode); + void fillOverlapped(OVERLAPPED & ol, HANDLE myEvent, t_filesize s); + void writeOverlappedPass(HANDLE handle, HANDLE myEvent, t_filesize position, const void * in,DWORD inBytes, abort_callback & abort); + void writeOverlapped(HANDLE handle, HANDLE myEvent, t_filesize & position, const void * in, size_t inBytes, abort_callback & abort); + void writeStreamOverlapped(HANDLE handle, HANDLE myEvent, const void * in, size_t inBytes, abort_callback & abort); + DWORD readOverlappedPass(HANDLE handle, HANDLE myEvent, t_filesize position, void * out, DWORD outBytes, abort_callback & abort); + size_t readOverlapped(HANDLE handle, HANDLE myEvent, t_filesize & position, void * out, size_t outBytes, abort_callback & abort); + size_t readStreamOverlapped(HANDLE handle, HANDLE myEvent, void * out, size_t outBytes, abort_callback & abort); + HANDLE createFile(LPCTSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile, abort_callback & abort); +}; + +template +class file_win32_wrapper_t : public file { +public: + file_win32_wrapper_t(HANDLE p_handle) : m_handle(p_handle), m_position(0) + { + } + + static file::ptr g_CreateFile(const char * p_path,DWORD p_access,DWORD p_sharemode,LPSECURITY_ATTRIBUTES p_security_attributes,DWORD p_createmode,DWORD p_flags,HANDLE p_template) { + SetLastError(NO_ERROR); + HANDLE handle = uCreateFile(p_path,p_access,p_sharemode,p_security_attributes,p_createmode,p_flags,p_template); + if (handle == INVALID_HANDLE_VALUE) { + const DWORD code = GetLastError(); + if (p_access & GENERIC_WRITE) win32_file_write_failure(code, p_path); + else exception_io_from_win32(code); + } + try { + return g_create_from_handle(handle); + } catch(...) {CloseHandle(handle); throw;} + } + + static service_ptr_t g_create_from_handle(HANDLE p_handle) { + return new service_impl_t >(p_handle); + } + + + void reopen(abort_callback & p_abort) {seek(0,p_abort);} + + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + if (!p_writeable) throw exception_io_denied(); + + PFC_STATIC_ASSERT(sizeof(t_size) >= sizeof(DWORD)); + + t_size bytes_written_total = 0; + + if (sizeof(t_size) == sizeof(DWORD)) { + p_abort.check_e(); + DWORD bytes_written = 0; + SetLastError(ERROR_SUCCESS); + if (!WriteFile(m_handle,p_buffer,(DWORD)p_bytes,&bytes_written,0)) exception_io_from_win32(GetLastError()); + if (bytes_written != p_bytes) throw exception_io("Write failure"); + bytes_written_total = bytes_written; + m_position += bytes_written; + } else { + while(bytes_written_total < p_bytes) { + p_abort.check_e(); + DWORD bytes_written = 0; + DWORD delta = (DWORD) pfc::min_t(p_bytes - bytes_written_total, 0x80000000); + SetLastError(ERROR_SUCCESS); + if (!WriteFile(m_handle,(const t_uint8*)p_buffer + bytes_written_total,delta,&bytes_written,0)) exception_io_from_win32(GetLastError()); + if (bytes_written != delta) throw exception_io("Write failure"); + bytes_written_total += bytes_written; + m_position += bytes_written; + } + } + } + + t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + PFC_STATIC_ASSERT(sizeof(t_size) >= sizeof(DWORD)); + + t_size bytes_read_total = 0; + if (sizeof(t_size) == sizeof(DWORD)) { + p_abort.check_e(); + DWORD bytes_read = 0; + SetLastError(ERROR_SUCCESS); + if (!ReadFile(m_handle,p_buffer,pfc::downcast_guarded(p_bytes),&bytes_read,0)) exception_io_from_win32(GetLastError()); + bytes_read_total = bytes_read; + m_position += bytes_read; + } else { + while(bytes_read_total < p_bytes) { + p_abort.check_e(); + DWORD bytes_read = 0; + DWORD delta = (DWORD) pfc::min_t(p_bytes - bytes_read_total, 0x80000000); + SetLastError(ERROR_SUCCESS); + if (!ReadFile(m_handle,(t_uint8*)p_buffer + bytes_read_total,delta,&bytes_read,0)) exception_io_from_win32(GetLastError()); + bytes_read_total += bytes_read; + m_position += bytes_read; + if (bytes_read != delta) break; + } + } + return bytes_read_total; + } + + + t_filesize get_size(abort_callback & p_abort) { + p_abort.check_e(); + return file_win32_helpers::get_size(m_handle); + } + + t_filesize get_position(abort_callback & p_abort) { + p_abort.check_e(); + return m_position; + } + + void resize(t_filesize p_size,abort_callback & p_abort) { + if (!p_writeable) throw exception_io_denied(); + p_abort.check_e(); + if (m_position != p_size) { + file_win32_helpers::seek(m_handle,p_size,file::seek_from_beginning); + } + SetLastError(ERROR_SUCCESS); + if (!SetEndOfFile(m_handle)) { + DWORD code = GetLastError(); + if (m_position != p_size) try {file_win32_helpers::seek(m_handle,m_position,file::seek_from_beginning);} catch(...) {} + exception_io_from_win32(code); + } + if (m_position > p_size) m_position = p_size; + if (m_position != p_size) file_win32_helpers::seek(m_handle,m_position,file::seek_from_beginning); + } + + + void seek(t_filesize p_position,abort_callback & p_abort) { + if (!p_seekable) throw exception_io_object_not_seekable(); + p_abort.check_e(); + if (p_position > file_win32_helpers::get_size(m_handle)) throw exception_io_seek_out_of_range(); + file_win32_helpers::seek(m_handle,p_position,file::seek_from_beginning); + m_position = p_position; + } + + bool can_seek() {return p_seekable;} + bool get_content_type(pfc::string_base & out) {return false;} + bool is_in_memory() {return false;} + void on_idle(abort_callback & p_abort) {p_abort.check_e();} + + t_filetimestamp get_timestamp(abort_callback & p_abort) { + p_abort.check_e(); + FlushFileBuffers(m_handle); + SetLastError(ERROR_SUCCESS); + t_filetimestamp temp; + if (!GetFileTime(m_handle,0,0,(FILETIME*)&temp)) exception_io_from_win32(GetLastError()); + return temp; + } + + bool is_remote() {return false;} + ~file_win32_wrapper_t() {CloseHandle(m_handle);} +protected: + HANDLE m_handle; + t_filesize m_position; +}; + +template +class file_win32_wrapper_overlapped_t : public file { +public: + file_win32_wrapper_overlapped_t(HANDLE file) : m_handle(file), m_position() { + WIN32_OP( (m_event = CreateEvent(NULL, TRUE, FALSE, NULL)) != NULL ); + } + ~file_win32_wrapper_overlapped_t() {CloseHandle(m_event); CloseHandle(m_handle);} + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + if (!p_writeable) throw exception_io_denied(); + return file_win32_helpers::writeOverlapped(m_handle, m_event, m_position, p_buffer, p_bytes, p_abort); + } + t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + return file_win32_helpers::readOverlapped(m_handle, m_event, m_position, p_buffer, p_bytes, p_abort); + } + + void reopen(abort_callback & p_abort) {seek(0,p_abort);} + + + t_filesize get_size(abort_callback & p_abort) { + p_abort.check_e(); + return file_win32_helpers::get_size(m_handle); + } + + t_filesize get_position(abort_callback & p_abort) { + p_abort.check_e(); + return m_position; + } + + void resize(t_filesize p_size,abort_callback & p_abort) { + if (!p_writeable) throw exception_io_denied(); + p_abort.check_e(); + file_win32_helpers::seek(m_handle,p_size,file::seek_from_beginning); + SetLastError(ERROR_SUCCESS); + if (!SetEndOfFile(m_handle)) { + DWORD code = GetLastError(); + exception_io_from_win32(code); + } + if (m_position > p_size) m_position = p_size; + } + + + void seek(t_filesize p_position,abort_callback & p_abort) { + p_abort.check_e(); + if (p_position > file_win32_helpers::get_size(m_handle)) throw exception_io_seek_out_of_range(); + // file_win32_helpers::seek(m_handle,p_position,file::seek_from_beginning); + m_position = p_position; + } + + bool can_seek() {return true;} + bool get_content_type(pfc::string_base & out) {return false;} + bool is_in_memory() {return false;} + void on_idle(abort_callback & p_abort) {p_abort.check_e();} + + t_filetimestamp get_timestamp(abort_callback & p_abort) { + p_abort.check_e(); + FlushFileBuffers(m_handle); + SetLastError(ERROR_SUCCESS); + t_filetimestamp temp; + if (!GetFileTime(m_handle,0,0,(FILETIME*)&temp)) exception_io_from_win32(GetLastError()); + return temp; + } + + bool is_remote() {return false;} + + + static file::ptr g_CreateFile(const char * p_path,DWORD p_access,DWORD p_sharemode,LPSECURITY_ATTRIBUTES p_security_attributes,DWORD p_createmode,DWORD p_flags,HANDLE p_template) { + p_flags |= FILE_FLAG_OVERLAPPED; + SetLastError(NO_ERROR); + HANDLE handle = uCreateFile(p_path,p_access,p_sharemode,p_security_attributes,p_createmode,p_flags,p_template); + if (handle == INVALID_HANDLE_VALUE) { + const DWORD code = GetLastError(); + if (p_access & GENERIC_WRITE) win32_file_write_failure(code, p_path); + else exception_io_from_win32(code); + } + try { + return g_create_from_handle(handle); + } catch(...) {CloseHandle(handle); throw;} + } + + static file::ptr g_create_from_handle(HANDLE p_handle) { + return new service_impl_t >(p_handle); + } + +protected: + HANDLE m_event, m_handle; + t_filesize m_position; +}; diff --git a/SDK/foobar2000/helpers/filetimetools.cpp b/SDK/foobar2000/helpers/filetimetools.cpp new file mode 100644 index 0000000..e352070 --- /dev/null +++ b/SDK/foobar2000/helpers/filetimetools.cpp @@ -0,0 +1,101 @@ +#include "stdafx.h" + + +#ifndef _WIN32 +#error PORTME +#endif + +static bool is_spacing(char c) {return c == ' ' || c==10 || c==13 || c == '\t';} + +static bool is_spacing(const char * str, t_size len) { + for(t_size walk = 0; walk < len; ++walk) if (!is_spacing(str[walk])) return false; + return true; +} + +typedef exception_io_data exception_time_error; + +static unsigned ParseDateElem(const char * ptr, t_size len) { + unsigned ret = 0; + for(t_size walk = 0; walk < len; ++walk) { + const char c = ptr[walk]; + if (c < '0' || c > '9') throw exception_time_error(); + ret = ret * 10 + (unsigned)(c - '0'); + } + return ret; +} + +t_filetimestamp foobar2000_io::filetimestamp_from_string(const char * date) { + // Accepted format + // YYYY-MM-DD HH:MM:SS + try { + t_size remaining = strlen(date); + SYSTEMTIME st = {}; + st.wDay = 1; st.wMonth = 1; + for(;;) { +#define ADVANCE(n) { PFC_ASSERT( remaining >= n); date += n; remaining -= n; } +#define ADVANCE_TEST(n) { if (remaining < n) throw exception_time_error(); } +#define PARSE(var, digits) { ADVANCE_TEST(digits); var = (WORD) ParseDateElem(date, digits); ADVANCE(digits) ; } +#define TEST_END( durationIncrement ) +#define SKIP(c) { ADVANCE_TEST(1); if (date[0] != c) throw exception_time_error(); ADVANCE(1); } +#define SKIP_SPACING() {while(remaining > 0 && is_spacing(*date)) ADVANCE(1);} + SKIP_SPACING(); + PARSE( st.wYear, 4 ); if (st.wYear < 1601) throw exception_time_error(); + TEST_END(wYear); SKIP('-'); + PARSE( st.wMonth, 2 ); if (st.wMonth < 1 || st.wMonth > 12) throw exception_time_error(); + TEST_END(wMonth); SKIP('-'); + PARSE( st.wDay, 2); if (st.wDay < 1 || st.wDay > 31) throw exception_time_error(); + TEST_END(wDay); SKIP(' '); + PARSE( st.wHour, 2); if (st.wHour >= 24) throw exception_time_error(); + TEST_END(wHour); SKIP(':'); + PARSE( st.wMinute, 2); if (st.wMinute >= 60) throw exception_time_error(); + TEST_END(wMinute); SKIP(':'); + PARSE( st.wSecond, 2); if (st.wSecond >= 60) throw exception_time_error(); + SKIP_SPACING(); + TEST_END( wSecond ); +#undef ADVANCE +#undef ADVANCE_TEST +#undef PARSE +#undef TEST_END +#undef SKIP +#undef SKIP_SPACING + if (remaining > 0) throw exception_time_error(); + break; + } + t_filetimestamp base, out; + if (!SystemTimeToFileTime(&st, (FILETIME*) &base)) throw exception_time_error(); + if (!LocalFileTimeToFileTime((const FILETIME*)&base, (FILETIME*)&out)) throw exception_time_error(); + return out; + } catch(exception_time_error) { + return filetimestamp_invalid; + } +} + +static const char g_invalidMsg[] = ""; + +format_filetimestamp::format_filetimestamp(t_filetimestamp p_timestamp) { + try { + SYSTEMTIME st; FILETIME ft; + if (FileTimeToLocalFileTime((FILETIME*)&p_timestamp,&ft)) { + if (FileTimeToSystemTime(&ft,&st)) { + m_buffer + << pfc::format_uint(st.wYear,4) << "-" << pfc::format_uint(st.wMonth,2) << "-" << pfc::format_uint(st.wDay,2) << " " + << pfc::format_uint(st.wHour,2) << ":" << pfc::format_uint(st.wMinute,2) << ":" << pfc::format_uint(st.wSecond,2); + return; + } + } + } catch(...) {} + m_buffer = g_invalidMsg; +} + +format_filetimestamp_utc::format_filetimestamp_utc(t_filetimestamp p_timestamp) { + try { + SYSTEMTIME st; + if (FileTimeToSystemTime((const FILETIME*)&p_timestamp,&st)) { + m_buffer + << pfc::format_uint(st.wYear,4) << "-" << pfc::format_uint(st.wMonth,2) << "-" << pfc::format_uint(st.wDay,2) << " " + << pfc::format_uint(st.wHour,2) << ":" << pfc::format_uint(st.wMinute,2) << ":" << pfc::format_uint(st.wSecond,2); + return; + } + } catch(...) {} + m_buffer = g_invalidMsg; +} diff --git a/SDK/foobar2000/helpers/filetimetools.h b/SDK/foobar2000/helpers/filetimetools.h new file mode 100644 index 0000000..89f2e5a --- /dev/null +++ b/SDK/foobar2000/helpers/filetimetools.h @@ -0,0 +1,23 @@ +namespace foobar2000_io { + t_filetimestamp filetimestamp_from_string(const char * date); + + //! Warning: this formats according to system timezone settings, created strings should be used for display only, never for storage. + class format_filetimestamp { + public: + format_filetimestamp(t_filetimestamp p_timestamp); + operator const char*() const {return m_buffer;} + const char * get_ptr() const {return m_buffer;} + private: + pfc::string_fixed_t<32> m_buffer; + }; + + class format_filetimestamp_utc { + public: + format_filetimestamp_utc(t_filetimestamp p_timestamp); + operator const char*() const {return m_buffer;} + const char * get_ptr() const {return m_buffer;} + private: + pfc::string_fixed_t<32> m_buffer; + }; + +} diff --git a/SDK/foobar2000/helpers/foobar2000_sdk_helpers.vcxproj b/SDK/foobar2000/helpers/foobar2000_sdk_helpers.vcxproj new file mode 100644 index 0000000..f468ff0 --- /dev/null +++ b/SDK/foobar2000/helpers/foobar2000_sdk_helpers.vcxproj @@ -0,0 +1,317 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {EE47764E-A202-4F85-A767-ABDAB4AFF35F} + foobar2000_sdk_helpers + + + + StaticLibrary + false + Unicode + v143 + + + StaticLibrary + false + Unicode + true + v143 + + + StaticLibrary + false + Unicode + v143 + + + StaticLibrary + false + Unicode + true + v143 + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(SolutionDir)$(Configuration)\ + $(Configuration)\ + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + $(SolutionDir)$(Configuration)\ + $(Configuration)\ + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + + + + MinSpace + WIN32;NDEBUG;_WINDOWS;_WIN32_WINNT=0x501;%(PreprocessorDefinitions) + true + false + Fast + false + Use + stdafx.h + Level3 + true + ProgramDatabase + MultiThreadedDLL + NotSet + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + X64 + + + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + Fast + false + Use + stdafx.h + Level3 + true + MultiThreadedDLL + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + Disabled + WIN32;_DEBUG;_WINDOWS;_WIN32_WINNT=0x501;%(PreprocessorDefinitions) + EnableFastChecks + Use + stdafx.h + Level3 + true + ProgramDatabase + MultiThreadedDebugDLL + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + X64 + + + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + Use + stdafx.h + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + + + Disabled + EnableFastChecks + Disabled + EnableFastChecks + + + + Disabled + EnableFastChecks + Disabled + EnableFastChecks + + + + + Disabled + EnableFastChecks + Disabled + EnableFastChecks + + + Disabled + EnableFastChecks + Disabled + EnableFastChecks + + + Disabled + EnableFastChecks + Disabled + EnableFastChecks + + + Disabled + EnableFastChecks + Disabled + EnableFastChecks + + + Disabled + EnableFastChecks + Disabled + EnableFastChecks + + + + + + + + Disabled + EnableFastChecks + Disabled + EnableFastChecks + + + + + + Disabled + EnableFastChecks + Create + Disabled + EnableFastChecks + Create + Create + Create + + + Disabled + EnableFastChecks + Disabled + EnableFastChecks + + + Disabled + EnableFastChecks + Disabled + EnableFastChecks + + + + Disabled + EnableFastChecks + Disabled + EnableFastChecks + + + + Disabled + EnableFastChecks + Disabled + EnableFastChecks + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SDK/foobar2000/helpers/foobar2000_sdk_helpers.vcxproj.filters b/SDK/foobar2000/helpers/foobar2000_sdk_helpers.vcxproj.filters new file mode 100644 index 0000000..86b4a60 --- /dev/null +++ b/SDK/foobar2000/helpers/foobar2000_sdk_helpers.vcxproj.filters @@ -0,0 +1,233 @@ + + + + + {f9bf58c4-374f-49a5-94db-1f5ae50beca1} + cpp;c;cxx;rc;def;r;odl;idl;hpj;bat + + + {07b1c50a-a3ad-4711-9ae0-d1411b80fd7a} + h;hpp;hxx;hm;inl + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/SDK/foobar2000/helpers/foobar2000_sdk_helpers.vcxproj.user b/SDK/foobar2000/helpers/foobar2000_sdk_helpers.vcxproj.user new file mode 100644 index 0000000..0f14913 --- /dev/null +++ b/SDK/foobar2000/helpers/foobar2000_sdk_helpers.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/SDK/foobar2000/helpers/fullFileBuffer.h b/SDK/foobar2000/helpers/fullFileBuffer.h new file mode 100644 index 0000000..25fd264 --- /dev/null +++ b/SDK/foobar2000/helpers/fullFileBuffer.h @@ -0,0 +1,31 @@ +class fullFileBuffer { +public: + fullFileBuffer() { + //hMutex = CreateMutex(NULL, FALSE, pfc::stringcvt::string_os_from_utf8(pfc::string_formatter() << "{3ABC4D98-2510-431C-A720-26BEB45F0278}-" << (uint32_t) GetCurrentProcessId())); + } + ~fullFileBuffer() { + //CloseHandle(hMutex); + } + file::ptr open(const char * path, abort_callback & abort, file::ptr hint, t_filesize sizeMax = 1024*1024*256) { + //mutexScope scope(hMutex, abort); + + file::ptr f; + if (hint.is_valid()) f = hint; + else filesystem::g_open_read( f, path, abort ); + t_filesize fs = f->get_size(abort); + if (fs < sizeMax) /*rejects size-unknown too*/ { + try { + service_ptr_t r = new service_impl_t(); + r->init( f, abort ); + f = r; + } catch(std::bad_alloc) {} + } + return f; + } + +private: + fullFileBuffer(const fullFileBuffer&); + void operator=(const fullFileBuffer&); + + //HANDLE hMutex; +}; diff --git a/SDK/foobar2000/helpers/helpers.h b/SDK/foobar2000/helpers/helpers.h new file mode 100644 index 0000000..fb8b58f --- /dev/null +++ b/SDK/foobar2000/helpers/helpers.h @@ -0,0 +1,46 @@ +#ifndef _FOOBAR2000_SDK_HELPERS_H_ +#define _FOOBAR2000_SDK_HELPERS_H_ + +#include "input_helpers.h" +#include "create_directory_helper.h" +#include "dialog_resize_helper.h" +#include "dropdown_helper.h" +#include "window_placement_helper.h" +#include "win32_dialog.h" +#include "cuesheet_index_list.h" +#include "cue_creator.h" +#include "cue_parser.h" +#include "text_file_loader.h" +#include "file_list_helper.h" +#include "listview_helper.h" +#include "stream_buffer_helper.h" +#include "file_info_const_impl.h" +#include "dynamic_bitrate_helper.h" +#include "cfg_guidlist.h" +#include "file_move_helper.h" +#include "file_cached.h" +#include "seekabilizer.h" +#include "string_filter.h" +#include "bitreader_helper.h" +#include "mp3_utils.h" +#include "win32_misc.h" +#include "fb2k_threads.h" +#include "COM_utils.h" +#include "metadb_io_hintlist.h" +#include "meta_table_builder.h" +#include "icon_remapping_wildcard.h" +#include "clipboard.h" +#include "IDataObjectUtils.h" +#include "CallForwarder.h" +#include "playlist_position_reference_tracker.h" +#include "ThreadUtils.h" +#include "ProcessUtils.h" +#include "VisUtils.h" +#include "filetimetools.h" +#include "ProfileCache.h" +#include "file_win32_wrapper.h" +#include "fullFileBuffer.h" +#include "CPowerRequest.h" +#include "writer_wav.h" + +#endif //_FOOBAR2000_SDK_HELPERS_H_ diff --git a/SDK/foobar2000/helpers/icon_remapping_wildcard.h b/SDK/foobar2000/helpers/icon_remapping_wildcard.h new file mode 100644 index 0000000..8542da1 --- /dev/null +++ b/SDK/foobar2000/helpers/icon_remapping_wildcard.h @@ -0,0 +1,13 @@ +class icon_remapping_wildcard_impl : public icon_remapping { +public: + icon_remapping_wildcard_impl(const char * p_pattern,const char * p_iconname) : m_pattern(p_pattern), m_iconname(p_iconname) {} + bool query(const char * p_extension,pfc::string_base & p_iconname) { + if (wildcard_helper::test(p_extension,m_pattern,true)) { + p_iconname = m_iconname; return true; + } else { + return false; + } + } +private: + pfc::string8 m_pattern,m_iconname; +}; diff --git a/SDK/foobar2000/helpers/input_helpers.cpp b/SDK/foobar2000/helpers/input_helpers.cpp new file mode 100644 index 0000000..6ccbb81 --- /dev/null +++ b/SDK/foobar2000/helpers/input_helpers.cpp @@ -0,0 +1,599 @@ +#include "stdafx.h" + +static void _input_helper_io_filter_fullbuffer(service_ptr_t & p_file,const char * p_path, t_filesize arg,abort_callback & p_abort) { + if (arg > 0 && !filesystem::g_is_remote_or_unrecognized(p_path)) { + fullFileBuffer a; + p_file = a.open(p_path, p_abort, p_file, arg); + } +} + +static void _input_helper_io_filter_blockbuffer(service_ptr_t & p_file,const char * p_path, t_filesize arg,abort_callback & p_abort) { + if (arg > 0 && !filesystem::g_is_remote_or_unrecognized(p_path)) { + if (p_file.is_empty()) filesystem::g_open_read( p_file, p_path, p_abort ); + if (!p_file->is_in_memory() && !p_file->is_remote() && p_file->can_seek()) { + file_cached::g_create( p_file, p_file, p_abort, (size_t) arg ); + } + } +} + +void input_helper::open(service_ptr_t p_filehint,metadb_handle_ptr p_location,unsigned p_flags,abort_callback & p_abort,bool p_from_redirect,bool p_skip_hints) +{ + open(p_filehint,p_location->get_location(),p_flags,p_abort,p_from_redirect,p_skip_hints); +} + +void input_helper::process_fullbuffer(service_ptr_t & p_file,const char * p_path,abort_callback & p_abort) { + if (m_ioFilter != NULL) m_ioFilter(p_file, p_path, m_ioFilterArg, p_abort); +} + +bool input_helper::need_file_reopen(const char * newPath) const { + return m_input.is_empty() || metadb::path_compare(m_path, newPath) != 0; +} + +bool input_helper::open_path(file::ptr p_filehint,const char * path,abort_callback & p_abort,bool p_from_redirect,bool p_skip_hints) { + p_abort.check(); + + if (!need_file_reopen(path)) return false; + m_input.release(); + + service_ptr_t l_file = p_filehint; + process_fullbuffer(l_file,path,p_abort); + + TRACK_CODE("input_entry::g_open_for_decoding", + input_entry::g_open_for_decoding(m_input,l_file,path,p_abort,p_from_redirect) + ); + + + if (!p_skip_hints) { + try { + static_api_ptr_t()->hint_reader(m_input.get_ptr(),path,p_abort); + } catch(exception_io_data) { + //Don't fail to decode when this barfs, might be barfing when reading info from another subsong than the one we're trying to decode etc. + m_input.release(); + if (l_file.is_valid()) l_file->reopen(p_abort); + TRACK_CODE("input_entry::g_open_for_decoding", + input_entry::g_open_for_decoding(m_input,l_file,path,p_abort,p_from_redirect) + ); + } + } + + m_path = path; + return true; +} + +void input_helper::open_decoding(t_uint32 subsong, t_uint32 flags, abort_callback & p_abort) { + TRACK_CODE("input_decoder::initialize",m_input->initialize(subsong,flags,p_abort)); +} + +void input_helper::open(const playable_location & location, abort_callback & abort, decodeOpen_t const & other) { + open_path(other.m_hint, location.get_path(), abort, other.m_from_redirect, other.m_skip_hints); + + set_logger( other.m_logger ); + + open_decoding(location.get_subsong(), other.m_flags, abort); +} + +void input_helper::open(service_ptr_t p_filehint,const playable_location & p_location,unsigned p_flags,abort_callback & p_abort,bool p_from_redirect,bool p_skip_hints) { + decodeOpen_t o; + o.m_hint = p_filehint; + o.m_flags = p_flags; + o.m_from_redirect = p_from_redirect; + o.m_skip_hints = p_skip_hints; + this->open( p_location, p_abort, o ); +} + + +void input_helper::close() { + m_input.release(); +} + +bool input_helper::is_open() { + return m_input.is_valid(); +} + +void input_helper::set_pause(bool state) { + input_decoder_v3::ptr v3; + if (m_input->service_query_t(v3)) v3->set_pause(state); +} +bool input_helper::flush_on_pause() { + input_decoder_v3::ptr v3; + if (m_input->service_query_t(v3)) return v3->flush_on_pause(); + else return false; +} + + +void input_helper::set_logger(event_logger::ptr ptr) { + input_decoder_v2::ptr v2; + if (m_input->service_query_t(v2)) v2->set_logger(ptr); +} + +bool input_helper::run_raw(audio_chunk & p_chunk, mem_block_container & p_raw, abort_callback & p_abort) { + input_decoder_v2::ptr v2; + if (!m_input->service_query_t(v2)) throw pfc::exception_not_implemented(); + return v2->run_raw(p_chunk, p_raw, p_abort); +} + +bool input_helper::run(audio_chunk & p_chunk,abort_callback & p_abort) { + TRACK_CODE("input_decoder::run",return m_input->run(p_chunk,p_abort)); +} + +void input_helper::seek(double seconds,abort_callback & p_abort) { + TRACK_CODE("input_decoder::seek",m_input->seek(seconds,p_abort)); +} + +bool input_helper::can_seek() { + return m_input->can_seek(); +} + +void input_helper::set_full_buffer(t_filesize val) { + m_ioFilter = _input_helper_io_filter_fullbuffer; + m_ioFilterArg = val; +} + +void input_helper::set_block_buffer(size_t val) { + m_ioFilter = _input_helper_io_filter_blockbuffer; + m_ioFilterArg = val; +} + +void input_helper::on_idle(abort_callback & p_abort) { + if (m_input.is_valid()) { + TRACK_CODE("input_decoder::on_idle",m_input->on_idle(p_abort)); + } +} + +bool input_helper::get_dynamic_info(file_info & p_out,double & p_timestamp_delta) { + TRACK_CODE("input_decoder::get_dynamic_info",return m_input->get_dynamic_info(p_out,p_timestamp_delta)); +} + +bool input_helper::get_dynamic_info_track(file_info & p_out,double & p_timestamp_delta) { + TRACK_CODE("input_decoder::get_dynamic_info_track",return m_input->get_dynamic_info_track(p_out,p_timestamp_delta)); +} + +void input_helper::get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort) { + TRACK_CODE("input_decoder::get_info",m_input->get_info(p_subsong,p_info,p_abort)); +} + +const char * input_helper::get_path() const { + return m_path; +} + + +input_helper::input_helper() : m_ioFilter(), m_ioFilterArg() +{ +} + + +void input_helper::g_get_info(const playable_location & p_location,file_info & p_info,abort_callback & p_abort,bool p_from_redirect) { + service_ptr_t instance; + input_entry::g_open_for_info_read(instance,0,p_location.get_path(),p_abort,p_from_redirect); + instance->get_info(p_location.get_subsong_index(),p_info,p_abort); +} + +void input_helper::g_set_info(const playable_location & p_location,file_info & p_info,abort_callback & p_abort,bool p_from_redirect) { + service_ptr_t instance; + input_entry::g_open_for_info_write(instance,0,p_location.get_path(),p_abort,p_from_redirect); + instance->set_info(p_location.get_subsong_index(),p_info,p_abort); + instance->commit(p_abort); +} + + +bool dead_item_filter::run(const pfc::list_base_const_t & p_list,bit_array_var & p_mask) { + file_list_helper::file_list_from_metadb_handle_list path_list; + path_list.init_from_list(p_list); + metadb_handle_list valid_handles; + static_api_ptr_t l_metadb; + for(t_size pathidx=0;pathidxhandle_create(temp,make_playable_location(path,0)); + valid_handles.add_item(temp); + } else { + try { + service_ptr_t reader; + + input_entry::g_open_for_info_read(reader,0,path,*this); + t_uint32 count = reader->get_subsong_count(); + for(t_uint32 n=0;nget_subsong(n); + l_metadb->handle_create(ptr,make_playable_location(path,index)); + valid_handles.add_item(ptr); + } + } catch(...) {} + } + } + + if (is_aborting()) return false; + + valid_handles.sort_by_pointer(); + for(t_size listidx=0;listidx & p_list,bit_array_var & p_mask,abort_callback & p_abort) +{ + dead_item_filter_impl_simple filter(p_abort); + return filter.run(p_list,p_mask); +} + +void input_info_read_helper::open(const char * p_path,abort_callback & p_abort) { + if (m_input.is_empty() || metadb::path_compare(m_path,p_path) != 0) + { + TRACK_CODE("input_entry::g_open_for_info_read",input_entry::g_open_for_info_read(m_input,0,p_path,p_abort)); + + m_path = p_path; + } +} + +void input_info_read_helper::get_info(const playable_location & p_location,file_info & p_info,t_filestats & p_stats,abort_callback & p_abort) { + open(p_location.get_path(),p_abort); + + TRACK_CODE("input_info_reader::get_file_stats",p_stats = m_input->get_file_stats(p_abort)); + + TRACK_CODE("input_info_reader::get_info",m_input->get_info(p_location.get_subsong_index(),p_info,p_abort)); +} + +void input_info_read_helper::get_info_check(const playable_location & p_location,file_info & p_info,t_filestats & p_stats,bool & p_reloaded,abort_callback & p_abort) { + open(p_location.get_path(),p_abort); + t_filestats newstats; + TRACK_CODE("input_info_reader::get_file_stats",newstats = m_input->get_file_stats(p_abort)); + if (metadb_handle::g_should_reload(p_stats,newstats,true)) { + p_stats = newstats; + TRACK_CODE("input_info_reader::get_info",m_input->get_info(p_location.get_subsong_index(),p_info,p_abort)); + p_reloaded = true; + } else { + p_reloaded = false; + } +} + + + + + + +void input_helper_cue::open(service_ptr_t p_filehint,const playable_location & p_location,unsigned p_flags,abort_callback & p_abort,double p_start,double p_length) { + p_abort.check(); + + m_start = p_start; + m_position = 0; + m_dynamic_info_trigger = false; + m_dynamic_info_track_trigger = false; + + m_input.open(p_filehint,p_location,p_flags,p_abort,true,true); + + if (!m_input.can_seek()) throw exception_io_object_not_seekable(); + + if (m_start > 0) { + m_input.seek(m_start,p_abort); + } + + if (p_length > 0) { + m_length = p_length; + } else { + file_info_impl temp; + m_input.get_info(0,temp,p_abort); + double ref_length = temp.get_length(); + if (ref_length <= 0) throw exception_io_data(); + m_length = ref_length - m_start + p_length /* negative or zero */; + if (m_length <= 0) throw exception_io_data(); + } +} + +void input_helper_cue::close() {m_input.close();} +bool input_helper_cue::is_open() {return m_input.is_open();} + +bool input_helper_cue::_m_input_run(audio_chunk & p_chunk, mem_block_container * p_raw, abort_callback & p_abort) { + if (p_raw == NULL) { + return m_input.run(p_chunk, p_abort); + } else { + return m_input.run_raw(p_chunk, *p_raw, p_abort); + } +} +bool input_helper_cue::_run(audio_chunk & p_chunk, mem_block_container * p_raw, abort_callback & p_abort) { + p_abort.check(); + + if (m_length > 0) { + if (m_position >= m_length) return false; + + if (!_m_input_run(p_chunk, p_raw, p_abort)) return false; + + m_dynamic_info_trigger = true; + m_dynamic_info_track_trigger = true; + + t_uint64 max = (t_uint64) audio_math::time_to_samples(m_length - m_position, p_chunk.get_sample_rate()); + if (max == 0) + {//handle rounding accidents, this normally shouldn't trigger + m_position = m_length; + return false; + } + + t_size samples = p_chunk.get_sample_count(); + if ((t_uint64)samples > max) + { + p_chunk.set_sample_count((unsigned)max); + if (p_raw != NULL) { + const t_size rawSize = p_raw->get_size(); + PFC_ASSERT( rawSize % samples == 0 ); + p_raw->set_size( (t_size) ( (t_uint64) rawSize * max / samples ) ); + } + m_position = m_length; + } + else + { + m_position += p_chunk.get_duration(); + } + return true; + } + else + { + if (!_m_input_run(p_chunk, p_raw, p_abort)) return false; + m_position += p_chunk.get_duration(); + return true; + } +} +bool input_helper_cue::run_raw(audio_chunk & p_chunk, mem_block_container & p_raw, abort_callback & p_abort) { + return _run(p_chunk, &p_raw, p_abort); +} + +bool input_helper_cue::run(audio_chunk & p_chunk,abort_callback & p_abort) { + return _run(p_chunk, NULL, p_abort); +} + +void input_helper_cue::seek(double p_seconds,abort_callback & p_abort) +{ + m_dynamic_info_trigger = false; + m_dynamic_info_track_trigger = false; + if (m_length <= 0 || p_seconds < m_length) { + m_input.seek(p_seconds + m_start,p_abort); + m_position = p_seconds; + } else { + m_position = m_length; + } +} + +bool input_helper_cue::can_seek() {return true;} + +void input_helper_cue::set_full_buffer(t_filesize val) {m_input.set_full_buffer(val);} + +void input_helper_cue::on_idle(abort_callback & p_abort) {m_input.on_idle(p_abort);} + +bool input_helper_cue::get_dynamic_info(file_info & p_out,double & p_timestamp_delta) { + if (m_dynamic_info_trigger) { + m_dynamic_info_trigger = false; + return m_input.get_dynamic_info(p_out,p_timestamp_delta); + } else { + return false; + } +} + +bool input_helper_cue::get_dynamic_info_track(file_info & p_out,double & p_timestamp_delta) { + if (m_dynamic_info_track_trigger) { + m_dynamic_info_track_trigger = false; + return m_input.get_dynamic_info_track(p_out,p_timestamp_delta); + } else { + return false; + } +} + +const char * input_helper_cue::get_path() const {return m_input.get_path();} + +void input_helper_cue::get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort) {m_input.get_info(p_subsong,p_info,p_abort);} + + + + + + +// openAudioData code + +namespace { + + class file_decodedaudio : public file_readonly { + public: + void init(const playable_location & loc, bool bSeekable, file::ptr fileHint, abort_callback & aborter) { + m_length = -1; m_lengthKnown = false; + m_subsong = loc.get_subsong(); + input_entry::g_open_for_decoding(m_decoder, fileHint, loc.get_path(), aborter); + m_seekable = bSeekable && m_decoder->can_seek(); + reopenDecoder(aborter); + readChunk(aborter, true); + } + + void reopen(abort_callback & aborter) { + + // Have valid chunk and it is the first chunk in the stream? Reset read pointers and bail, no need to reopen + if (m_chunk.get_sample_count() > 0 && m_chunkBytesPtr == m_currentPosition) { + m_currentPosition = 0; + m_chunkBytesPtr = 0; + m_eof = false; + return; + } + + reopenDecoder(aborter); + readChunk(aborter); + } + + bool is_remote() { + return false; + } +#if FOOBAR2000_TARGET_VERSION >= 2000 + t_filestats get_stats(abort_callback & aborter) { + t_filestats fs = m_decoder->get_file_stats(aborter); + fs.m_size = get_size(aborter); + return fs; + } +#else + t_filetimestamp get_timestamp(abort_callback & p_abort) { + return m_decoder->get_file_stats(p_abort).m_timestamp; + } +#endif + void on_idle(abort_callback & p_abort) { + m_decoder->on_idle(p_abort); + } + bool get_content_type(pfc::string_base & p_out) { + return false; + } + bool can_seek() { + return m_seekable; + } + void seek(t_filesize p_position, abort_callback & p_abort) { + if (!m_seekable) throw exception_io_object_not_seekable(); + + + { + t_filesize chunkBegin = m_currentPosition - m_chunkBytesPtr; + t_filesize chunkEnd = chunkBegin + curChunkBytes(); + if (p_position >= chunkBegin && p_position < chunkEnd) { + m_chunkBytesPtr = (size_t)(p_position - chunkBegin); + m_currentPosition = p_position; + m_eof = false; + return; + } + } + + { + t_filesize s = get_size(p_abort); + if (s != filesize_invalid) { + if (p_position > s) throw exception_io_seek_out_of_range(); + if (p_position == s) { + m_chunk.reset(); + m_chunkBytesPtr = 0; + m_currentPosition = p_position; + m_eof = true; + return; + } + } + } + + + + const size_t row = m_spec.chanCount * sizeof(audio_sample); + t_filesize samples = p_position / row; + const double seekTime = audio_math::samples_to_time(samples, m_spec.sampleRate); + m_decoder->seek(seekTime, p_abort); + m_eof = false; // do this before readChunk + if (!this->readChunk(p_abort)) { + throw std::runtime_error(PFC_string_formatter() << "Premature EOF in referenced audio file at " << pfc::format_time_ex(seekTime, 6) << " out of " << pfc::format_time_ex(length(p_abort), 6)); + } + m_chunkBytesPtr = p_position % row; + if (m_chunkBytesPtr > curChunkBytes()) { + // Should not ever happen + m_chunkBytesPtr = 0; + throw std::runtime_error("Decoder returned invalid data"); + } + + m_currentPosition = p_position; + m_eof = false; + } + + t_filesize get_size(abort_callback & aborter) { + const double l = length(aborter); + if (l <= 0) return filesize_invalid; + return audio_math::time_to_samples(l, m_spec.sampleRate) * m_spec.chanCount * sizeof(audio_sample); + } + t_filesize get_position(abort_callback & p_abort) { + return m_currentPosition; + } + t_size read(void * p_buffer, t_size p_bytes, abort_callback & p_abort) { + size_t done = 0; + for (;;) { + p_abort.check(); + { + const size_t inChunk = curChunkBytes(); + const size_t inChunkRemaining = inChunk - m_chunkBytesPtr; + const size_t delta = pfc::min_t(inChunkRemaining, (p_bytes - done)); + memcpy((uint8_t*)p_buffer + done, (const uint8_t*)m_chunk.get_data() + m_chunkBytesPtr, delta); + m_chunkBytesPtr += delta; + done += delta; + m_currentPosition += delta; + + if (done == p_bytes) break; + } + if (!readChunk(p_abort)) break; + } + return done; + } + audio_chunk::spec_t const & get_spec() const { return m_spec; } + private: + void reopenDecoder(abort_callback & aborter) { + uint32_t flags = input_flag_no_looping; + if (!m_seekable) flags |= input_flag_no_seeking; + m_decoder->initialize(m_subsong, flags, aborter); + m_eof = false; + m_currentPosition = 0; + } + size_t curChunkBytes() const { + return m_chunk.get_used_size() * sizeof(audio_sample); + } + bool readChunk(abort_callback & aborter, bool initial = false) { + m_chunkBytesPtr = 0; + for (;;) { + if (m_eof || !m_decoder->run(m_chunk, aborter)) { + if (initial) throw std::runtime_error("Decoder produced no data"); + m_eof = true; + m_chunk.reset(); + return false; + } + if (m_chunk.is_valid()) break; + } + audio_chunk::spec_t spec = m_chunk.get_spec(); + if (initial) m_spec = spec; + else if (m_spec != spec) throw std::runtime_error("Sample format change in mid stream"); + return true; + } + double length(abort_callback & aborter) { + if (!m_lengthKnown) { + file_info_impl temp; + m_decoder->get_info(m_subsong, temp, aborter); + m_length = temp.get_length(); + m_lengthKnown = true; + } + return m_length; + } + audio_chunk_fast_impl m_chunk; + size_t m_chunkBytesPtr; + audio_chunk::spec_t m_spec; + double m_length; + bool m_lengthKnown; + bool m_seekable; + uint32_t m_subsong; + input_decoder::ptr m_decoder; + bool m_eof; + t_filesize m_currentPosition; + }; + +} + +openAudioData_t openAudioData(playable_location const & loc, bool bSeekable, file::ptr fileHint, abort_callback & aborter) { + service_ptr_t f; f = new service_impl_t < file_decodedaudio > ; + f->init(loc, bSeekable, fileHint, aborter); + + openAudioData_t oad = {}; + oad.audioData = f; + oad.audioSpec = f->get_spec(); + return oad; +} \ No newline at end of file diff --git a/SDK/foobar2000/helpers/input_helpers.h b/SDK/foobar2000/helpers/input_helpers.h new file mode 100644 index 0000000..3104bb0 --- /dev/null +++ b/SDK/foobar2000/helpers/input_helpers.h @@ -0,0 +1,133 @@ +#ifndef _INPUT_HELPERS_H_ +#define _INPUT_HELPERS_H_ + +typedef void (* _input_helper_io_filter)(service_ptr_t & p_file,const char * p_path, t_filesize arg,abort_callback & p_abort); + +class input_helper { +public: + input_helper(); + + struct decodeOpen_t { + decodeOpen_t() : m_from_redirect(), m_skip_hints(), m_flags() {} + event_logger::ptr m_logger; + bool m_from_redirect; + bool m_skip_hints; + unsigned m_flags; + file::ptr m_hint; + }; + + void open(service_ptr_t p_filehint,metadb_handle_ptr p_location,unsigned p_flags,abort_callback & p_abort,bool p_from_redirect = false,bool p_skip_hints = false); + void open(service_ptr_t p_filehint,const playable_location & p_location,unsigned p_flags,abort_callback & p_abort,bool p_from_redirect = false,bool p_skip_hints = false); + + void open(const playable_location & location, abort_callback & abort, decodeOpen_t const & other); + void open(metadb_handle_ptr location, abort_callback & abort, decodeOpen_t const & other) {this->open(location->get_location(), abort, other);} + + + //! Multilevel open helpers. + //! @returns Diagnostic/helper value: true if the decoder had to be re-opened entirely, false if the instance was reused. + bool open_path(file::ptr p_filehint,const char * path,abort_callback & p_abort,bool p_from_redirect,bool p_skip_hints); + //! Multilevel open helpers. + void open_decoding(t_uint32 subsong, t_uint32 flags, abort_callback & p_abort); + + bool need_file_reopen(const char * newPath) const; + + void close(); + bool is_open(); + bool run(audio_chunk & p_chunk,abort_callback & p_abort); + bool run_raw(audio_chunk & p_chunk, mem_block_container & p_raw, abort_callback & p_abort); + void seek(double seconds,abort_callback & p_abort); + bool can_seek(); + void set_full_buffer(t_filesize val); + void set_block_buffer(size_t val); + void on_idle(abort_callback & p_abort); + bool get_dynamic_info(file_info & p_out,double & p_timestamp_delta); + bool get_dynamic_info_track(file_info & p_out,double & p_timestamp_delta); + void set_logger(event_logger::ptr ptr); + void set_pause(bool state); + bool flush_on_pause(); + + //! Retrieves path of currently open file. + const char * get_path() const; + + //! Retrieves info about specific subsong of currently open file. + void get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort); + + static void g_get_info(const playable_location & p_location,file_info & p_info,abort_callback & p_abort,bool p_from_redirect = false); + static void g_set_info(const playable_location & p_location,file_info & p_info,abort_callback & p_abort,bool p_from_redirect = false); + + + static bool g_mark_dead(const pfc::list_base_const_t & p_list,bit_array_var & p_mask,abort_callback & p_abort); + +private: + void process_fullbuffer(service_ptr_t & p_file,const char * p_path,abort_callback & p_abort); + service_ptr_t m_input; + pfc::string8 m_path; + _input_helper_io_filter m_ioFilter; + t_filesize m_ioFilterArg; +}; + +class NOVTABLE dead_item_filter : public abort_callback { +public: + virtual void on_progress(t_size p_position,t_size p_total) = 0; + + bool run(const pfc::list_base_const_t & p_list,bit_array_var & p_mask); +}; + +class input_info_read_helper { +public: + input_info_read_helper() {} + void get_info(const playable_location & p_location,file_info & p_info,t_filestats & p_stats,abort_callback & p_abort); + void get_info_check(const playable_location & p_location,file_info & p_info,t_filestats & p_stats,bool & p_reloaded,abort_callback & p_abort); +private: + void open(const char * p_path,abort_callback & p_abort); + + pfc::string8 m_path; + service_ptr_t m_input; +}; + + + +class input_helper_cue { +public: + void open(service_ptr_t p_filehint,const playable_location & p_location,unsigned p_flags,abort_callback & p_abort,double p_start,double p_length); + + void close(); + bool is_open(); + bool run(audio_chunk & p_chunk,abort_callback & p_abort); + bool run_raw(audio_chunk & p_chunk, mem_block_container & p_raw, abort_callback & p_abort); + void seek(double seconds,abort_callback & p_abort); + bool can_seek(); + void set_full_buffer(t_filesize val); + void on_idle(abort_callback & p_abort); + bool get_dynamic_info(file_info & p_out,double & p_timestamp_delta); + bool get_dynamic_info_track(file_info & p_out,double & p_timestamp_delta); + void set_logger(event_logger::ptr ptr) {m_input.set_logger(ptr);} + + const char * get_path() const; + + void get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort); + +private: + bool _run(audio_chunk & p_chunk, mem_block_container * p_raw, abort_callback & p_abort); + bool _m_input_run(audio_chunk & p_chunk, mem_block_container * p_raw, abort_callback & p_abort); + input_helper m_input; + double m_start,m_length,m_position; + bool m_dynamic_info_trigger,m_dynamic_info_track_trigger; +}; + +//! openAudioData return value, see openAudioData() +struct openAudioData_t { + file::ptr audioData; // audio data stream + audio_chunk::spec_t audioSpec; // format description (sample rate, channel layout). +}; + +//! Opens the specified location as a stream of audio_samples. \n +//! Returns a file object that allows you to read the audio data stream as if it was a physical file, together with audio stream format description (sample rate, channel layout). \n +//! Please keep in mind that certain features of the returned file object are only as reliable as the underlying file format or decoder implementation allows them to be. \n +//! Reported exact file size may be either unavailable or unreliable if the file format does not let us known the exact value without decoding the whole file. \n +//! Seeking may be inaccurate with certain file formats. \n +//! In general, all file object methods will work as intended on core-supported file formats such as FLAC or WavPack. \n +//! However, if you want 100% functionality regardless of file format being worked with, mirror the content to a temp file and let go of the file object returned by openAudioData(). +openAudioData_t openAudioData(playable_location const & loc, bool bSeekable, file::ptr fileHint, abort_callback & aborter); + +#endif diff --git a/SDK/foobar2000/helpers/listview_helper.cpp b/SDK/foobar2000/helpers/listview_helper.cpp new file mode 100644 index 0000000..0ea4186 --- /dev/null +++ b/SDK/foobar2000/helpers/listview_helper.cpp @@ -0,0 +1,191 @@ +#include "stdafx.h" + +#ifdef _WIN32 + + +namespace listview_helper { + + unsigned insert_item(HWND p_listview,unsigned p_index,const char * p_name,LPARAM p_param) + { + if (p_index == ~0) p_index = ListView_GetItemCount(p_listview); + LVITEM item = {}; + + pfc::stringcvt::string_os_from_utf8 os_string_temp(p_name); + + item.mask = LVIF_TEXT | LVIF_PARAM; + item.iItem = p_index; + item.lParam = p_param; + item.pszText = const_cast(os_string_temp.get_ptr()); + + LRESULT ret = uSendMessage(p_listview,LVM_INSERTITEM,0,(LPARAM)&item); + if (ret < 0) return ~0; + else return (unsigned) ret; + } + + unsigned insert_item2(HWND p_listview, unsigned p_index, const char * col0, const char * col1, LPARAM p_param) { + unsigned i = insert_item( p_listview, p_index, col0, p_param ); + if (i != ~0) { + set_item_text( p_listview, i, 1, col1 ); + } + return i; + } + + unsigned insert_item3(HWND p_listview, unsigned p_index, const char * col0, const char * col1, const char * col2, LPARAM p_param) { + unsigned i = insert_item( p_listview, p_index, col0, p_param ); + if (i != ~0) { + set_item_text( p_listview, i, 1, col1 ); + set_item_text( p_listview, i, 2, col2 ); + } + return i; + } + + unsigned insert_column(HWND p_listview,unsigned p_index,const char * p_name,unsigned p_width_dlu) + { + pfc::stringcvt::string_os_from_utf8 os_string_temp(p_name); + + RECT rect = {0,0,p_width_dlu,0}; + MapDialogRect(GetParent(p_listview),&rect); + + LVCOLUMN data = {}; + data.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_FMT; + data.fmt = LVCFMT_LEFT; + data.cx = rect.right; + data.pszText = const_cast(os_string_temp.get_ptr()); + + LRESULT ret = uSendMessage(p_listview,LVM_INSERTCOLUMN,p_index,(LPARAM)&data); + if (ret < 0) return ~0; + else return (unsigned) ret; + } + + void get_item_text(HWND p_listview,unsigned p_index,unsigned p_column,pfc::string_base & p_out) { + enum {buffer_length = 1024*64}; + pfc::array_t buffer; buffer.set_size(buffer_length); + ListView_GetItemText(p_listview,p_index,p_column,buffer.get_ptr(),buffer_length); + p_out = pfc::stringcvt::string_utf8_from_os(buffer.get_ptr(),buffer_length); + } + + bool set_item_text(HWND p_listview,unsigned p_index,unsigned p_column,const char * p_name) + { + LVITEM item = {}; + + pfc::stringcvt::string_os_from_utf8 os_string_temp(p_name); + + item.mask = LVIF_TEXT; + item.iItem = p_index; + item.iSubItem = p_column; + item.pszText = const_cast(os_string_temp.get_ptr()); + return uSendMessage(p_listview,LVM_SETITEM,0,(LPARAM)&item) ? true : false; + } + + bool is_item_selected(HWND p_listview,unsigned p_index) + { + LVITEM item = {}; + item.mask = LVIF_STATE; + item.iItem = p_index; + item.stateMask = LVIS_SELECTED; + if (!uSendMessage(p_listview,LVM_GETITEM,0,(LPARAM)&item)) return false; + return (item.state & LVIS_SELECTED) ? true : false; + } + + void set_item_selection(HWND p_listview,unsigned p_index,bool p_state) + { + PFC_ASSERT( ::IsWindow(p_listview) ); + LVITEM item = {}; + item.stateMask = LVIS_SELECTED; + item.state = p_state ? LVIS_SELECTED : 0; + WIN32_OP_D( SendMessage(p_listview,LVM_SETITEMSTATE,(WPARAM)p_index,(LPARAM)&item) ); + } + + bool select_single_item(HWND p_listview,unsigned p_index) + { + LRESULT temp = SendMessage(p_listview,LVM_GETITEMCOUNT,0,0); + if (temp < 0) return false; + ListView_SetSelectionMark(p_listview,p_index); + unsigned n; const unsigned m = pfc::downcast_guarded(temp); + for(n=0;n= 0) { + ListView_EnsureVisible(p_list, firstsel, FALSE); + RECT rect; + WIN32_OP_D( ListView_GetItemRect(p_list,firstsel,&rect,LVIR_BOUNDS) ); + p_point.x = (rect.left + rect.right) / 2; + p_point.y = (rect.top + rect.bottom) / 2; + WIN32_OP_D( ClientToScreen(p_list,&p_point) ); + } else { + RECT rect; + WIN32_OP_D(GetClientRect(p_list,&rect)); + p_point.x = (rect.left + rect.right) / 2; + p_point.y = (rect.top + rect.bottom) / 2; + WIN32_OP_D(ClientToScreen(p_list,&p_point)); + } + p_selection = firstsel; + } else { + POINT pt = p_coords; // {(short)LOWORD(p_coords),(short)HIWORD(p_coords)}; + p_point = pt; + POINT client = pt; + WIN32_OP_D( ScreenToClient(p_list,&client) ); + LVHITTESTINFO info = {}; + info.pt = client; + p_selection = ListView_HitTest(p_list,&info); + } +} + +#if 0 +static bool ProbeColumn(HWND view, int index) { + LVCOLUMN col = {LVCF_ORDER}; + return !! ListView_GetColumn(view, index, &col); +} +int ListView_GetColumnCount(HWND listView) { + if (!ProbeColumn(listView, 0)) return 0; + int hi = 1; + for(;;) { + if (!ProbeColumn(listView, hi)) break; + hi <<= 1; + if (hi <= 0) { + PFC_ASSERT(!"Shouldn't get here!"); + return -1; + } + } + int lo = hi >> 1; + //lo is the highest known valid column, hi is the lowest known invalid, let's bsearch thru + while(lo + 1 < hi) { + PFC_ASSERT( lo < hi ); + const int mid = lo + (hi - lo) / 2; + PFC_ASSERT( lo < mid && mid < hi ); + if (ProbeColumn(listView, mid)) { + lo = mid; + } else { + hi = mid; + } + } + return hi; +} +#else +int ListView_GetColumnCount(HWND listView) { + HWND header = ListView_GetHeader(listView); + PFC_ASSERT(header != NULL); + return Header_GetItemCount(header); +} +#endif + +#endif // _WIN32 diff --git a/SDK/foobar2000/helpers/listview_helper.h b/SDK/foobar2000/helpers/listview_helper.h new file mode 100644 index 0000000..ffb68ac --- /dev/null +++ b/SDK/foobar2000/helpers/listview_helper.h @@ -0,0 +1,49 @@ +#ifdef _WIN32 + +namespace listview_helper +{ + unsigned insert_item(HWND p_listview,unsigned p_index,const char * p_name,LPARAM p_param);//returns index of new item on success, infinite on failure + + unsigned insert_column(HWND p_listview,unsigned p_index,const char * p_name,unsigned p_width_dlu);//returns index of new item on success, infinite on failure + + bool set_item_text(HWND p_listview,unsigned p_index,unsigned p_column,const char * p_name); + + bool is_item_selected(HWND p_listview,unsigned p_index); + + void set_item_selection(HWND p_listview,unsigned p_index,bool p_state); + + bool select_single_item(HWND p_listview,unsigned p_index); + + bool ensure_visible(HWND p_listview,unsigned p_index); + + void get_item_text(HWND p_listview,unsigned p_index,unsigned p_column,pfc::string_base & p_out); + + unsigned insert_item2(HWND p_listview, unsigned p_index, const char * col0, const char * col1, LPARAM p_param = 0); + unsigned insert_item3(HWND p_listview, unsigned p_index, const char * col0, const char * col1, const char * col2, LPARAM p_param = 0); + + +}; + +static int ListView_GetFirstSelection(HWND p_listview) { + return ListView_GetNextItem(p_listview,-1,LVNI_SELECTED); +} + +static int ListView_GetSingleSelection(HWND p_listview) { + if (ListView_GetSelectedCount(p_listview) != 1) return -1; + return ListView_GetFirstSelection(p_listview); +} + +static int ListView_GetFocusItem(HWND p_listview) { + return ListView_GetNextItem(p_listview,-1,LVNI_FOCUSED); +} + +static bool ListView_IsItemSelected(HWND p_listview,int p_index) { + return ListView_GetItemState(p_listview,p_index,LVIS_SELECTED) != 0; +} + +void ListView_GetContextMenuPoint(HWND p_list,LPARAM p_coords,POINT & p_point,int & p_selection); +void ListView_GetContextMenuPoint(HWND p_list,POINT p_coords,POINT & p_point,int & p_selection); + +int ListView_GetColumnCount(HWND listView); + +#endif \ No newline at end of file diff --git a/SDK/foobar2000/helpers/meta_table_builder.h b/SDK/foobar2000/helpers/meta_table_builder.h new file mode 100644 index 0000000..c3614f2 --- /dev/null +++ b/SDK/foobar2000/helpers/meta_table_builder.h @@ -0,0 +1,141 @@ +class _meta_table_enum_wrapper { +public: + _meta_table_enum_wrapper(file_info & p_info) : m_info(p_info) {} + template + void operator() (const char * p_name,const t_values & p_values) { + t_size index = ~0; + for(typename t_values::const_iterator iter = p_values.first(); iter.is_valid(); ++iter) { + if (index == ~0) index = m_info.__meta_add_unsafe(p_name,*iter); + else m_info.meta_add_value(index,*iter); + } + } +private: + file_info & m_info; +}; + +class _meta_table_enum_wrapper_RG { +public: + _meta_table_enum_wrapper_RG(file_info & p_info) : m_info(p_info) {} + template + void operator() (const char * p_name,const t_values & p_values) { + if (p_values.get_count() > 0) { + if (!m_info.info_set_replaygain(p_name, *p_values.first())) { + t_size index = ~0; + for(typename t_values::const_iterator iter = p_values.first(); iter.is_valid(); ++iter) { + if (index == ~0) index = m_info.__meta_add_unsafe(p_name,*iter); + else m_info.meta_add_value(index,*iter); + } + } + } + } +private: + file_info & m_info; +}; + +//! Purpose: building a file_info metadata table from loose input without search-for-existing-entry bottleneck +class meta_table_builder { +public: + typedef pfc::chain_list_v2_t t_entry; + typedef pfc::map_t t_content; + + t_content & content() {return m_data;} + t_content const & content() const {return m_data;} + + void add(const char * p_name,const char * p_value,t_size p_value_len = ~0) { + if (file_info::g_is_valid_field_name(p_name)) { + _add(p_name).insert_last()->set_string(p_value,p_value_len); + } + } + + void remove(const char * p_name) { + m_data.remove(p_name); + } + void set(const char * p_name,const char * p_value,t_size p_value_len = ~0) { + if (file_info::g_is_valid_field_name(p_name)) { + t_entry & entry = _add(p_name); + entry.remove_all(); + entry.insert_last()->set_string(p_value,p_value_len); + } + } + t_entry & add(const char * p_name) { + if (!file_info::g_is_valid_field_name(p_name)) uBugCheck();//we return a reference, nothing smarter to do + return _add(p_name); + } + void deduplicate(const char * name) { + t_entry * e; + if (!m_data.query_ptr(name, e)) return; + pfc::avltree_t found; + for(t_entry::iterator iter = e->first(); iter.is_valid(); ) { + t_entry::iterator next = iter; ++next; + const char * v = *iter; + if (!found.add_item_check(v)) e->remove(iter); + iter = next; + } + } + void keep_one(const char * name) { + t_entry * e; + if (!m_data.query_ptr(name, e)) return; + while(e->get_count() > 1) e->remove(e->last()); + } + void tidy_VorbisComment() { + deduplicate("album artist"); + deduplicate("publisher"); + keep_one("totaltracks"); + keep_one("totaldiscs"); + } + void finalize(file_info & p_info) const { + p_info.meta_remove_all(); + _meta_table_enum_wrapper e(p_info); + m_data.enumerate(e); + } + void finalize_withRG(file_info & p_info) const { + p_info.meta_remove_all(); p_info.set_replaygain(replaygain_info_invalid); + _meta_table_enum_wrapper_RG e(p_info); + m_data.enumerate(e); + } + + void from_info(const file_info & p_info) { + m_data.remove_all(); + from_info_overwrite(p_info); + } + void from_info_withRG(const file_info & p_info) { + m_data.remove_all(); + from_info_overwrite(p_info); + from_RG_overwrite(p_info.get_replaygain()); + } + void from_RG_overwrite(replaygain_info info) { + replaygain_info::t_text_buffer buffer; + if (info.format_album_gain(buffer)) set("replaygain_album_gain", buffer); + if (info.format_track_gain(buffer)) set("replaygain_track_gain", buffer); + if (info.format_album_peak(buffer)) set("replaygain_album_peak", buffer); + if (info.format_track_peak(buffer)) set("replaygain_track_peak", buffer); + } + void from_info_overwrite(const file_info & p_info) { + for(t_size metawalk = 0, metacount = p_info.meta_get_count(); metawalk < metacount; ++metawalk ) { + const t_size valuecount = p_info.meta_enum_value_count(metawalk); + if (valuecount > 0) { + t_entry & entry = add(p_info.meta_enum_name(metawalk)); + entry.remove_all(); + for(t_size valuewalk = 0; valuewalk < valuecount; ++valuewalk) { + entry.insert_last(p_info.meta_enum_value(metawalk,valuewalk)); + } + } + } + } + void reset() {m_data.remove_all();} + + void fix_itunes_compilation() { + static const char cmp[] = "itunescompilation"; + if (m_data.have_item(cmp)) { + // m_data.remove(cmp); + if (!m_data.have_item("album artist")) add("album artist", "Various Artists"); + } + } +private: + + t_entry & _add(const char * p_name) { + return m_data.find_or_add(p_name); + } + + t_content m_data; +}; diff --git a/SDK/foobar2000/helpers/metadb_io_hintlist.cpp b/SDK/foobar2000/helpers/metadb_io_hintlist.cpp new file mode 100644 index 0000000..60d1e83 --- /dev/null +++ b/SDK/foobar2000/helpers/metadb_io_hintlist.cpp @@ -0,0 +1,39 @@ +#include "stdafx.h" + +void metadb_io_hintlist::run() { + if (m_entries.get_count() > 0) { + static_api_ptr_t()->hint_multi_async( + metadb_io_hintlist_wrapper_part1(m_entries), + metadb_io_hintlist_wrapper_part2(m_entries), + metadb_io_hintlist_wrapper_part3(m_entries), + metadb_io_hintlist_wrapper_part4(m_entries) + ); + } + m_entries.remove_all(); +} + +void metadb_io_hintlist::add(metadb_handle_ptr const & p_handle,const file_info & p_info,t_filestats const & p_stats,bool p_fresh) { + t_entry entry; + entry.m_handle = p_handle; + entry.m_info.new_t(p_info); + entry.m_stats = p_stats; + entry.m_fresh = p_fresh; + m_entries.add_item(entry); +} + +void metadb_io_hintlist::hint_reader(service_ptr_t p_reader, const char * p_path,abort_callback & p_abort) { + static_api_ptr_t api; + const t_uint32 subsongcount = p_reader->get_subsong_count(); + t_filestats stats = p_reader->get_file_stats(p_abort); + for(t_uint32 subsong = 0; subsong < subsongcount; subsong++) { + t_uint32 subsong_id = p_reader->get_subsong(subsong); + metadb_handle_ptr handle; + api->handle_create(handle,make_playable_location(p_path,subsong_id)); + if (handle->should_reload(stats,true)) { + file_info_impl temp; + p_reader->get_info(subsong_id,temp,p_abort); + + add(handle,temp,stats,true); + } + } +} diff --git a/SDK/foobar2000/helpers/metadb_io_hintlist.h b/SDK/foobar2000/helpers/metadb_io_hintlist.h new file mode 100644 index 0000000..8d9c66b --- /dev/null +++ b/SDK/foobar2000/helpers/metadb_io_hintlist.h @@ -0,0 +1,50 @@ + +class metadb_io_hintlist { +public: + void hint_reader(service_ptr_t p_reader, const char * p_path,abort_callback & p_abort); + void add(metadb_handle_ptr const & p_handle,const file_info & p_info,t_filestats const & p_stats,bool p_fresh); + void run(); + t_size get_pending_count() const {return m_entries.get_count();} +private: + struct t_entry { + metadb_handle_ptr m_handle; + pfc::rcptr_t m_info; + t_filestats m_stats; + bool m_fresh; + }; + class metadb_io_hintlist_wrapper_part1 : public pfc::list_base_const_t { + public: + metadb_io_hintlist_wrapper_part1(const pfc::list_base_const_t & p_list) : m_list(p_list) {} + t_size get_count() const {return m_list.get_count();} + void get_item_ex(metadb_handle_ptr & p_out, t_size n) const {p_out = m_list[n].m_handle;} + + private: + const pfc::list_base_const_t & m_list; + }; + class metadb_io_hintlist_wrapper_part2 : public pfc::list_base_const_t { + public: + metadb_io_hintlist_wrapper_part2(const pfc::list_base_const_t & p_list) : m_list(p_list) {} + t_size get_count() const {return m_list.get_count();} + void get_item_ex(const file_info* & p_out, t_size n) const {p_out = &*m_list[n].m_info;} + private: + const pfc::list_base_const_t & m_list; + }; + class metadb_io_hintlist_wrapper_part3 : public pfc::list_base_const_t { + public: + metadb_io_hintlist_wrapper_part3(const pfc::list_base_const_t & p_list) : m_list(p_list) {} + t_size get_count() const {return m_list.get_count();} + void get_item_ex(t_filestats & p_out, t_size n) const {p_out = m_list[n].m_stats;} + private: + const pfc::list_base_const_t & m_list; + }; + class metadb_io_hintlist_wrapper_part4 : public bit_array { + public: + metadb_io_hintlist_wrapper_part4(const pfc::list_base_const_t & p_list) : m_list(p_list) {} + bool get(t_size n) const {return m_list[n].m_fresh;} + private: + const pfc::list_base_const_t & m_list; + }; + + pfc::list_t m_entries; +}; + diff --git a/SDK/foobar2000/helpers/mp3_utils.cpp b/SDK/foobar2000/helpers/mp3_utils.cpp new file mode 100644 index 0000000..2511bd1 --- /dev/null +++ b/SDK/foobar2000/helpers/mp3_utils.cpp @@ -0,0 +1,261 @@ +#include "stdafx.h" + +using namespace bitreader_helper; + +static unsigned extract_header_bits(const t_uint8 p_header[4],unsigned p_base,unsigned p_bits) +{ + assert(p_base+p_bits<=32); + return (unsigned) extract_bits(p_header,p_base,p_bits); +} + +namespace { + + class header_parser + { + public: + header_parser(const t_uint8 p_header[4]) : m_bitptr(0) + { + memcpy(m_header,p_header,4); + } + unsigned read(unsigned p_bits) + { + unsigned ret = extract_header_bits(m_header,m_bitptr,p_bits); + m_bitptr += p_bits; + return ret; + } + private: + t_uint8 m_header[4]; + unsigned m_bitptr; + }; +} + +typedef t_uint16 uint16; + +static const uint16 bitrate_table_l1v1[16] = { 0, 32, 64, 96,128,160,192,224,256,288,320,352,384,416,448, 0}; +static const uint16 bitrate_table_l2v1[16] = { 0, 32, 48, 56, 64, 80, 96,112,128,160,192,224,256,320,384, 0}; +static const uint16 bitrate_table_l3v1[16] = { 0, 32, 40, 48, 56, 64, 80, 96,112,128,160,192,224,256,320, 0}; +static const uint16 bitrate_table_l1v2[16] = { 0, 32, 48, 56, 64, 80, 96,112,128,144,160,176,192,224,256, 0}; +static const uint16 bitrate_table_l23v2[16] = { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160, 0}; +static const uint16 sample_rate_table[] = {11025,12000,8000}; + +unsigned mp3_utils::QueryMPEGFrameSize(const t_uint8 p_header[4]) +{ + TMPEGFrameInfo info; + if (!ParseMPEGFrameHeader(info,p_header)) return 0; + return info.m_bytes; +} + +bool mp3_utils::ParseMPEGFrameHeader(TMPEGFrameInfo & p_info,const t_uint8 p_header[4]) +{ + enum {MPEG_LAYER_1 = 3, MPEG_LAYER_2 = 2, MPEG_LAYER_3 = 1}; + enum {_MPEG_1 = 3, _MPEG_2 = 2, _MPEG_25 = 0}; + + header_parser parser(p_header); + if (parser.read(11) != 0x7FF) return false; + unsigned mpeg_version = parser.read(2); + unsigned layer = parser.read(2); + unsigned protection = parser.read(1); + unsigned bitrate_index = parser.read(4); + unsigned sample_rate_index = parser.read(2); + if (sample_rate_index == 3) return false;//reserved + unsigned paddingbit = parser.read(1); + int paddingdelta = 0; + parser.read(1);//private + unsigned channel_mode = parser.read(2); + parser.read(2);//channel_mode_extension + parser.read(1);//copyright + parser.read(1);//original + parser.read(2);//emphasis + + unsigned bitrate = 0,sample_rate = 0; + + switch(layer) + { + default: + return false; + case MPEG_LAYER_3: + paddingdelta = paddingbit ? 1 : 0; + + p_info.m_layer = 3; + switch(mpeg_version) + { + case _MPEG_1: + p_info.m_duration = 1152; + bitrate = bitrate_table_l3v1[bitrate_index]; + break; + case _MPEG_2: + case _MPEG_25: + p_info.m_duration = 576; + bitrate = bitrate_table_l23v2[bitrate_index]; + break; + default: + return false; + } + + break; + case MPEG_LAYER_2: + paddingdelta = paddingbit ? 1 : 0; + p_info.m_duration = 1152; + p_info.m_layer = 2; + switch(mpeg_version) + { + case _MPEG_1: + bitrate = bitrate_table_l2v1[bitrate_index]; + break; + case _MPEG_2: + case _MPEG_25: + bitrate = bitrate_table_l23v2[bitrate_index]; + break; + default: + return false; + } + break; + case MPEG_LAYER_1: + paddingdelta = paddingbit ? 4 : 0; + p_info.m_duration = 384; + p_info.m_layer = 1; + switch(mpeg_version) + { + case _MPEG_1: + bitrate = bitrate_table_l1v1[bitrate_index]; + break; + case _MPEG_2: + case _MPEG_25: + bitrate = bitrate_table_l1v2[bitrate_index]; + break; + default: + return false; + } + break; + } + if (bitrate == 0) return false; + + sample_rate = sample_rate_table[sample_rate_index]; + if (sample_rate == 0) return false; + switch(mpeg_version) + { + case _MPEG_1: + sample_rate *= 4; + p_info.m_mpegversion = MPEG_1; + break; + case _MPEG_2: + sample_rate *= 2; + p_info.m_mpegversion = MPEG_2; + break; + case _MPEG_25: + p_info.m_mpegversion = MPEG_25; + break; + } + + switch(channel_mode) + { + case 0: + case 1: + case 2: + p_info.m_channels = 2; + break; + case 3: + p_info.m_channels = 1; + break; + } + + p_info.m_channel_mode = channel_mode; + + p_info.m_sample_rate = sample_rate; + + + p_info.m_bytes = ( bitrate /*kbps*/ * (1000/8) /* kbps-to-bytes*/ * p_info.m_duration /*samples-per-frame*/ ) / sample_rate + paddingdelta; + + if (p_info.m_layer == 1) p_info.m_bytes &= ~3; + + p_info.m_crc = protection == 0; + + return true; +} + +unsigned mp3header::get_samples_per_frame() +{ + mp3_utils::TMPEGFrameInfo fr; + if (!decode(fr)) return 0; + return fr.m_duration; +} + +bool mp3_utils::IsSameStream(TMPEGFrameInfo const & p_frame1,TMPEGFrameInfo const & p_frame2) { + return + p_frame1.m_channel_mode == p_frame2.m_channel_mode && + p_frame1.m_sample_rate == p_frame2.m_sample_rate && + p_frame1.m_layer == p_frame2.m_layer && + p_frame1.m_mpegversion == p_frame2.m_mpegversion; +} + + + +bool mp3_utils::ValidateFrameCRC(const t_uint8 * frameData, t_size frameSize, TMPEGFrameInfo const & info) { + if (frameSize < info.m_bytes) return false; //FAIL, incomplete data + if (!info.m_crc) return true; //nothing to check, frame appears valid + return ExtractFrameCRC(frameData, frameSize, info) == CalculateFrameCRC(frameData, frameSize, info); +} + +static t_uint32 CRC_update(unsigned value, t_uint32 crc) +{ + enum { CRC16_POLYNOMIAL = 0x8005 }; + unsigned i; + value <<= 8; + for (i = 0; i < 8; i++) { + value <<= 1; + crc <<= 1; + if (((crc ^ value) & 0x10000)) crc ^= CRC16_POLYNOMIAL; + } + return crc; +} + + +void mp3_utils::RecalculateFrameCRC(t_uint8 * frameData, t_size frameSize, TMPEGFrameInfo const & info) { + PFC_ASSERT( frameSize >= info.m_bytes && info.m_crc ); + + const t_uint16 crc = CalculateFrameCRC(frameData, frameSize, info); + frameData[4] = (t_uint8)(crc >> 8); + frameData[5] = (t_uint8)(crc & 0xFF); +} + +static t_uint16 grabFrameCRC(const t_uint8 * frameData, t_size sideInfoLen) { + t_uint32 crc = 0xffff; + crc = CRC_update(frameData[2], crc); + crc = CRC_update(frameData[3], crc); + for (t_size i = 6; i < sideInfoLen; i++) { + crc = CRC_update(frameData[i], crc); + } + + return (t_uint32) (crc & 0xFFFF); +} + +t_uint16 mp3_utils::ExtractFrameCRC(const t_uint8 * frameData, t_size frameSize, TMPEGFrameInfo const & info) { + PFC_ASSERT( frameSize >= info.m_bytes && info.m_crc ); + + return ((t_uint16)frameData[4] << 8) | (t_uint16)frameData[5]; + +} +t_uint16 mp3_utils::CalculateFrameCRC(const t_uint8 * frameData, t_size frameSize, TMPEGFrameInfo const & info) { + PFC_ASSERT( frameSize >= info.m_bytes && info.m_crc ); + + t_size sideInfoLen = 0; + if (info.m_mpegversion == MPEG_1) + sideInfoLen = (info.m_channels == 1) ? 4 + 17 : 4 + 32; + else + sideInfoLen = (info.m_channels == 1) ? 4 + 9 : 4 + 17; + + //CRC + sideInfoLen += 2; + + PFC_ASSERT( sideInfoLen <= frameSize ); + + return grabFrameCRC(frameData, sideInfoLen); +} + + +bool mp3_utils::ValidateFrameCRC(const t_uint8 * frameData, t_size frameSize) { + if (frameSize < 4) return false; //FAIL, not a valid frame + TMPEGFrameInfo info; + if (!ParseMPEGFrameHeader(info, frameData)) return false; //FAIL, not a valid frame + return ValidateFrameCRC(frameData, frameSize, info); +} diff --git a/SDK/foobar2000/helpers/mp3_utils.h b/SDK/foobar2000/helpers/mp3_utils.h new file mode 100644 index 0000000..13c9de4 --- /dev/null +++ b/SDK/foobar2000/helpers/mp3_utils.h @@ -0,0 +1,68 @@ +namespace mp3_utils +{ + + enum { + MPG_MD_STEREO=0, + MPG_MD_JOINT_STEREO=1, + MPG_MD_DUAL_CHANNEL=2, + MPG_MD_MONO=3, + }; + + typedef t_uint8 byte; + + enum {MPEG_1, MPEG_2, MPEG_25}; + + struct TMPEGFrameInfo + { + unsigned m_bytes; + unsigned m_sample_rate; + unsigned m_layer; + unsigned m_mpegversion; + unsigned m_channels; + unsigned m_duration; + unsigned m_channel_mode; + bool m_crc; + }; + + + bool ParseMPEGFrameHeader(TMPEGFrameInfo & p_info,const t_uint8 p_header[4]); + bool ValidateFrameCRC(const t_uint8 * frameData, t_size frameSize); + bool ValidateFrameCRC(const t_uint8 * frameData, t_size frameSize, TMPEGFrameInfo const & frameInfo); + + //! Assumes valid frame with CRC (frameInfo.m_crc set, frameInfo.m_bytes <= frameSize). + t_uint16 ExtractFrameCRC(const t_uint8 * frameData, t_size frameSize, TMPEGFrameInfo const & frameInfo); + //! Assumes valid frame with CRC (frameInfo.m_crc set, frameInfo.m_bytes <= frameSize). + t_uint16 CalculateFrameCRC(const t_uint8 * frameData, t_size frameSize, TMPEGFrameInfo const & frameInfo); + //! Assumes valid frame with CRC (frameInfo.m_crc set, frameInfo.m_bytes <= frameSize). + void RecalculateFrameCRC(t_uint8 * frameData, t_size frameSize, TMPEGFrameInfo const & frameInfo); + + unsigned QueryMPEGFrameSize(const t_uint8 p_header[4]); + bool IsSameStream(TMPEGFrameInfo const & p_frame1,TMPEGFrameInfo const & p_frame2); +}; + +class mp3header +{ + t_uint8 bytes[4]; +public: + + inline void copy(const mp3header & src) {memcpy(bytes,src.bytes,4);} + inline void copy_raw(const void * src) {memcpy(bytes,src,4);} + + inline mp3header(const mp3header & src) {copy(src);} + inline mp3header() {} + + inline const mp3header & operator=(const mp3header & src) {copy(src); return *this;} + + inline void get_bytes(void * out) {memcpy(out,bytes,4);} + inline unsigned get_frame_size() const {return mp3_utils::QueryMPEGFrameSize(bytes);} + inline bool decode(mp3_utils::TMPEGFrameInfo & p_out) {return mp3_utils::ParseMPEGFrameHeader(p_out,bytes);} + + unsigned get_samples_per_frame(); +}; + +static inline mp3header mp3header_from_buffer(const void * p_buffer) +{ + mp3header temp; + temp.copy_raw(p_buffer); + return temp; +} \ No newline at end of file diff --git a/SDK/foobar2000/helpers/playlist_position_reference_tracker.h b/SDK/foobar2000/helpers/playlist_position_reference_tracker.h new file mode 100644 index 0000000..2f79bab --- /dev/null +++ b/SDK/foobar2000/helpers/playlist_position_reference_tracker.h @@ -0,0 +1,73 @@ +class playlist_position_reference_tracker : public playlist_callback_impl_base { +public: + //! @param p_trackitem Specifies whether we want to track some specific item rather than just an offset in a playlist. When set to true, item index becomes invalidated when the item we're tracking is removed. + playlist_position_reference_tracker(bool p_trackitem = true) : playlist_callback_impl_base(~0), m_trackitem(p_trackitem), m_playlist(pfc_infinite), m_item(pfc_infinite) {} + + void on_items_added(t_size p_playlist,t_size p_start, const pfc::list_base_const_t & p_data,const bit_array & p_selection) { + if (p_playlist == m_playlist && m_item != pfc_infinite && p_start <= m_item) { + m_item += p_data.get_count(); + } + } + void on_items_reordered(t_size p_playlist,const t_size * p_order,t_size p_count) { + if (p_playlist == m_playlist) { + if (m_item < p_count) { + m_item = order_helper::g_find_reverse(p_order,m_item); + } else { + m_item = pfc_infinite; + } + } + } + + void on_items_removed(t_size p_playlist,const bit_array & p_mask,t_size p_old_count,t_size p_new_count) { + if (p_playlist == m_playlist) { + if (m_item < p_old_count) { + const t_size item_before = m_item; + for(t_size walk = p_mask.find_first(true,0,p_old_count); walk < p_old_count; walk = p_mask.find_next(true,walk,p_old_count)) { + if (walk < item_before) { + m_item--; + } else if (walk == item_before) { + if (m_trackitem) m_item = pfc_infinite; + break; + } else { + break; + } + } + if (m_item >= p_new_count) m_item = pfc_infinite; + } else { + m_item = pfc_infinite; + } + } + } + + //todo? could be useful in some cases + void on_items_replaced(t_size p_playlist,const bit_array & p_mask,const pfc::list_base_const_t & p_data) {} + + void on_playlist_created(t_size p_index,const char * p_name,t_size p_name_len) { + if (m_playlist != pfc_infinite && p_index <= m_playlist) m_playlist++; + } + void on_playlists_reorder(const t_size * p_order,t_size p_count) { + if (m_playlist < p_count) m_playlist = order_helper::g_find_reverse(p_order,m_playlist); + else m_playlist = pfc_infinite; + } + void on_playlists_removed(const bit_array & p_mask,t_size p_old_count,t_size p_new_count) { + if (m_playlist < p_old_count) { + const t_size playlist_before = m_playlist; + for(t_size walk = p_mask.find_first(true,0,p_old_count); walk < p_old_count; walk = p_mask.find_next(true,walk,p_old_count)) { + if (walk < playlist_before) { + m_playlist--; + } else if (walk == playlist_before) { + m_playlist = pfc_infinite; + break; + } else { + break; + } + } + } else { + m_playlist = pfc_infinite; + } + } + + t_size m_playlist, m_item; +private: + const bool m_trackitem; +}; diff --git a/SDK/foobar2000/helpers/seekabilizer.cpp b/SDK/foobar2000/helpers/seekabilizer.cpp new file mode 100644 index 0000000..75be809 --- /dev/null +++ b/SDK/foobar2000/helpers/seekabilizer.cpp @@ -0,0 +1,219 @@ +#include "stdafx.h" + +enum {backread_on_seek = 1024}; + +void seekabilizer_backbuffer::initialize(t_size p_size) +{ + m_depth = m_cursor = 0; + + m_buffer.set_size(p_size); +} + +void seekabilizer_backbuffer::write(const void * p_buffer,t_size p_bytes) +{ + if (p_bytes >= m_buffer.get_size()) + { + memcpy(m_buffer.get_ptr(),(const t_uint8*)p_buffer + p_bytes - m_buffer.get_size(),m_buffer.get_size()); + m_cursor = 0; + m_depth = m_buffer.get_size(); + } + else + { + const t_uint8* sourceptr = (const t_uint8*) p_buffer; + t_size remaining = p_bytes; + while(remaining > 0) + { + t_size delta = m_buffer.get_size() - m_cursor; + if (delta > remaining) delta = remaining; + + memcpy(m_buffer.get_ptr() + m_cursor,sourceptr,delta); + + sourceptr += delta; + remaining -= delta; + m_cursor = (m_cursor + delta) % m_buffer.get_size(); + + m_depth = pfc::min_t(m_buffer.get_size(),m_depth + delta); + + } + } +} + +void seekabilizer_backbuffer::read(t_size p_backlogdepth,void * p_buffer,t_size p_bytes) const +{ + assert(p_backlogdepth <= m_depth); + assert(p_backlogdepth >= p_bytes); + + + t_uint8* targetptr = (t_uint8*) p_buffer; + t_size remaining = p_bytes; + t_size cursor = (m_cursor + m_buffer.get_size() - p_backlogdepth) % m_buffer.get_size(); + + while(remaining > 0) + { + t_size delta = m_buffer.get_size() - cursor; + if (delta > remaining) delta = remaining; + + memcpy(targetptr,m_buffer.get_ptr() + cursor,delta); + + targetptr += delta; + remaining -= delta; + cursor = (cursor + delta) % m_buffer.get_size(); + } +} + +t_size seekabilizer_backbuffer::get_depth() const +{ + return m_depth; +} + +t_size seekabilizer_backbuffer::get_max_depth() const +{ + return m_buffer.get_size(); +} + +void seekabilizer_backbuffer::reset() +{ + m_depth = m_cursor = 0; +} + + +void seekabilizer::initialize(service_ptr_t p_base,t_size p_buffer_size,abort_callback & p_abort) { + m_buffer.initialize(p_buffer_size); + m_file = p_base; + m_position = m_position_base = 0; + m_size = m_file->get_size(p_abort); +} + +void seekabilizer::g_seekabilize(service_ptr_t & p_reader,t_size p_buffer_size,abort_callback & p_abort) { + if (p_reader.is_valid() && p_reader->is_remote() && p_buffer_size > 0) { + service_ptr_t instance = new service_impl_t(); + instance->initialize(p_reader,p_buffer_size,p_abort); + p_reader = instance.get_ptr(); + } +} + +t_size seekabilizer::read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + p_abort.check_e(); + + if (m_position > m_position_base + pfc::max_t(m_buffer.get_max_depth(),backread_on_seek) && m_file->can_seek()) { + m_buffer.reset(); + t_filesize target = m_position; + if (target < backread_on_seek) target = 0; + else target -= backread_on_seek; + m_file->seek(target,p_abort); + m_position_base = target; + } + + //seek ahead + while(m_position > m_position_base) { + enum {tempsize = 1024}; + t_uint8 temp[tempsize]; + t_size delta = (t_size) pfc::min_t(tempsize,m_position - m_position_base); + t_size bytes_read = 0; + bytes_read = m_file->read(temp,delta,p_abort); + m_buffer.write(temp,bytes_read); + m_position_base += bytes_read; + + if (bytes_read < delta) { + return 0; + } + } + + t_size done = 0; + t_uint8 * targetptr = (t_uint8*) p_buffer; + + //try to read backbuffer + if (m_position < m_position_base) { + if (m_position_base - m_position > (t_filesize)m_buffer.get_depth()) throw exception_io_seek_out_of_range(); + t_size backread_depth = (t_size) (m_position_base - m_position); + t_size delta = pfc::min_t(backread_depth,p_bytes-done); + m_buffer.read(backread_depth,targetptr,delta); + done += delta; + m_position += delta; + } + + //regular read + if (done < p_bytes) + { + t_size bytes_read; + bytes_read = m_file->read(targetptr+done,p_bytes-done,p_abort); + + m_buffer.write(targetptr+done,bytes_read); + + done += bytes_read; + m_position += bytes_read; + m_position_base += bytes_read; + } + + return done; +} + +t_filesize seekabilizer::get_size(abort_callback & p_abort) { + p_abort.check_e(); + return m_size; +} + +t_filesize seekabilizer::get_position(abort_callback & p_abort) { + p_abort.check_e(); + return m_position; +} + +void seekabilizer::seek(t_filesize p_position,abort_callback & p_abort) { + assert(m_position_base >= m_buffer.get_depth()); + p_abort.check_e(); + + if (m_size != filesize_invalid && p_position > m_size) throw exception_io_seek_out_of_range(); + + t_filesize lowest = m_position_base - m_buffer.get_depth(); + + if (p_position < lowest) { + if (m_file->can_seek()) { + m_buffer.reset(); + t_filesize target = p_position; + t_size delta = m_buffer.get_max_depth(); + if (delta > backread_on_seek) delta = backread_on_seek; + if (target > delta) target -= delta; + else target = 0; + m_file->seek(target,p_abort); + m_position_base = target; + } + else { + m_buffer.reset(); + m_file->reopen(p_abort); + m_position_base = 0; + } + } + + m_position = p_position; +} + +bool seekabilizer::can_seek() +{ + return true; +} + +bool seekabilizer::get_content_type(pfc::string_base & p_out) {return m_file->get_content_type(p_out);} + +bool seekabilizer::is_in_memory() {return false;} + +void seekabilizer::on_idle(abort_callback & p_abort) {return m_file->on_idle(p_abort);} + +t_filetimestamp seekabilizer::get_timestamp(abort_callback & p_abort) { + p_abort.check_e(); + return m_file->get_timestamp(p_abort); +} + +void seekabilizer::reopen(abort_callback & p_abort) { + if (m_position_base - m_buffer.get_depth() == 0) { + seek(0,p_abort); + } else { + m_position = m_position_base = 0; + m_buffer.reset(); + m_file->reopen(p_abort); + } +} + +bool seekabilizer::is_remote() +{ + return m_file->is_remote(); +} diff --git a/SDK/foobar2000/helpers/seekabilizer.h b/SDK/foobar2000/helpers/seekabilizer.h new file mode 100644 index 0000000..0025a64 --- /dev/null +++ b/SDK/foobar2000/helpers/seekabilizer.h @@ -0,0 +1,36 @@ +class seekabilizer_backbuffer +{ +public: + void initialize(t_size p_size); + void write(const void * p_buffer,t_size p_bytes); + void read(t_size p_backlogdepth,void * p_buffer,t_size p_bytes) const; + t_size get_depth() const; + void reset(); + t_size get_max_depth() const; +private: + pfc::array_t m_buffer; + t_size m_depth,m_cursor; +}; + +class seekabilizer : public file_readonly { +public: + void initialize(service_ptr_t p_base,t_size p_buffer_size,abort_callback & p_abort); + + static void g_seekabilize(service_ptr_t & p_reader,t_size p_buffer_size,abort_callback & p_abort); + + t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort); + t_filesize get_size(abort_callback & p_abort); + t_filesize get_position(abort_callback & p_abort); + void seek(t_filesize p_position,abort_callback & p_abort); + bool can_seek(); + bool get_content_type(pfc::string_base & p_out); + bool is_in_memory(); + void on_idle(abort_callback & p_abort); + t_filetimestamp get_timestamp(abort_callback & p_abort); + void reopen(abort_callback & p_abort); + bool is_remote(); +private: + service_ptr_t m_file; + seekabilizer_backbuffer m_buffer; + t_filesize m_size,m_position,m_position_base; +}; \ No newline at end of file diff --git a/SDK/foobar2000/helpers/stream_buffer_helper.cpp b/SDK/foobar2000/helpers/stream_buffer_helper.cpp new file mode 100644 index 0000000..edd3a79 --- /dev/null +++ b/SDK/foobar2000/helpers/stream_buffer_helper.cpp @@ -0,0 +1,87 @@ +#include "stdafx.h" + +stream_reader_buffered::stream_reader_buffered(stream_reader * p_base,t_size p_buffer) : m_base(p_base) +{ + m_buffer.set_size_in_range(pfc::min_t(1024, p_buffer), p_buffer); + m_bufferRemaining = 0; +} + +t_size stream_reader_buffered::read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + if (p_bytes <= m_bufferRemaining) { + memcpy( p_buffer, m_bufferPtr, p_bytes ); + m_bufferRemaining -= p_bytes; + m_bufferPtr += p_bytes; + return p_bytes; + } + + p_abort.check(); + char * output = (char*) p_buffer; + t_size output_ptr = 0; + + while(output_ptr < p_bytes) { + { + t_size delta = pfc::min_t(p_bytes - output_ptr, m_bufferRemaining); + if (delta > 0) + { + memcpy(output + output_ptr, m_bufferPtr, delta); + output_ptr += delta; + m_bufferPtr += delta; + m_bufferRemaining -= delta; + } + } + + if (m_bufferRemaining == 0) + { + t_size bytes_read; + bytes_read = m_base->read(m_buffer.get_ptr(), m_buffer.get_size(), p_abort); + m_bufferPtr = m_buffer.get_ptr(); + m_bufferRemaining = bytes_read; + + if (m_bufferRemaining == 0) break; + } + + } + + return output_ptr; +} + +stream_writer_buffered::stream_writer_buffered(stream_writer * p_base,t_size p_buffer) + : m_base(p_base) +{ + m_buffer.set_size_in_range(pfc::min_t(1024, p_buffer), p_buffer); + m_buffer_ptr = 0; +} + +void stream_writer_buffered::write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) { + p_abort.check_e(); + const char * source = (const char*)p_buffer; + t_size source_remaining = p_bytes; + const t_size buffer_size = m_buffer.get_size(); + if (source_remaining >= buffer_size) + { + flush(p_abort); + m_base->write_object(source,source_remaining,p_abort); + return; + } + + if (m_buffer_ptr + source_remaining >= buffer_size) + { + t_size delta = buffer_size - m_buffer_ptr; + memcpy(m_buffer.get_ptr() + m_buffer_ptr, source,delta); + source += delta; + source_remaining -= delta; + m_buffer_ptr += delta; + flush(p_abort); + } + + memcpy(m_buffer.get_ptr() + m_buffer_ptr, source,source_remaining); + m_buffer_ptr += source_remaining; +} + + +void stream_writer_buffered::flush(abort_callback & p_abort) { + if (m_buffer_ptr > 0) { + m_base->write_object(m_buffer.get_ptr(),m_buffer_ptr,p_abort); + m_buffer_ptr = 0; + } +} \ No newline at end of file diff --git a/SDK/foobar2000/helpers/stream_buffer_helper.h b/SDK/foobar2000/helpers/stream_buffer_helper.h new file mode 100644 index 0000000..999b7e9 --- /dev/null +++ b/SDK/foobar2000/helpers/stream_buffer_helper.h @@ -0,0 +1,27 @@ +class stream_reader_buffered : public stream_reader +{ +public: + stream_reader_buffered(stream_reader * p_base,t_size p_buffer); + t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort); +private: + stream_reader * m_base; + pfc::array_t m_buffer; + const char * m_bufferPtr; + size_t m_bufferRemaining; +}; + +class stream_writer_buffered : public stream_writer +{ +public: + stream_writer_buffered(stream_writer * p_base,t_size p_buffer); + + void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort); + + void flush(abort_callback & p_abort); + +private: + stream_writer * m_base; + pfc::array_t m_buffer; + t_size m_buffer_ptr; +}; + diff --git a/SDK/foobar2000/helpers/string_filter.h b/SDK/foobar2000/helpers/string_filter.h new file mode 100644 index 0000000..c396c19 --- /dev/null +++ b/SDK/foobar2000/helpers/string_filter.h @@ -0,0 +1,24 @@ +class string_filter_noncasesensitive { +public: + string_filter_noncasesensitive(const char * p_string,t_size p_string_len = ~0) { + ::uStringLower(m_pattern,p_string,p_string_len); + } + + bool test(const char * p_string,t_size p_string_len = ~0) const { + ::uStringLower(m_lowercasebuffer,p_string,p_string_len); + t_size walk = 0; + while(m_pattern[walk] != 0) { + while(m_pattern[walk] == ' ') walk++; + t_size delta = 0; + while(m_pattern[walk+delta] != 0 && m_pattern[walk+delta] != ' ') delta++; + if (delta > 0) { + if (pfc::string_find_first_ex(m_lowercasebuffer,~0,m_pattern+walk,delta) == ~0) return false; + } + walk += delta; + } + return true; + } +private: + mutable pfc::string8_fastalloc m_lowercasebuffer; + pfc::string8 m_pattern; +}; diff --git a/SDK/foobar2000/helpers/text_file_loader.cpp b/SDK/foobar2000/helpers/text_file_loader.cpp new file mode 100644 index 0000000..0ae4714 --- /dev/null +++ b/SDK/foobar2000/helpers/text_file_loader.cpp @@ -0,0 +1,106 @@ +#include "StdAfx.h" + +// FIX ME non working on non Windows due to ANSI nonsense + +static const unsigned char utf8_header[3] = {0xEF,0xBB,0xBF}; + +namespace text_file_loader +{ + void write(const service_ptr_t & p_file,abort_callback & p_abort,const char * p_string,bool is_utf8) + { + p_file->seek(0,p_abort); + p_file->set_eof(p_abort); + if (is_utf8) + { + p_file->write_object(utf8_header,sizeof(utf8_header),p_abort); + p_file->write_object(p_string,strlen(p_string),p_abort); + } + else + { +#ifdef _WIN32 + pfc::stringcvt::string_ansi_from_utf8 bah(p_string); + p_file->write_object(bah,bah.length(),p_abort); +#else + throw exception_io_data(); +#endif + } + } + + void read(const service_ptr_t & p_file,abort_callback & p_abort,pfc::string_base & p_out,bool & is_utf8) { + p_out.reset(); + if (p_file->can_seek()) + { + p_file->seek(0,p_abort); + } + + pfc::array_t mem; + t_filesize size64; + size64 = p_file->get_size(p_abort); + if (size64 == filesize_invalid)//typically HTTP + { + pfc::string8 ansitemp; + is_utf8 = false; + enum {delta = 1024*64, max = 1024*512}; + char temp[3]; + t_size done; + done = p_file->read(temp,3,p_abort); + if (done != 3) + { + if (done > 0) p_out = pfc::stringcvt::string_utf8_from_ansi(temp,done); + return; + } + if (!memcmp(utf8_header,temp,3)) is_utf8 = true; + else ansitemp.add_string(temp,3); + + mem.set_size(delta); + + for(;;) + { + done = p_file->read(mem.get_ptr(),delta,p_abort); + if (done > 0) + { + if (is_utf8) p_out.add_string(mem.get_ptr(),done); + else ansitemp.add_string(mem.get_ptr(),done); + } + if (done < delta) break; + } + + if (!is_utf8) + { + p_out = pfc::stringcvt::string_utf8_from_ansi(ansitemp); + } + + return; + } + else + { + if (size64>1024*1024*128) throw exception_io_data();//hard limit + t_size size = pfc::downcast_guarded(size64); + mem.set_size(size+1); + char * asdf = mem.get_ptr(); + p_file->read_object(asdf,size,p_abort); + asdf[size]=0; + if (size>3 && !memcmp(utf8_header,asdf,3)) {is_utf8 = true; p_out.add_string(asdf+3); } + else { + is_utf8 = false; + p_out = pfc::stringcvt::string_utf8_from_ansi(asdf); + } + return; + } + } + + void write(const char * p_path,abort_callback & p_abort,const char * p_string,bool is_utf8) + { + service_ptr_t f; + filesystem::g_open_write_new(f,p_path,p_abort); + write(f,p_abort,p_string,is_utf8); + } + + void read(const char * p_path,abort_callback & p_abort,pfc::string_base & p_out,bool & is_utf8) + { + service_ptr_t f; + filesystem::g_open_read(f,p_path,p_abort); + read(f,p_abort,p_out,is_utf8); + } + +} \ No newline at end of file diff --git a/SDK/foobar2000/helpers/text_file_loader.h b/SDK/foobar2000/helpers/text_file_loader.h new file mode 100644 index 0000000..853cce0 --- /dev/null +++ b/SDK/foobar2000/helpers/text_file_loader.h @@ -0,0 +1,9 @@ +namespace text_file_loader +{ + void write(const service_ptr_t & p_file,abort_callback & p_abort,const char * p_string,bool is_utf8); + void read(const service_ptr_t & p_file,abort_callback & p_abort,pfc::string_base & p_out,bool & is_utf8); + + void write(const char * p_path,abort_callback & p_abort,const char * p_string,bool is_utf8); + void read(const char * p_path,abort_callback & p_abort,pfc::string_base & p_out,bool & is_utf8); + +}; \ No newline at end of file diff --git a/SDK/foobar2000/helpers/win32_dialog.cpp b/SDK/foobar2000/helpers/win32_dialog.cpp new file mode 100644 index 0000000..04a3fdb --- /dev/null +++ b/SDK/foobar2000/helpers/win32_dialog.cpp @@ -0,0 +1,291 @@ +#include "stdafx.h" + +#ifdef _WIN32 + +namespace dialog_helper { + + + INT_PTR CALLBACK dialog::DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp) + { + dialog * p_this; + BOOL rv; + if (msg==WM_INITDIALOG) + { + p_this = reinterpret_cast(lp); + p_this->wnd = wnd; + SetWindowLongPtr(wnd,DWLP_USER,lp); + + if (p_this->m_is_modal) p_this->m_modal_scope.initialize(wnd); + } + else p_this = reinterpret_cast(GetWindowLongPtr(wnd,DWLP_USER)); + + rv = p_this ? p_this->on_message(msg,wp,lp) : FALSE; + + if (msg==WM_DESTROY && p_this) + { + SetWindowLongPtr(wnd,DWLP_USER,0); +// p_this->wnd = 0; + } + + return rv; + } + + + int dialog::run_modal(unsigned id,HWND parent) + { + assert(wnd == 0); + if (wnd != 0) return -1; + m_is_modal = true; + return uDialogBox(id,parent,DlgProc,reinterpret_cast(this)); + } + HWND dialog::run_modeless(unsigned id,HWND parent) + { + assert(wnd == 0); + if (wnd != 0) return 0; + m_is_modal = false; + return uCreateDialog(id,parent,DlgProc,reinterpret_cast(this)); + } + + void dialog::end_dialog(int code) + { + assert(m_is_modal); + if (m_is_modal) uEndDialog(wnd,code); + } + + + + + + + + + + + int dialog_modal::run(unsigned p_id,HWND p_parent,HINSTANCE p_instance) + { + int status; + + // note: uDialogBox() has its own modal scope, we don't want that to trigger + // if this is ever changed, move deinit to WM_DESTROY handler in DlgProc + + status = (int)DialogBoxParam(p_instance,MAKEINTRESOURCE(p_id),p_parent,DlgProc,reinterpret_cast(this)); + + m_modal_scope.deinitialize(); + + return status; + } + + void dialog_modal::end_dialog(int p_code) + { + EndDialog(m_wnd,p_code); + } + + + INT_PTR CALLBACK dialog_modal::DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp) + { + dialog_modal * _this; + if (msg==WM_INITDIALOG) + { + _this = reinterpret_cast(lp); + _this->m_wnd = wnd; + SetWindowLongPtr(wnd,DWLP_USER,lp); + + _this->m_modal_scope.initialize(wnd); + } + else _this = reinterpret_cast(GetWindowLongPtr(wnd,DWLP_USER)); + + assert(_this == 0 || _this->m_wnd == wnd); + + return _this ? _this->on_message(msg,wp,lp) : FALSE; + } + + + bool dialog_modeless::create(unsigned p_id,HWND p_parent,HINSTANCE p_instance) { + assert(!m_is_in_create); + if (m_is_in_create) return false; + pfc::vartoggle_t scope(m_is_in_create,true); + if (CreateDialogParam(p_instance,MAKEINTRESOURCE(p_id),p_parent,DlgProc,reinterpret_cast(this)) == 0) return false; + return m_wnd != 0; + } + + dialog_modeless::~dialog_modeless() { + assert(!m_is_in_create); + switch(m_destructor_status) + { + case destructor_none: + m_destructor_status = destructor_normal; + if (m_wnd != 0) + { + DestroyWindow(m_wnd); + m_wnd = 0; + } + break; + case destructor_fromwindow: + if (m_wnd != 0) SetWindowLongPtr(m_wnd,DWLP_USER,0); + break; + default: + //should never trigger + pfc::crash(); + break; + } + } + + void dialog_modeless::on_window_destruction() + { + if (m_is_in_create) + { + m_wnd = 0; + } + else + switch(m_destructor_status) + { + case destructor_none: + m_destructor_status = destructor_fromwindow; + delete this; + break; + case destructor_fromwindow: + pfc::crash(); + break; + default: + break; + } + } + + BOOL dialog_modeless::on_message_wrap(UINT msg,WPARAM wp,LPARAM lp) + { + if (m_destructor_status == destructor_none) + return on_message(msg,wp,lp); + else + return FALSE; + } + + INT_PTR CALLBACK dialog_modeless::DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp) + { + dialog_modeless * thisptr; + BOOL rv; + if (msg == WM_INITDIALOG) + { + thisptr = reinterpret_cast(lp); + thisptr->m_wnd = wnd; + SetWindowLongPtr(wnd,DWLP_USER,lp); + modeless_dialog_manager::g_add(wnd); + } + else thisptr = reinterpret_cast(GetWindowLongPtr(wnd,DWLP_USER)); + + rv = thisptr ? thisptr->on_message_wrap(msg,wp,lp) : FALSE; + + if (msg == WM_DESTROY) + modeless_dialog_manager::g_remove(wnd); + + if (msg == WM_DESTROY && thisptr != 0) + thisptr->on_window_destruction(); + + return rv; + } + + + + + + + + + + + + + + + + + dialog_modeless_v2::dialog_modeless_v2(unsigned p_id,HWND p_parent,HINSTANCE p_instance,bool p_stealfocus) : m_wnd(0), m_status(status_construction), m_stealfocus(p_stealfocus) + { + WIN32_OP( CreateDialogParam(p_instance,MAKEINTRESOURCE(p_id),p_parent,DlgProc,reinterpret_cast(this)) != NULL ); + m_status = status_lifetime; + } + + dialog_modeless_v2::~dialog_modeless_v2() + { + bool is_window_being_destroyed = (m_status == status_destruction_requested); + m_status = status_destruction; + + if (m_wnd != 0) + { + if (is_window_being_destroyed) + detach_window(); + else + DestroyWindow(m_wnd); + } + } + + INT_PTR CALLBACK dialog_modeless_v2::DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp) + { + dialog_modeless_v2 * thisptr; + BOOL rv = FALSE; + if (msg == WM_INITDIALOG) + { + thisptr = reinterpret_cast(lp); + assert(thisptr->m_status == status_construction); + thisptr->m_wnd = wnd; + SetWindowLongPtr(wnd,DWLP_USER,lp); + if (GetWindowLong(wnd,GWL_STYLE) & WS_POPUP) { + modeless_dialog_manager::g_add(wnd); + } + } + else thisptr = reinterpret_cast(GetWindowLongPtr(wnd,DWLP_USER)); + + if (thisptr != NULL) rv = thisptr->on_message_internal(msg,wp,lp); + + if (msg == WM_DESTROY) + { + modeless_dialog_manager::g_remove(wnd); + } + + return rv; + } + + + void dialog_modeless_v2::detach_window() + { + if (m_wnd != 0) + { + SetWindowLongPtr(m_wnd,DWLP_USER,0); + m_wnd = 0; + } + } + + + BOOL dialog_modeless_v2::on_message_internal(UINT msg,WPARAM wp,LPARAM lp) + { + if (m_status == status_lifetime || m_status == status_destruction_requested) + { + if (msg == WM_DESTROY) + { + assert(m_status == status_lifetime); + m_status = status_destruction_requested; + delete this; + return TRUE; + } + else + return on_message(msg,wp,lp); + } + else if (m_status == status_construction) + { + if (msg == WM_INITDIALOG) return m_stealfocus ? TRUE : FALSE; + else return FALSE; + } + else return FALSE; + } +} + +HWND uCreateDialog(UINT id,HWND parent,DLGPROC proc,LPARAM param) +{ + return CreateDialogParam(core_api::get_my_instance(),MAKEINTRESOURCE(id),parent,proc,param); +} + +int uDialogBox(UINT id,HWND parent,DLGPROC proc,LPARAM param) +{ + return (int)DialogBoxParam(core_api::get_my_instance(),MAKEINTRESOURCE(id),parent,proc,param); +} + +#endif \ No newline at end of file diff --git a/SDK/foobar2000/helpers/win32_dialog.h b/SDK/foobar2000/helpers/win32_dialog.h new file mode 100644 index 0000000..4ac7154 --- /dev/null +++ b/SDK/foobar2000/helpers/win32_dialog.h @@ -0,0 +1,126 @@ +#ifdef _WIN32 + +#ifndef _FOOBAR2000_HELPERS_WIN32_DIALOG_H_ +#define _FOOBAR2000_HELPERS_WIN32_DIALOG_H_ + +//DEPRECATED dialog helpers - kept only for compatibility with old code - do not use in new code, use WTL instead. + +namespace dialog_helper +{ + + class dialog + { + protected: + + dialog() : wnd(0), m_is_modal(false) {} + ~dialog() { } + + virtual BOOL on_message(UINT msg,WPARAM wp,LPARAM lp)=0; + + void end_dialog(int code); + + public: + inline HWND get_wnd() {return wnd;} + + __declspec(deprecated) int run_modal(unsigned id,HWND parent); + + __declspec(deprecated) HWND run_modeless(unsigned id,HWND parent); + private: + HWND wnd; + static INT_PTR CALLBACK DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp); + + bool m_is_modal; + + modal_dialog_scope m_modal_scope; + }; + + //! This class is meant to be instantiated on-stack, as a local variable. Using new/delete operators instead or even making this a member of another object works, but does not make much sense because of the way this works (single run() call). + class dialog_modal + { + public: + __declspec(deprecated) int run(unsigned p_id,HWND p_parent,HINSTANCE p_instance = core_api::get_my_instance()); + protected: + virtual BOOL on_message(UINT msg,WPARAM wp,LPARAM lp)=0; + + inline dialog_modal() : m_wnd(0) {} + void end_dialog(int p_code); + inline HWND get_wnd() const {return m_wnd;} + private: + static INT_PTR CALLBACK DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp); + + HWND m_wnd; + modal_dialog_scope m_modal_scope; + }; + + //! This class is meant to be used with new/delete operators only. Destroying the window - outside create() / WM_INITDIALOG - will result in object calling delete this. If object is deleted directly using delete operator, WM_DESTROY handler may not be called so it should not be used (use destructor of derived class instead). + //! Classes derived from dialog_modeless must not be instantiated in any other way than operator new(). + /*! Typical usage : \n + class mydialog : public dialog_helper::dialog_modeless {...}; + (...) + bool createmydialog() + { + mydialog * instance = new mydialog; + if (instance == 0) return flase; + if (!instance->create(...)) {delete instance; return false;} + return true; + } + + */ + class dialog_modeless + { + public: + //! Creates the dialog window. This will call on_message with WM_INITDIALOG. To abort creation, you can call DestroyWindow() on our window; it will not delete the object but make create() return false instead. You should not delete the object from inside WM_INITDIALOG handler or anything else possibly called from create(). + //! @returns true on success, false on failure. + __declspec(deprecated) bool create(unsigned p_id,HWND p_parent,HINSTANCE p_instance = core_api::get_my_instance()); + protected: + //! Standard windows message handler (DialogProc-style). Use get_wnd() to retrieve our dialog window handle. + virtual BOOL on_message(UINT msg,WPARAM wp,LPARAM lp)=0; + + inline dialog_modeless() : m_wnd(0), m_destructor_status(destructor_none), m_is_in_create(false) {} + inline HWND get_wnd() const {return m_wnd;} + virtual ~dialog_modeless(); + private: + static INT_PTR CALLBACK DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp); + void on_window_destruction(); + + BOOL on_message_wrap(UINT msg,WPARAM wp,LPARAM lp); + + HWND m_wnd; + enum {destructor_none,destructor_normal,destructor_fromwindow} m_destructor_status; + bool m_is_in_create; + }; + + + class dialog_modeless_v2 + { + protected: + __declspec(deprecated) explicit dialog_modeless_v2(unsigned p_id,HWND p_parent,HINSTANCE p_instance = core_api::get_my_instance(),bool p_stealfocus = true); + virtual ~dialog_modeless_v2(); + HWND get_wnd() const {return m_wnd;} + virtual BOOL on_message(UINT msg,WPARAM wp,LPARAM lp) {return FALSE;} + + static dialog_modeless_v2 * __unsafe__instance_from_window(HWND p_wnd) {return reinterpret_cast(GetWindowLongPtr(p_wnd,DWLP_USER));} + private: + static INT_PTR CALLBACK DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp); + void detach_window(); + BOOL on_message_internal(UINT msg,WPARAM wp,LPARAM lp); + enum {status_construction, status_lifetime, status_destruction_requested, status_destruction} m_status; + HWND m_wnd; + const bool m_stealfocus; + + const dialog_modeless_v2 & operator=(const dialog_modeless_v2 &); + dialog_modeless_v2(const dialog_modeless_v2 &); + }; + +}; + +//! Wrapper (provided mainly for old code), simplifies parameters compared to standard CreateDialog() by using core_api::get_my_instance(). +HWND uCreateDialog(UINT id,HWND parent,DLGPROC proc,LPARAM param = 0); +//! Wrapper (provided mainly for old code), simplifies parameters compared to standard DialogBox() by using core_api::get_my_instance(). +int uDialogBox(UINT id,HWND parent,DLGPROC proc,LPARAM param = 0); + + +#endif + + +#endif // _WIN32 \ No newline at end of file diff --git a/SDK/foobar2000/helpers/win32_misc.cpp b/SDK/foobar2000/helpers/win32_misc.cpp new file mode 100644 index 0000000..504e706 --- /dev/null +++ b/SDK/foobar2000/helpers/win32_misc.cpp @@ -0,0 +1,288 @@ +#include "stdafx.h" + +void registerclass_scope_delayed::toggle_on(UINT p_style,WNDPROC p_wndproc,int p_clsextra,int p_wndextra,HICON p_icon,HCURSOR p_cursor,HBRUSH p_background,const TCHAR * p_class_name,const TCHAR * p_menu_name) { + toggle_off(); + WNDCLASS wc = {}; + wc.style = p_style; + wc.lpfnWndProc = p_wndproc; + wc.cbClsExtra = p_clsextra; + wc.cbWndExtra = p_wndextra; + wc.hInstance = core_api::get_my_instance(); + wc.hIcon = p_icon; + wc.hCursor = p_cursor; + wc.hbrBackground = p_background; + wc.lpszMenuName = p_menu_name; + wc.lpszClassName = p_class_name; + WIN32_OP_CRITICAL("RegisterClass", (m_class = RegisterClass(&wc)) != 0); +} + +void registerclass_scope_delayed::toggle_off() { + if (m_class != 0) { + UnregisterClass((LPCTSTR)m_class,core_api::get_my_instance()); + m_class = 0; + } +} + + +unsigned QueryScreenDPI() { + HDC dc = GetDC(0); + unsigned ret = GetDeviceCaps(dc,LOGPIXELSY); + ReleaseDC(0,dc); + return ret; +} + + +SIZE QueryScreenDPIEx() { + HDC dc = GetDC(0); + SIZE ret = { GetDeviceCaps(dc,LOGPIXELSY), GetDeviceCaps(dc,LOGPIXELSY) }; + ReleaseDC(0,dc); + return ret; +} + + +bool IsMenuNonEmpty(HMENU menu) { + unsigned n,m=GetMenuItemCount(menu); + for(n=0;n msgFormatted; msgFormatted.set_size(pfc::strlen_t(_Message) + 64); + wsprintfW(msgFormatted.get_ptr(), L"%s (code: %u)", _Message, code); + if (IsDebuggerPresent()) { + OutputDebugString(TEXT("WIN32_OP_D() failure:\n")); + OutputDebugString(msgFormatted.get_ptr()); + OutputDebugString(TEXT("\n")); + pfc::crash(); + } + _wassert(msgFormatted.get_ptr(),_File,_Line); +} +#endif + + +void GetOSVersionString(pfc::string_base & out) { + out.reset(); GetOSVersionStringAppend(out); +} + +static bool running_under_wine(void) { + HMODULE module = GetModuleHandle(_T("ntdll.dll")); + if (!module) return false; + return GetProcAddress(module, "wine_server_call") != NULL; +} +static bool FetchWineInfoAppend(pfc::string_base & out) { + typedef const char *(__cdecl *t_wine_get_build_id)(void); + typedef void (__cdecl *t_wine_get_host_version)( const char **sysname, const char **release ); + const HMODULE ntdll = GetModuleHandle(_T("ntdll.dll")); + if (ntdll == NULL) return false; + t_wine_get_build_id wine_get_build_id; + t_wine_get_host_version wine_get_host_version; + wine_get_build_id = (t_wine_get_build_id)GetProcAddress(ntdll, "wine_get_build_id"); + wine_get_host_version = (t_wine_get_host_version)GetProcAddress(ntdll, "wine_get_host_version"); + if (wine_get_build_id == NULL || wine_get_host_version == NULL) { + if (GetProcAddress(ntdll, "wine_server_call") != NULL) { + out << "wine (unknown version)"; + return true; + } + return false; + } + const char * sysname = NULL; const char * release = NULL; + wine_get_host_version(&sysname, &release); + out << wine_get_build_id() << ", on: " << sysname << " / " << release; + return true; +} +void GetOSVersionStringAppend(pfc::string_base & out) { + + if (FetchWineInfoAppend(out)) return; + + OSVERSIONINFO ver = {}; ver.dwOSVersionInfoSize = sizeof(ver); + WIN32_OP( GetVersionEx(&ver) ); + SYSTEM_INFO info = {}; + GetNativeSystemInfo(&info); + + out << "Windows " << (int)ver.dwMajorVersion << "." << (int)ver.dwMinorVersion << "." << (int)ver.dwBuildNumber; + if (ver.szCSDVersion[0] != 0) out << " " << pfc::stringcvt::string_utf8_from_os(ver.szCSDVersion, PFC_TABSIZE(ver.szCSDVersion)); + + switch(info.wProcessorArchitecture) { + case PROCESSOR_ARCHITECTURE_AMD64: + out << " x64"; break; + case PROCESSOR_ARCHITECTURE_IA64: + out << " IA64"; break; + case PROCESSOR_ARCHITECTURE_INTEL: + out << " x86"; break; + } +} + + +void SetDefaultMenuItem(HMENU p_menu,unsigned p_id) { + MENUITEMINFO info = {sizeof(info)}; + info.fMask = MIIM_STATE; + GetMenuItemInfo(p_menu,p_id,FALSE,&info); + info.fState |= MFS_DEFAULT; + SetMenuItemInfo(p_menu,p_id,FALSE,&info); +} + + +bool SetClipboardDataBlock(UINT p_format,const void * p_block,t_size p_block_size) { + bool success = false; + if (OpenClipboard(NULL)) { + EmptyClipboard(); + HANDLE handle = GlobalAlloc(GMEM_MOVEABLE,p_block_size); + if (handle == NULL) { + CloseClipboard(); + throw std::bad_alloc(); + } + {CGlobalLock lock(handle);memcpy(lock.GetPtr(),p_block,p_block_size);} + if (SetClipboardData(p_format,handle) == NULL) { + GlobalFree(handle);//todo? + } else { + success = true; + } + CloseClipboard(); + } + return success; +} + +mutexScope::mutexScope(HANDLE hMutex_, abort_callback & abort) : hMutex(hMutex_) { + HANDLE h[2] = {hMutex, abort.get_abort_event()}; + switch( WaitForMultipleObjects(2, h, FALSE, INFINITE) ) { + case WAIT_OBJECT_0: + break; // and enter + case WAIT_OBJECT_0+1: + throw exception_aborted(); + default: + uBugCheck(); + } +} +mutexScope::~mutexScope() { + ReleaseMutex(hMutex); +} + + + +void winLocalFileScope::open( const char * inPath, file::ptr inReader, abort_callback & aborter) { + close(); + if (inPath != NULL) { + if (_extract_native_path_ptr( inPath ) ) { + pfc::string8 prefixed; + pfc::winPrefixPath( prefixed, inPath ); + m_path = pfc::stringcvt::string_wide_from_utf8( prefixed ); + m_isTemp = false; + return; + } + } + + pfc::string8 tempPath; + if (!uGetTempPath( tempPath )) uBugCheck(); + tempPath.add_filename( PFC_string_formatter() << pfc::print_guid( pfc::createGUID() ) << ".rar" ); + + m_path = pfc::stringcvt::string_wide_from_utf8( tempPath ); + + if (inReader.is_empty()) { + if (inPath == NULL) uBugCheck(); + inReader = fileOpenReadExisting( inPath, aborter, 1.0 ); + } + + file::ptr writer = fileOpenWriteNew( PFC_string_formatter() << "file://" << tempPath, aborter, 1.0 ); + file::g_transfer_file( inReader , writer, aborter ); + m_isTemp = true; +} +void winLocalFileScope::close() { + if (m_isTemp && m_path.length() > 0) { + pfc::lores_timer timer; + timer.start(); + for(;;) { + if (DeleteFile( m_path.c_str() )) break; + if (timer.query() > 1.0) break; + Sleep(10); + } + } + m_path.clear(); +} + +CMutex::CMutex(const TCHAR * name) { + WIN32_OP_CRITICAL( "CreateMutex", m_hMutex = CreateMutex(NULL, FALSE, name) ); +} +CMutex::~CMutex() { + CloseHandle(m_hMutex); +} + +void CMutex::AcquireByHandle( HANDLE hMutex, abort_callback & aborter ) { + SetLastError(0); + HANDLE hWait[2] = {hMutex, aborter.get_abort_event()}; + switch(WaitForMultipleObjects( 2, hWait, FALSE, INFINITE ) ) { + case WAIT_FAILED: + WIN32_OP_FAIL_CRITICAL("WaitForSingleObject"); + case WAIT_OBJECT_0: + return; + case WAIT_OBJECT_0 + 1: + PFC_ASSERT( aborter.is_aborting() ); + throw exception_aborted(); + default: + uBugCheck(); + } +} + +void CMutex::Acquire( abort_callback& aborter ) { + AcquireByHandle( Handle(), aborter ); +} + +void CMutex::Release() { + ReleaseMutex( Handle() ); +} + + +CMutexScope::CMutexScope(CMutex & mutex, DWORD timeOutMS, const char * timeOutBugMsg) : m_mutex(mutex) { + SetLastError(0); + const unsigned div = 4; + for(unsigned walk = 0; walk < div; ++walk) { + switch(WaitForSingleObject( m_mutex.Handle(), timeOutMS/div ) ) { + case WAIT_FAILED: + WIN32_OP_FAIL_CRITICAL("WaitForSingleObject"); + case WAIT_OBJECT_0: + return; + case WAIT_TIMEOUT: + break; + default: + uBugCheck(); + } + } + TRACK_CODE(timeOutBugMsg, uBugCheck()); +} + +CMutexScope::CMutexScope(CMutex & mutex) : m_mutex(mutex) { + SetLastError(0); + switch(WaitForSingleObject( m_mutex.Handle(), INFINITE ) ) { + case WAIT_FAILED: + WIN32_OP_FAIL_CRITICAL("WaitForSingleObject"); + case WAIT_OBJECT_0: + return; + default: + uBugCheck(); + } +} + +CMutexScope::CMutexScope(CMutex & mutex, abort_callback & aborter) : m_mutex(mutex) { + mutex.Acquire( aborter ); +} + +CMutexScope::~CMutexScope() { + ReleaseMutex(m_mutex.Handle()); +} \ No newline at end of file diff --git a/SDK/foobar2000/helpers/win32_misc.h b/SDK/foobar2000/helpers/win32_misc.h new file mode 100644 index 0000000..d3bf5cc --- /dev/null +++ b/SDK/foobar2000/helpers/win32_misc.h @@ -0,0 +1,374 @@ +PFC_NORETURN PFC_NOINLINE void WIN32_OP_FAIL(); +PFC_NORETURN PFC_NOINLINE void WIN32_OP_FAIL_CRITICAL(const char * what); + +#ifdef _DEBUG +void WIN32_OP_D_FAIL(const wchar_t * _Message, const wchar_t *_File, unsigned _Line); +#endif + +//Throws an exception when (OP) evaluates to false/zero. +#define WIN32_OP(OP) \ + { \ + SetLastError(NO_ERROR); \ + if (!(OP)) WIN32_OP_FAIL(); \ + } + +// Kills the application with appropriate debug info when (OP) evaluates to false/zero. +#define WIN32_OP_CRITICAL(WHAT, OP) \ + { \ + SetLastError(NO_ERROR); \ + if (!(OP)) WIN32_OP_FAIL_CRITICAL(WHAT); \ + } + +//WIN32_OP_D() acts like an assert specialized for win32 operations in debug build, ignores the return value / error codes in release build. +//Use WIN32_OP_D() instead of WIN32_OP() on operations that are extremely unlikely to fail, so failure condition checks are performed in the debug build only, to avoid bloating release code with pointless error checks. +#ifdef _DEBUG +#define WIN32_OP_D(OP) \ + { \ + SetLastError(NO_ERROR); \ + if (!(OP)) WIN32_OP_D_FAIL(PFC_WIDESTRING(#OP), PFC_WIDESTRING(__FILE__), __LINE__); \ + } + +#else +#define WIN32_OP_D(OP) (void)( (OP), 0); +#endif + + +class registerclass_scope_delayed { +public: + registerclass_scope_delayed() : m_class(0) {} + + bool is_registered() const {return m_class != 0;} + void toggle_on(UINT p_style,WNDPROC p_wndproc,int p_clsextra,int p_wndextra,HICON p_icon,HCURSOR p_cursor,HBRUSH p_background,const TCHAR * p_classname,const TCHAR * p_menuname); + void toggle_off(); + ATOM get_class() const {return m_class;} + + ~registerclass_scope_delayed() {toggle_off();} +private: + registerclass_scope_delayed(const registerclass_scope_delayed &) {throw pfc::exception_not_implemented();} + const registerclass_scope_delayed & operator=(const registerclass_scope_delayed &) {throw pfc::exception_not_implemented();} + + ATOM m_class; +}; + + + +typedef CGlobalLockScope CGlobalLock;//for compatibility, implementation moved elsewhere + +bool SetClipboardDataBlock(UINT p_format,const void * p_block,t_size p_block_size); + +template +static bool SetClipboardDataBlock(UINT p_format,const t_array & p_array) { + PFC_STATIC_ASSERT( sizeof(p_array[0]) == 1 ); + return SetClipboardDataBlock(p_format,p_array.get_ptr(),p_array.get_size()); +} + +template +static bool GetClipboardDataBlock(UINT p_format,t_array & p_array) { + PFC_STATIC_ASSERT( sizeof(p_array[0]) == 1 ); + if (OpenClipboard(NULL)) { + HANDLE handle = GetClipboardData(p_format); + if (handle == NULL) { + CloseClipboard(); + return false; + } + { + CGlobalLock lock(handle); + const t_size size = lock.GetSize(); + try { + p_array.set_size(size); + } catch(...) { + CloseClipboard(); + throw; + } + memcpy(p_array.get_ptr(),lock.GetPtr(),size); + } + CloseClipboard(); + return true; + } else { + return false; + } +} + + +class OleInitializeScope { +public: + OleInitializeScope() { + if (FAILED(OleInitialize(NULL))) throw pfc::exception("OleInitialize() failure"); + } + ~OleInitializeScope() { + OleUninitialize(); + } + +private: + PFC_CLASS_NOT_COPYABLE(OleInitializeScope,OleInitializeScope); +}; + +class CoInitializeScope { +public: + CoInitializeScope() { + if (FAILED(CoInitialize(NULL))) throw pfc::exception("CoInitialize() failed"); + } + CoInitializeScope(DWORD params) { + if (FAILED(CoInitializeEx(NULL, params))) throw pfc::exception("CoInitialize() failed"); + } + ~CoInitializeScope() { + CoUninitialize(); + } + PFC_CLASS_NOT_COPYABLE_EX(CoInitializeScope) +}; + + +unsigned QueryScreenDPI(); + +SIZE QueryScreenDPIEx(); + +static WORD GetOSVersion() { + const DWORD ver = GetVersion(); + return (WORD)HIBYTE(LOWORD(ver)) | ((WORD)LOBYTE(LOWORD(ver)) << 8); +} + +#if _WIN32_WINNT >= 0x501 +#define WS_EX_COMPOSITED_Safe() WS_EX_COMPOSITED +#else +static DWORD WS_EX_COMPOSITED_Safe() { + return (GetOSVersion() < 0x501) ? 0 : 0x02000000L; +} +#endif + + + + + +class EnableWindowScope { +public: + EnableWindowScope(HWND p_window,BOOL p_state) throw() : m_window(p_window) { + m_oldState = IsWindowEnabled(m_window); + EnableWindow(m_window,p_state); + } + ~EnableWindowScope() throw() { + EnableWindow(m_window,m_oldState); + } + +private: + BOOL m_oldState; + HWND m_window; +}; + +bool IsMenuNonEmpty(HMENU menu); + +class SetTextColorScope { +public: + SetTextColorScope(HDC dc, COLORREF col) throw() : m_dc(dc) { + m_oldCol = SetTextColor(dc,col); + } + ~SetTextColorScope() throw() { + SetTextColor(m_dc,m_oldCol); + } + PFC_CLASS_NOT_COPYABLE_EX(SetTextColorScope) +private: + HDC m_dc; + COLORREF m_oldCol; +}; + +class CloseHandleScope { +public: + CloseHandleScope(HANDLE handle) throw() : m_handle(handle) {} + ~CloseHandleScope() throw() {CloseHandle(m_handle);} + HANDLE Detach() throw() {return pfc::replace_t(m_handle,INVALID_HANDLE_VALUE);} + HANDLE Get() const throw() {return m_handle;} + void Close() throw() {CloseHandle(Detach());} + PFC_CLASS_NOT_COPYABLE_EX(CloseHandleScope) +private: + HANDLE m_handle; +}; + +class CModelessDialogEntry { +public: + inline CModelessDialogEntry() : m_wnd() {} + inline CModelessDialogEntry(HWND p_wnd) : m_wnd() {Set(p_wnd);} + inline ~CModelessDialogEntry() {Set(NULL);} + + void Set(HWND p_new) { + static_api_ptr_t api; + if (m_wnd) api->remove(m_wnd); + m_wnd = p_new; + if (m_wnd) api->add(m_wnd); + } +private: + PFC_CLASS_NOT_COPYABLE_EX(CModelessDialogEntry); + HWND m_wnd; +}; + +void GetOSVersionString(pfc::string_base & out); +void GetOSVersionStringAppend(pfc::string_base & out); + + + +void SetDefaultMenuItem(HMENU p_menu,unsigned p_id); + + + + +class TypeFind { +public: + static LRESULT Handler(NMHDR* hdr, int subItemFrom = 0, int subItemCnt = 1) { + NMLVFINDITEM * info = reinterpret_cast(hdr); + const HWND wnd = hdr->hwndFrom; + if (info->lvfi.flags & LVFI_NEARESTXY) return -1; + const size_t count = _ItemCount(wnd); + if (count == 0) return -1; + const size_t base = (size_t) info->iStart % count; + for(size_t walk = 0; walk < count; ++walk) { + const size_t index = (walk + base) % count; + for(int subItem = subItemFrom; subItem < subItemFrom + subItemCnt; ++subItem) { + if (StringPrefixMatch(info->lvfi.psz, _ItemText(wnd, index, subItem))) return (LRESULT) index; + } + } + for(size_t walk = 0; walk < count; ++walk) { + const size_t index = (walk + base) % count; + for(int subItem = subItemFrom; subItem < subItemFrom + subItemCnt; ++subItem) { + if (StringPartialMatch(info->lvfi.psz, _ItemText(wnd, index, subItem))) return (LRESULT) index; + } + } + return -1; + } + + static wchar_t myCharLower(wchar_t c) { + return (wchar_t) CharLower((wchar_t*)c); + } + static bool StringPrefixMatch(const wchar_t * part, const wchar_t * str) { + unsigned walk = 0; + for(;;) { + wchar_t c1 = part[walk], c2 = str[walk]; + if (c1 == 0) return true; + if (c2 == 0) return false; + if (myCharLower(c1) != myCharLower(c2)) return false; + ++walk; + } + } + + static bool StringPartialMatch(const wchar_t * part, const wchar_t * str) { + unsigned base = 0; + for(;;) { + unsigned walk = 0; + for(;;) { + wchar_t c1 = part[walk], c2 = str[base + walk]; + if (c1 == 0) return true; + if (c2 == 0) return false; + if (myCharLower(c1) != myCharLower(c2)) break; + ++walk; + } + ++ base; + } + } + + static size_t _ItemCount(HWND wnd) { + return ListView_GetItemCount(wnd); + } + static const wchar_t * _ItemText(HWND wnd, size_t index, int subItem = 0) { + NMLVDISPINFO info = {}; + info.hdr.code = LVN_GETDISPINFO; + info.hdr.idFrom = GetDlgCtrlID(wnd); + info.hdr.hwndFrom = wnd; + info.item.iItem = index; + info.item.iSubItem = subItem; + info.item.mask = LVIF_TEXT; + ::SendMessage(::GetParent(wnd), WM_NOTIFY, info.hdr.idFrom, reinterpret_cast(&info)); + if (info.item.pszText == NULL) return L""; + return info.item.pszText; + } + +}; + + +class mutexScope { +public: + mutexScope(HANDLE hMutex_, abort_callback & abort); + ~mutexScope(); +private: + PFC_CLASS_NOT_COPYABLE_EX(mutexScope); + HANDLE hMutex; +}; + +class CDLL { +public: +#ifdef _DEBUG + static LPTOP_LEVEL_EXCEPTION_FILTER _GetEH() { + LPTOP_LEVEL_EXCEPTION_FILTER rv = SetUnhandledExceptionFilter(NULL); + SetUnhandledExceptionFilter(rv); + return rv; + } +#endif + CDLL(const wchar_t * Name) : hMod() { + Load(Name); + } + CDLL() : hMod() {} + void Load(const wchar_t * Name) { + PFC_ASSERT( hMod == NULL ); +#ifdef _DEBUG + auto handlerBefore = _GetEH(); +#endif + WIN32_OP( hMod = LoadLibrary(Name) ); +#ifdef _DEBUG + PFC_ASSERT( handlerBefore == _GetEH() ); +#endif + } + + + ~CDLL() { + if (hMod) FreeLibrary(hMod); + } + template void Bind(funcptr_t & outFunc, const char * name) { + WIN32_OP( outFunc = (funcptr_t)GetProcAddress(hMod, name) ); + } + + HMODULE hMod; + + PFC_CLASS_NOT_COPYABLE_EX(CDLL); +}; + +class winLocalFileScope { +public: + void open( const char * inPath, file::ptr inReader, abort_callback & aborter); + void close(); + + winLocalFileScope() : m_isTemp() {} + winLocalFileScope( const char * inPath, file::ptr inReader, abort_callback & aborter ) : m_isTemp() { + open( inPath, inReader, aborter ); + } + + ~winLocalFileScope() { + close(); + } + + const wchar_t * Path() const {return m_path.c_str();} +private: + bool m_isTemp; + std::wstring m_path; +}; + + + +class CMutex { +public: + CMutex(const TCHAR * name = NULL); + ~CMutex(); + HANDLE Handle() {return m_hMutex;} + static void AcquireByHandle( HANDLE hMutex, abort_callback & aborter ); + void Acquire( abort_callback& aborter ); + void Release(); +private: + CMutex(const CMutex&); void operator=(const CMutex&); + HANDLE m_hMutex; +}; + +class CMutexScope { +public: + CMutexScope(CMutex & mutex, DWORD timeOutMS, const char * timeOutBugMsg); + CMutexScope(CMutex & mutex); + CMutexScope(CMutex & mutex, abort_callback & aborter); + ~CMutexScope(); +private: + CMutexScope(const CMutexScope &); void operator=(const CMutexScope&); + CMutex & m_mutex; +}; diff --git a/SDK/foobar2000/helpers/window_placement_helper.cpp b/SDK/foobar2000/helpers/window_placement_helper.cpp new file mode 100644 index 0000000..4de5357 --- /dev/null +++ b/SDK/foobar2000/helpers/window_placement_helper.cpp @@ -0,0 +1,216 @@ +#include "stdafx.h" + +#ifdef _WIN32 + +static bool g_is_enabled() +{ + return standard_config_objects::query_remember_window_positions(); +} + +static BOOL CALLBACK __MonitorEnumProc( + HMONITOR hMonitor, // handle to display monitor + HDC hdcMonitor, // handle to monitor DC + LPRECT lprcMonitor, // monitor intersection rectangle + LPARAM dwData // data + ) { + RECT * clip = (RECT*)dwData; + RECT newclip; + if (UnionRect(&newclip,clip,lprcMonitor)) { + *clip = newclip; + } + return TRUE; +} + +static bool test_rect(const RECT * rc) { + RECT clip = {}; + if (EnumDisplayMonitors(NULL,NULL,__MonitorEnumProc,(LPARAM)&clip)) { + const LONG sanitycheck = 4; + const LONG cwidth = clip.right - clip.left; + const LONG cheight = clip.bottom - clip.top; + + const LONG width = rc->right - rc->left; + const LONG height = rc->bottom - rc->top; + + if (width > cwidth * sanitycheck || height > cheight * sanitycheck) return false; + } + + return MonitorFromRect(rc,MONITOR_DEFAULTTONULL) != NULL; +} + + +bool cfg_window_placement::read_from_window(HWND window) +{ + WINDOWPLACEMENT wp = {}; + if (g_is_enabled()) { + wp.length = sizeof(wp); + if (!GetWindowPlacement(window,&wp)) { + PFC_ASSERT(!"GetWindowPlacement fail!"); + memset(&wp,0,sizeof(wp)); + } else { + // bad, breaks with taskbar on top + /*if (wp.showCmd == SW_SHOWNORMAL) { + GetWindowRect(window, &wp.rcNormalPosition); + }*/ + } + /*else + { + if (!IsWindowVisible(window)) wp.showCmd = SW_HIDE; + }*/ + } + m_data = wp; + return m_data.length == sizeof(m_data); +} + +void cfg_window_placement::on_window_creation_silent(HWND window) { + PFC_ASSERT(!m_windows.have_item(window)); + m_windows.add_item(window); +} +bool cfg_window_placement::on_window_creation(HWND window) +{ + bool ret = false; + PFC_ASSERT(!m_windows.have_item(window)); + m_windows.add_item(window); + + if (g_is_enabled()) + { + if (m_data.length==sizeof(m_data) && test_rect(&m_data.rcNormalPosition)) + { + if (SetWindowPlacement(window,&m_data)) + { + ret = true; + } + } + } + + return ret; +} + + +void cfg_window_placement::on_window_destruction(HWND window) +{ + if (m_windows.have_item(window)) + { + read_from_window(window); + m_windows.remove_item(window); + } +} + +void cfg_window_placement::get_data_raw(stream_writer * p_stream,abort_callback & p_abort) { + if (g_is_enabled()) { + { + t_size n, m = m_windows.get_count(); + for(n=0;nwrite_object(&m_data,sizeof(m_data),p_abort); + } + } +} + +void cfg_window_placement::set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) { + if (p_sizehint == 0) return; + WINDOWPLACEMENT temp; + try { + p_stream->read_object(&temp,sizeof(temp),p_abort); + } catch(exception_io_data) {return;} + if (temp.length == sizeof(temp)) m_data = temp; +} + + +cfg_window_placement::cfg_window_placement(const GUID & p_guid) : cfg_var(p_guid) +{ + memset(&m_data,0,sizeof(m_data)); +} + + +cfg_window_size::cfg_window_size(const GUID & p_guid) : cfg_var(p_guid), m_width(~0), m_height(~0) {} + +static BOOL SetWindowSize(HWND p_wnd,unsigned p_x,unsigned p_y) +{ + if (p_x != ~0 && p_y != ~0) + return SetWindowPos(p_wnd,0,0,0,p_x,p_y,SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOZORDER); + else + return FALSE; +} + +bool cfg_window_size::on_window_creation(HWND p_wnd) +{ + bool ret = false; + PFC_ASSERT(!m_windows.have_item(p_wnd)); + m_windows.add_item(p_wnd); + + if (g_is_enabled()) + { + if (SetWindowSize(p_wnd,m_width,m_height)) ret = true; + } + + return ret; +} + +void cfg_window_size::on_window_destruction(HWND p_wnd) +{ + if (m_windows.have_item(p_wnd)) + { + read_from_window(p_wnd); + m_windows.remove_item(p_wnd); + } +} + +bool cfg_window_size::read_from_window(HWND p_wnd) +{ + if (g_is_enabled()) + { + RECT r; + if (GetWindowRect(p_wnd,&r)) + { + m_width = r.right - r.left; + m_height = r.bottom - r.top; + return true; + } + else + { + m_width = m_height = ~0; + return false; + } + } + else + { + m_width = m_height = ~0; + return false; + } +} + +void cfg_window_size::get_data_raw(stream_writer * p_stream,abort_callback & p_abort) { + if (g_is_enabled()) { + { + t_size n, m = m_windows.get_count(); + for(n=0;nwrite_lendian_t(m_width,p_abort); + p_stream->write_lendian_t(m_height,p_abort); + } + } +} + +void cfg_window_size::set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) { + if (p_sizehint == 0) return; + t_uint32 width,height; + try { + p_stream->read_lendian_t(width,p_abort); + p_stream->read_lendian_t(height,p_abort); + } catch(exception_io_data) {return;} + + m_width = width; m_height = height; +} +#endif // _WIN32 diff --git a/SDK/foobar2000/helpers/window_placement_helper.h b/SDK/foobar2000/helpers/window_placement_helper.h new file mode 100644 index 0000000..a66fa81 --- /dev/null +++ b/SDK/foobar2000/helpers/window_placement_helper.h @@ -0,0 +1,38 @@ +#ifdef _WIN32 + +#ifndef _WINDOW_PLACEMENT_HELPER_H_ +#define _WINDOW_PLACEMENT_HELPER_H_ + +class cfg_window_placement : public cfg_var +{ +public: + bool on_window_creation(HWND window);//returns true if window position has been changed, false if not + void on_window_creation_silent(HWND window); + void on_window_destruction(HWND window); + bool read_from_window(HWND window); + void get_data_raw(stream_writer * p_stream,abort_callback & p_abort); + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort); + cfg_window_placement(const GUID & p_guid); +private: + pfc::list_hybrid_t m_windows; + WINDOWPLACEMENT m_data; +}; + +class cfg_window_size : public cfg_var +{ +public: + bool on_window_creation(HWND window);//returns true if window position has been changed, false if not + void on_window_destruction(HWND window); + bool read_from_window(HWND window); + void get_data_raw(stream_writer * p_stream,abort_callback & p_abort); + void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort); + cfg_window_size(const GUID & p_guid); +private: + pfc::list_hybrid_t m_windows; + t_uint32 m_width,m_height; +}; + + +#endif //_WINDOW_PLACEMENT_HELPER_H_ + +#endif // _WIN32 \ No newline at end of file diff --git a/SDK/foobar2000/helpers/writer_wav.cpp b/SDK/foobar2000/helpers/writer_wav.cpp new file mode 100644 index 0000000..f1bbe33 --- /dev/null +++ b/SDK/foobar2000/helpers/writer_wav.cpp @@ -0,0 +1,283 @@ +#include "stdafx.h" + + +static const GUID guid_RIFF = pfc::GUID_from_text("66666972-912E-11CF-A5D6-28DB04C10000"); +static const GUID guid_WAVE = pfc::GUID_from_text("65766177-ACF3-11D3-8CD1-00C04F8EDB8A"); +static const GUID guid_FMT = pfc::GUID_from_text("20746D66-ACF3-11D3-8CD1-00C04F8EDB8A"); +static const GUID guid_DATA = pfc::GUID_from_text("61746164-ACF3-11D3-8CD1-00C04F8EDB8A"); + +struct RIFF_chunk_desc { + GUID m_guid; + const char * m_name; +}; + +static const RIFF_chunk_desc RIFF_chunks[] = { + {guid_RIFF, "RIFF"}, + {guid_WAVE, "WAVE"}, + {guid_FMT , "fmt "}, + {guid_DATA, "data"}, +}; + +bool wavWriterSetup_t::needWFXE() const { + if (this->m_bpsValid != this->m_bps) return true; + switch(m_channels) + { + case 1: + return m_channel_mask != audio_chunk::channel_config_mono; + case 2: + return m_channel_mask != audio_chunk::channel_config_stereo; +/* case 4: + m_wfxe = m_setup.m_channel_mask != (audio_chunk::channel_front_left | audio_chunk::channel_front_right | audio_chunk::channel_back_left | audio_chunk::channel_back_right); + break; + case 6: + m_wfxe = m_setup.m_channel_mask != audio_chunk::channel_config_5point1; + break;*/ + default: + return true; + } + +} + +void wavWriterSetup_t::initialize3(const audio_chunk::spec_t & spec, unsigned bps, unsigned bpsValid, bool bFloat, bool bDither, bool bWave64) { + m_bps = bps; + m_bpsValid = bpsValid; + m_samplerate = spec.sampleRate; + m_channels = spec.chanCount; + m_channel_mask = spec.chanMask; + m_float = bFloat; + m_dither = bDither; + m_wave64 = bWave64; +} + +void wavWriterSetup_t::initialize2(const audio_chunk & p_chunk, unsigned p_bps, unsigned p_bpsValid, bool p_float, bool p_dither, bool p_wave64) { + m_bps = p_bps; + m_bpsValid = p_bpsValid; + m_samplerate = p_chunk.get_srate(); + m_channels = p_chunk.get_channels(); + m_channel_mask = p_chunk.get_channel_config(); + m_float = p_float; + m_dither = p_dither; + m_wave64 = p_wave64; +} + +void wavWriterSetup_t::initialize(const audio_chunk & p_chunk, unsigned p_bps, bool p_float, bool p_dither, bool p_wave64) +{ + unsigned bpsValid = p_bps; + unsigned bps = (p_bps + 7) & ~7; + initialize2(p_chunk, bps, bpsValid, p_float, p_dither, p_wave64); +} + +void wavWriterSetup_t::setup_wfx(WAVEFORMATEX & p_wfx) +{ + p_wfx.wFormatTag = m_float ? WAVE_FORMAT_IEEE_FLOAT : WAVE_FORMAT_PCM; + p_wfx.nChannels = m_channels; + p_wfx.nSamplesPerSec = m_samplerate; + p_wfx.nAvgBytesPerSec = (m_bps >> 3) * m_channels * m_samplerate; + p_wfx.nBlockAlign = (m_bps>>3) * m_channels; + p_wfx.wBitsPerSample = m_bps; + p_wfx.cbSize = 0; +} + +void wavWriterSetup_t::setup_wfxe(WAVEFORMATEXTENSIBLE & p_wfxe) +{ + setup_wfx(p_wfxe.Format); + p_wfxe.Format.wFormatTag=WAVE_FORMAT_EXTENSIBLE; + p_wfxe.Format.cbSize=22; + p_wfxe.Samples.wValidBitsPerSample = this->m_bpsValid; + p_wfxe.dwChannelMask = audio_chunk::g_channel_config_to_wfx(m_channel_mask); + p_wfxe.SubFormat = m_float ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM; + +} + +void CWavWriter::writeID(const GUID & id, abort_callback & abort) { + if (is64()) { + m_file->write_object_t(id, abort); + } else { + for(t_size walk = 0; walk < PFC_TABSIZE(RIFF_chunks); ++walk) { + if (id == RIFF_chunks[walk].m_guid) { + m_file->write(RIFF_chunks[walk].m_name, 4, abort); return; + } + } + uBugCheck(); + } +} + +void CWavWriter::writeSize(t_uint64 size, abort_callback & abort) { + if (is64()) { + if (size != ~0) size += 24; + m_file->write_lendian_t(size, abort); + } else { + t_uint32 clipped; + if (size > 0xFFFFFFFF) clipped = 0xFFFFFFFF; + else clipped = (t_uint32) size; + m_file->write_lendian_t(clipped, abort); + } +} + +size_t CWavWriter::align(abort_callback & abort) { + t_uint8 dummy[8] = {}; + const t_uint32 val = is64() ? 8 : 2; + t_filesize pos = m_file->get_position(abort); + t_size delta = (val - (pos%val)) % val; + if (delta > 0) m_file->write(dummy, delta, abort); + return delta; +} + +void CWavWriter::open(const char * p_path, const wavWriterSetup_t & p_setup, abort_callback & p_abort) +{ + service_ptr_t l_file; + filesystem::g_open_write_new(l_file,p_path,p_abort); + open(l_file,p_setup,p_abort); +} + +namespace { +PFC_DECLARE_EXCEPTION(exceptionBadBitDepth, exception_io_data, "Invalid bit depth specified"); +} +void CWavWriter::open(service_ptr_t p_file, const wavWriterSetup_t & p_setup, abort_callback & p_abort) +{ + m_file = p_file; + m_setup = p_setup; + + if (m_setup.m_channels == 0 || m_setup.m_channels > 18 || m_setup.m_channels != audio_chunk::g_count_channels(m_setup.m_channel_mask)) throw exception_io_data(); + + if (!audio_chunk::g_is_valid_sample_rate(m_setup.m_samplerate)) throw exception_io_data(); + + if (m_setup.m_bpsValid > m_setup.m_bps) throw exceptionBadBitDepth(); + + if (m_setup.m_float) + { + if (m_setup.m_bps != 32 && m_setup.m_bps != 64) throw exceptionBadBitDepth(); + if (m_setup.m_bpsValid != m_setup.m_bps) throw exceptionBadBitDepth(); + } + else + { + if (m_setup.m_bps != 8 && m_setup.m_bps != 16 && m_setup.m_bps != 24 && m_setup.m_bps != 32) throw exceptionBadBitDepth(); + if (m_setup.m_bpsValid < 1) throw exceptionBadBitDepth(); + } + + m_wfxe = m_setup.needWFXE(); + + writeID(guid_RIFF, p_abort); + m_offset_fix1 = m_file->get_position(p_abort); + writeSize(~0, p_abort); + + writeID(guid_WAVE, p_abort); + + writeID(guid_FMT, p_abort); + if (m_wfxe) { + writeSize(sizeof(WAVEFORMATEXTENSIBLE),p_abort); + + WAVEFORMATEXTENSIBLE wfxe; + m_setup.setup_wfxe(wfxe); + m_file->write_object(&wfxe,sizeof(wfxe),p_abort); + } else { + writeSize(sizeof(PCMWAVEFORMAT),p_abort); + + WAVEFORMATEX wfx; + m_setup.setup_wfx(wfx); + m_file->write_object(&wfx,/* blah */ sizeof(PCMWAVEFORMAT),p_abort); + } + align(p_abort); + + writeID(guid_DATA, p_abort); + m_offset_fix2 = m_file->get_position(p_abort); + writeSize(~0, p_abort); + m_offset_fix1_delta = m_file->get_position(p_abort) - chunkOverhead(); + + + m_bytes_written = 0; + + if (!m_setup.m_float) + { + m_postprocessor = standard_api_create_t(); + } +} + +void CWavWriter::write(const audio_chunk & p_chunk, abort_callback & p_abort) +{ + if (p_chunk.get_channels() != m_setup.m_channels + || p_chunk.get_channel_config() != m_setup.m_channel_mask + || p_chunk.get_srate() != m_setup.m_samplerate + ) throw exception_unexpected_audio_format_change(); + + + if (m_setup.m_float) + { + switch(m_setup.m_bps) + { + case 32: + { +#if audio_sample_size == 32 + t_size bytes = p_chunk.get_sample_count() * p_chunk.get_channels() * sizeof(audio_sample); + m_file->write_object(p_chunk.get_data(),bytes,p_abort); + m_bytes_written += bytes; +#else + enum {tempsize = 256}; + double temp[tempsize]; + t_size todo = p_chunk.get_sample_count() * p_chunk.get_channels(); + const audio_sample * readptr = p_chunk.get_data(); + while(todo > 0) + { + unsigned n,delta = todo; + if (delta > tempsize) delta = tempsize; + for(n=0;nwrite_object(temp,bytes,p_abort); + m_bytes_written += bytes; + todo -= delta; + } +#endif + } + break; +#if 0 + case 64: + { + unsigned bytes = p_chunk.get_sample_count() * p_chunk.get_channels() * sizeof(audio_sample); + m_file->write_object_e(p_chunk.get_data(),bytes,p_abort); + m_bytes_written += bytes; + } + break; +#endif + default: + throw exception_io_data(); + } + } + else + { + m_postprocessor->run(p_chunk,m_postprocessor_output,m_setup.m_bpsValid,m_setup.m_bps,m_setup.m_dither,1.0f); + m_file->write_object(m_postprocessor_output.get_ptr(),m_postprocessor_output.get_size(),p_abort); + m_bytes_written += m_postprocessor_output.get_size(); + } +} + +void CWavWriter::finalize(abort_callback & p_abort) +{ + if (m_file.is_valid()) + { + const size_t alignG = align(p_abort); + + if (m_file->can_seek()) { + m_file->seek(m_offset_fix1,p_abort); + writeSize(m_bytes_written + alignG + m_offset_fix1_delta, p_abort); + m_file->seek(m_offset_fix2,p_abort); + writeSize(m_bytes_written, p_abort); + } + m_file.release(); + } + m_postprocessor.release(); +} + +void CWavWriter::close() +{ + m_file.release(); + m_postprocessor.release(); +} + +audio_chunk::spec_t CWavWriter::get_spec() const { + audio_chunk::spec_t spec = {}; + spec.sampleRate = m_setup.m_samplerate; + spec.chanCount = m_setup.m_channels; + spec.chanMask = m_setup.m_channel_mask; + return spec; +} diff --git a/SDK/foobar2000/helpers/writer_wav.h b/SDK/foobar2000/helpers/writer_wav.h new file mode 100644 index 0000000..2320b60 --- /dev/null +++ b/SDK/foobar2000/helpers/writer_wav.h @@ -0,0 +1,52 @@ +#ifndef _foobar2000_wav_writer_h_ +#define _foobar2000_wav_writer_h_ + +#ifdef _WIN32 +#include +#endif + +struct wavWriterSetup_t +{ + unsigned m_bps,m_bpsValid,m_samplerate,m_channels,m_channel_mask; + bool m_float,m_dither, m_wave64; + + + void initialize(const audio_chunk & p_chunk,unsigned p_bps,bool p_float,bool p_dither, bool p_wave64 = false); + void initialize2(const audio_chunk & p_chunk,unsigned p_bps, unsigned p_bpsValid,bool p_float,bool p_dither, bool p_wave64 = false); + void initialize3(const audio_chunk::spec_t & spec, unsigned bps, unsigned bpsValid, bool bFloat, bool bDither, bool bWave64 = false); + +#ifdef _WAVEFORMATEX_ + void setup_wfx(WAVEFORMATEX & p_wfx); +#endif +#ifdef _WAVEFORMATEXTENSIBLE_ + void setup_wfxe(WAVEFORMATEXTENSIBLE & p_wfx); +#endif + bool needWFXE() const; +}; + +class CWavWriter +{ +public: + void open(const char * p_path, const wavWriterSetup_t & p_setup, abort_callback & p_abort); + void open(service_ptr_t p_file, const wavWriterSetup_t & p_setup, abort_callback & p_abort); + void write(const audio_chunk & p_chunk,abort_callback & p_abort); + void finalize(abort_callback & p_abort); + void close(); + bool is_open() const { return m_file.is_valid(); } + audio_chunk::spec_t get_spec() const; +private: + size_t align(abort_callback & abort); + void writeSize(t_uint64 size, abort_callback & abort); + bool is64() const {return m_setup.m_wave64;} + t_uint32 chunkOverhead() const {return is64() ? 24 : 8;} + t_uint32 idOverhead() const {return is64() ? 16 : 4;} + void writeID(const GUID & id, abort_callback & abort); + service_ptr_t m_file; + service_ptr_t m_postprocessor; + wavWriterSetup_t m_setup; + bool m_wfxe; + t_uint64 m_offset_fix1,m_offset_fix2,m_offset_fix1_delta,m_bytes_written; + mem_block_container_aligned_incremental_impl<16> m_postprocessor_output; +}; + +#endif //_foobar2000_wav_writer_h_ \ No newline at end of file diff --git a/SDK/foobar2000/shared/audio_math.h b/SDK/foobar2000/shared/audio_math.h new file mode 100644 index 0000000..fd7e505 --- /dev/null +++ b/SDK/foobar2000/shared/audio_math.h @@ -0,0 +1,65 @@ +#pragma once + +#define audio_sample_bytes (audio_sample_size/8) + +/* +PROBLEM: +audio_math is implemented in pfc (pfc::audio_math) and in shared.dll (::audio_math) +We must overlay shared.dll methods on top of PFC ones +*/ + +namespace audio_math +{ + //! p_source/p_output can point to same buffer + void SHARED_EXPORT scale(const audio_sample * p_source,t_size p_count,audio_sample * p_output,audio_sample p_scale); + void SHARED_EXPORT convert_to_int16(const audio_sample * p_source,t_size p_count,t_int16 * p_output,audio_sample p_scale); + void SHARED_EXPORT convert_to_int32(const audio_sample * p_source,t_size p_count,t_int32 * p_output,audio_sample p_scale); + audio_sample SHARED_EXPORT convert_to_int16_calculate_peak(const audio_sample * p_source,t_size p_count,t_int16 * p_output,audio_sample p_scale); + void SHARED_EXPORT convert_from_int16(const t_int16 * p_source,t_size p_count,audio_sample * p_output,audio_sample p_scale); + void SHARED_EXPORT convert_from_int32(const t_int32 * p_source,t_size p_count,audio_sample * p_output,audio_sample p_scale); + audio_sample SHARED_EXPORT convert_to_int32_calculate_peak(const audio_sample * p_source,t_size p_count,t_int32 * p_output,audio_sample p_scale); + audio_sample SHARED_EXPORT calculate_peak(const audio_sample * p_source,t_size p_count); + void SHARED_EXPORT kill_denormal(audio_sample * p_buffer,t_size p_count); + void SHARED_EXPORT add_offset(audio_sample * p_buffer,audio_sample p_delta,t_size p_count); +} + +namespace audio_math_shareddll = audio_math; +typedef pfc::audio_math audio_math_pfc; + +// Overlay class, overrides specific pfc::audio_math methods +class fb2k_audio_math : public audio_math_pfc { +public: + static void scale(const audio_sample * p_source,t_size p_count,audio_sample * p_output,audio_sample p_scale) { + audio_math_shareddll::scale(p_source, p_count, p_output, p_scale); + } + static void convert_to_int16(const audio_sample * p_source,t_size p_count,t_int16 * p_output,audio_sample p_scale) { + audio_math_shareddll::convert_to_int16(p_source, p_count, p_output, p_scale); + } + static void convert_to_int32(const audio_sample * p_source,t_size p_count,t_int32 * p_output,audio_sample p_scale) { + audio_math_shareddll::convert_to_int32(p_source, p_count, p_output, p_scale); + } + static audio_sample convert_to_int16_calculate_peak(const audio_sample * p_source,t_size p_count,t_int16 * p_output,audio_sample p_scale) { + return audio_math_shareddll::convert_to_int16_calculate_peak(p_source,p_count,p_output,p_scale); + } + static void convert_from_int16(const t_int16 * p_source,t_size p_count,audio_sample * p_output,audio_sample p_scale) { + audio_math_shareddll::convert_from_int16(p_source,p_count,p_output,p_scale); + } + static void convert_from_int32(const t_int32 * p_source,t_size p_count,audio_sample * p_output,audio_sample p_scale) { + audio_math_shareddll::convert_from_int32(p_source,p_count,p_output,p_scale); + } + static audio_sample convert_to_int32_calculate_peak(const audio_sample * p_source,t_size p_count,t_int32 * p_output,audio_sample p_scale) { + return audio_math_shareddll::convert_to_int32_calculate_peak(p_source,p_count,p_output,p_scale); + } + static audio_sample calculate_peak(const audio_sample * p_source,t_size p_count) { + return audio_math_shareddll::calculate_peak(p_source,p_count); + } + static void kill_denormal(audio_sample * p_buffer,t_size p_count) { + audio_math_shareddll::kill_denormal(p_buffer, p_count); + } + static void add_offset(audio_sample * p_buffer,audio_sample p_delta,t_size p_count) { + audio_math_shareddll::add_offset(p_buffer,p_delta,p_count); + } +}; + +// Anyone trying to talk to audio_math namespace will reach fb2k_audio_math which calls the right thing +#define audio_math fb2k_audio_math diff --git a/SDK/foobar2000/shared/fb2kdebug.h b/SDK/foobar2000/shared/fb2kdebug.h new file mode 100644 index 0000000..d8ebeba --- /dev/null +++ b/SDK/foobar2000/shared/fb2kdebug.h @@ -0,0 +1,105 @@ +extern "C" +{ + LPCSTR SHARED_EXPORT uGetCallStackPath(); + LONG SHARED_EXPORT uExceptFilterProc(LPEXCEPTION_POINTERS param); + PFC_NORETURN void SHARED_EXPORT uBugCheck(); + +#ifdef _DEBUG + void SHARED_EXPORT fb2kDebugSelfTest(); +#endif +} + +class uCallStackTracker +{ + t_size param; +public: + explicit SHARED_EXPORT uCallStackTracker(const char * name); + SHARED_EXPORT ~uCallStackTracker(); +}; + + + +#if 1 +#define TRACK_CALL(X) uCallStackTracker TRACKER__##X(#X) +#define TRACK_CALL_TEXT(X) uCallStackTracker TRACKER__BLAH(X) +#define TRACK_CODE(description,code) {uCallStackTracker __call_tracker(description); code;} +#else +#define TRACK_CALL(X) +#define TRACK_CALL_TEXT(X) +#define TRACK_CODE(description,code) {code;} +#endif + +static int uExceptFilterProc_inline(LPEXCEPTION_POINTERS param) { + uDumpCrashInfo(param); + TerminateProcess(GetCurrentProcess(), 0); + return 0;// never reached +} + + +#define FB2K_DYNAMIC_ASSERT( X ) { if (!(X)) uBugCheck(); } + +#define __except_instacrash __except(uExceptFilterProc(GetExceptionInformation())) +#define fb2k_instacrash_scope(X) __try { X; } __except_instacrash {} + +PFC_NORETURN static void fb2kCriticalError(DWORD code, DWORD argCount = 0, const ULONG_PTR * args = NULL) { + fb2k_instacrash_scope( RaiseException(code,EXCEPTION_NONCONTINUABLE,argCount,args); ); +} +PFC_NORETURN static void fb2kDeadlock() { + fb2kCriticalError(0x63d81b66); +} + +static void fb2kWaitForCompletion(HANDLE hEvent) { + switch(WaitForSingleObject(hEvent, INFINITE)) { + case WAIT_OBJECT_0: + return; + default: + uBugCheck(); + } +} + +static void fb2kWaitForThreadCompletion(HANDLE hWaitFor, DWORD threadID) { + switch(WaitForSingleObject(hWaitFor, INFINITE)) { + case WAIT_OBJECT_0: + return; + default: + uBugCheck(); + } +} + +static void fb2kWaitForThreadCompletion2(HANDLE hWaitFor, HANDLE hThread, DWORD threadID) { + switch(WaitForSingleObject(hWaitFor, INFINITE)) { + case WAIT_OBJECT_0: + return; + default: + uBugCheck(); + } +} + + +static void __cdecl _OverrideCrtAbort_handler(int signal) { + const ULONG_PTR args[] = {signal}; + RaiseException(0x6F8E1DC8 /* random GUID */, EXCEPTION_NONCONTINUABLE, _countof(args), args); +} + +static void __cdecl _PureCallHandler() { + RaiseException(0xf6538887 /* random GUID */, EXCEPTION_NONCONTINUABLE, 0, 0); +} + +static void _InvalidParameter( + const wchar_t * expression, + const wchar_t * function, + const wchar_t * file, + unsigned int line, + uintptr_t pReserved +) { + RaiseException(0xd142b808 /* random GUID */, EXCEPTION_NONCONTINUABLE, 0, 0); +} + +static void OverrideCrtAbort() { + const int signals[] = {SIGINT, SIGTERM, SIGBREAK, SIGABRT}; + for(size_t i=0; i<_countof(signals); i++) signal(signals[i], _OverrideCrtAbort_handler); + _set_abort_behavior(0, ~0); + + _set_purecall_handler(_PureCallHandler); + _set_invalid_parameter_handler(_InvalidParameter); +} diff --git a/SDK/foobar2000/shared/filedialogs.h b/SDK/foobar2000/shared/filedialogs.h new file mode 100644 index 0000000..a5b2be8 --- /dev/null +++ b/SDK/foobar2000/shared/filedialogs.h @@ -0,0 +1,7 @@ +class uGetOpenFileNameMultiResult_impl : public uGetOpenFileNameMultiResult { + pfc::list_t m_data; +public: + void AddItem(pfc::stringp param) {m_data.add_item(param);} + t_size get_count() const {return m_data.get_count();} + void get_item_ex(const char * & out,t_size n) const {out = m_data[n].ptr();} +}; diff --git a/SDK/foobar2000/shared/shared-Win32.lib b/SDK/foobar2000/shared/shared-Win32.lib new file mode 100644 index 0000000..da0ccb0 Binary files /dev/null and b/SDK/foobar2000/shared/shared-Win32.lib differ diff --git a/SDK/foobar2000/shared/shared-x64.lib b/SDK/foobar2000/shared/shared-x64.lib new file mode 100644 index 0000000..ce643a8 Binary files /dev/null and b/SDK/foobar2000/shared/shared-x64.lib differ diff --git a/SDK/foobar2000/shared/shared.h b/SDK/foobar2000/shared/shared.h new file mode 100644 index 0000000..98d5936 --- /dev/null +++ b/SDK/foobar2000/shared/shared.h @@ -0,0 +1,563 @@ +#ifndef _SHARED_DLL__SHARED_H_ +#define _SHARED_DLL__SHARED_H_ + +#include "../../pfc/pfc.h" + +#include + +// Global flag - whether it's OK to leak static objects as they'll be released anyway by process death +#define FB2K_LEAK_STATIC_OBJECTS PFC_LEAK_STATIC_OBJECTS + +#include + +#ifndef WIN32 +#error N/A +#endif + +#ifndef STRICT +#define STRICT +#endif + +#include +#include +#include +#include +//#include +#include + +#ifndef NOTHROW +#ifdef _MSC_VER +#define NOTHROW __declspec(nothrow) +#else +#define NOTHROW +#endif +#endif + +#define SHARED_API /*NOTHROW*/ __stdcall + +#ifndef SHARED_EXPORTS +#define SHARED_EXPORT __declspec(dllimport) SHARED_API +#else +#define SHARED_EXPORT __declspec(dllexport) SHARED_API +#endif + +extern "C" { + +//SHARED_EXPORT BOOL IsUnicode(); +#ifdef UNICODE +#define IsUnicode() 1 +#else +#define IsUnicode() 0 +#endif + +LRESULT SHARED_EXPORT uSendMessageText(HWND wnd,UINT msg,WPARAM wp,const char * text); +LRESULT SHARED_EXPORT uSendDlgItemMessageText(HWND wnd,UINT id,UINT msg,WPARAM wp,const char * text); +BOOL SHARED_EXPORT uGetWindowText(HWND wnd,pfc::string_base & out); +BOOL SHARED_EXPORT uSetWindowText(HWND wnd,const char * p_text); +BOOL SHARED_EXPORT uSetWindowTextEx(HWND wnd,const char * p_text,unsigned p_text_length); +BOOL SHARED_EXPORT uGetDlgItemText(HWND wnd,UINT id,pfc::string_base & out); +BOOL SHARED_EXPORT uSetDlgItemText(HWND wnd,UINT id,const char * p_text); +BOOL SHARED_EXPORT uSetDlgItemTextEx(HWND wnd,UINT id,const char * p_text,unsigned p_text_length); +BOOL SHARED_EXPORT uBrowseForFolder(HWND parent,const char * title,pfc::string_base & out); +BOOL SHARED_EXPORT uBrowseForFolderWithFile(HWND parent,const char * title,pfc::string_base & out,const char * p_file_to_find); +int SHARED_EXPORT uMessageBox(HWND wnd,const char * text,const char * caption,UINT type); +void SHARED_EXPORT uOutputDebugString(const char * msg); +BOOL SHARED_EXPORT uAppendMenu(HMENU menu,UINT flags,UINT_PTR id,const char * content); +BOOL SHARED_EXPORT uInsertMenu(HMENU menu,UINT position,UINT flags,UINT_PTR id,const char * content); +int SHARED_EXPORT uStringCompare(const char * elem1, const char * elem2); +int SHARED_EXPORT uCharCompare(t_uint32 p_char1,t_uint32 p_char2); +int SHARED_EXPORT uStringCompare_ConvertNumbers(const char * elem1,const char * elem2); +HINSTANCE SHARED_EXPORT uLoadLibrary(const char * name); +HANDLE SHARED_EXPORT uCreateEvent(LPSECURITY_ATTRIBUTES lpEventAttributes,BOOL bManualReset,BOOL bInitialState, const char * lpName); +HANDLE SHARED_EXPORT GetInfiniteWaitEvent(); +DWORD SHARED_EXPORT uGetModuleFileName(HMODULE hMod,pfc::string_base & out); +BOOL SHARED_EXPORT uSetClipboardString(const char * ptr); +BOOL SHARED_EXPORT uGetClipboardString(pfc::string_base & out); +BOOL SHARED_EXPORT uSetClipboardRawData(UINT format,const void * ptr,t_size size);//does not empty the clipboard +BOOL SHARED_EXPORT uGetClassName(HWND wnd,pfc::string_base & out); +t_size SHARED_EXPORT uCharLength(const char * src); +BOOL SHARED_EXPORT uDragQueryFile(HDROP hDrop,UINT idx,pfc::string_base & out); +UINT SHARED_EXPORT uDragQueryFileCount(HDROP hDrop); +BOOL SHARED_EXPORT uGetTextExtentPoint32(HDC dc,const char * text,UINT cb,LPSIZE size);//note, cb is number of bytes, not actual unicode characters in the string (read: plain strlen() will do) +BOOL SHARED_EXPORT uExtTextOut(HDC dc,int x,int y,UINT flags,const RECT * rect,const char * text,UINT cb,const int * lpdx); +BOOL SHARED_EXPORT uTextOutColors(HDC dc,const char * src,UINT len,int x,int y,const RECT * clip,BOOL is_selected,DWORD default_color); +BOOL SHARED_EXPORT uTextOutColorsTabbed(HDC dc,const char * src,UINT src_len,const RECT * item,int border,const RECT * clip,BOOL selected,DWORD default_color,BOOL use_columns); +UINT SHARED_EXPORT uGetTextHeight(HDC dc); +UINT SHARED_EXPORT uGetFontHeight(HFONT font); +BOOL SHARED_EXPORT uChooseColor(DWORD * p_color,HWND parent,DWORD * p_custom_colors); +HCURSOR SHARED_EXPORT uLoadCursor(HINSTANCE hIns,const char * name); +HICON SHARED_EXPORT uLoadIcon(HINSTANCE hIns,const char * name); +HMENU SHARED_EXPORT uLoadMenu(HINSTANCE hIns,const char * name); +BOOL SHARED_EXPORT uGetEnvironmentVariable(const char * name,pfc::string_base & out); +HMODULE SHARED_EXPORT uGetModuleHandle(const char * name); +UINT SHARED_EXPORT uRegisterWindowMessage(const char * name); +BOOL SHARED_EXPORT uMoveFile(const char * src,const char * dst); +BOOL SHARED_EXPORT uDeleteFile(const char * fn); +DWORD SHARED_EXPORT uGetFileAttributes(const char * fn); +BOOL SHARED_EXPORT uFileExists(const char * fn); +BOOL SHARED_EXPORT uRemoveDirectory(const char * fn); +HANDLE SHARED_EXPORT uCreateFile(const char * p_path,DWORD p_access,DWORD p_sharemode,LPSECURITY_ATTRIBUTES p_security_attributes,DWORD p_createmode,DWORD p_flags,HANDLE p_template); +HANDLE SHARED_EXPORT uCreateFileMapping(HANDLE hFile,LPSECURITY_ATTRIBUTES lpFileMappingAttributes,DWORD flProtect,DWORD dwMaximumSizeHigh,DWORD dwMaximumSizeLow,const char * lpName); +BOOL SHARED_EXPORT uCreateDirectory(const char * fn,LPSECURITY_ATTRIBUTES blah); +HANDLE SHARED_EXPORT uCreateMutex(LPSECURITY_ATTRIBUTES blah,BOOL bInitialOwner,const char * name); +BOOL SHARED_EXPORT uGetLongPathName(const char * name,pfc::string_base & out);//may just fail to work on old windows versions, present on win98/win2k+ +BOOL SHARED_EXPORT uGetFullPathName(const char * name,pfc::string_base & out); +BOOL SHARED_EXPORT uSearchPath(const char * path, const char * filename, const char * extension, pfc::string_base & p_out); +BOOL SHARED_EXPORT uFixPathCaps(const char * path,pfc::string_base & p_out); +//BOOL SHARED_EXPORT uFixPathCapsQuick(const char * path,pfc::string_base & p_out); +void SHARED_EXPORT uGetCommandLine(pfc::string_base & out); +BOOL SHARED_EXPORT uGetTempPath(pfc::string_base & out); +BOOL SHARED_EXPORT uGetTempFileName(const char * path_name,const char * prefix,UINT unique,pfc::string_base & out); +BOOL SHARED_EXPORT uGetOpenFileName(HWND parent,const char * p_ext_mask,unsigned def_ext_mask,const char * p_def_ext,const char * p_title,const char * p_directory,pfc::string_base & p_filename,BOOL b_save); +//note: uGetOpenFileName extension mask uses | as separator, not null +HANDLE SHARED_EXPORT uLoadImage(HINSTANCE hIns,const char * name,UINT type,int x,int y,UINT flags); +UINT SHARED_EXPORT uRegisterClipboardFormat(const char * name); +BOOL SHARED_EXPORT uGetClipboardFormatName(UINT format,pfc::string_base & out); +BOOL SHARED_EXPORT uFormatSystemErrorMessage(pfc::string_base & p_out,DWORD p_code); + +HANDLE SHARED_EXPORT uSortStringCreate(const char * src); +int SHARED_EXPORT uSortStringCompare(HANDLE string1,HANDLE string2); +int SHARED_EXPORT uSortStringCompareEx(HANDLE string1,HANDLE string2,DWORD flags);//flags - see win32 CompareString +int SHARED_EXPORT uSortPathCompare(HANDLE string1,HANDLE string2); +void SHARED_EXPORT uSortStringFree(HANDLE string); + +// New in 1.1.12 +HANDLE SHARED_EXPORT CreateFileAbortable( __in LPCWSTR lpFileName, + __in DWORD dwDesiredAccess, + __in DWORD dwShareMode, + __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes, + __in DWORD dwCreationDisposition, + __in DWORD dwFlagsAndAttributes, + // Template file handle NOT supported. + __in_opt HANDLE hAborter + ); + + +int SHARED_EXPORT uCompareString(DWORD flags,const char * str1,unsigned len1,const char * str2,unsigned len2); + +class NOVTABLE uGetOpenFileNameMultiResult : public pfc::list_base_const_t +{ +public: + inline t_size GetCount() {return get_count();} + inline const char * GetFileName(t_size index) {return get_item(index);} + virtual ~uGetOpenFileNameMultiResult() {} +}; + +typedef uGetOpenFileNameMultiResult * puGetOpenFileNameMultiResult; + +puGetOpenFileNameMultiResult SHARED_EXPORT uGetOpenFileNameMulti(HWND parent,const char * p_ext_mask,unsigned def_ext_mask,const char * p_def_ext,const char * p_title,const char * p_directory); + +// new in fb2k 1.1.1 +puGetOpenFileNameMultiResult SHARED_EXPORT uBrowseForFolderEx(HWND parent,const char * title, const char * initPath); +puGetOpenFileNameMultiResult SHARED_EXPORT uEvalKnownFolder(const GUID& id); + + +class NOVTABLE uFindFile +{ +protected: + uFindFile() {} +public: + virtual BOOL FindNext()=0; + virtual const char * GetFileName()=0; + virtual t_uint64 GetFileSize()=0; + virtual DWORD GetAttributes()=0; + virtual FILETIME GetCreationTime()=0; + virtual FILETIME GetLastAccessTime()=0; + virtual FILETIME GetLastWriteTime()=0; + virtual ~uFindFile() {}; + inline bool IsDirectory() {return (GetAttributes() & FILE_ATTRIBUTE_DIRECTORY) ? true : false;} +}; + +typedef uFindFile * puFindFile; + +puFindFile SHARED_EXPORT uFindFirstFile(const char * path); + +HINSTANCE SHARED_EXPORT uShellExecute(HWND wnd,const char * oper,const char * file,const char * params,const char * dir,int cmd); +HWND SHARED_EXPORT uCreateStatusWindow(LONG style,const char * text,HWND parent,UINT id); + +BOOL SHARED_EXPORT uShellNotifyIcon(DWORD dwMessage,HWND wnd,UINT id,UINT callbackmsg,HICON icon,const char * tip); +BOOL SHARED_EXPORT uShellNotifyIconEx(DWORD dwMessage,HWND wnd,UINT id,UINT callbackmsg,HICON icon,const char * tip,const char * balloon_title,const char * balloon_msg); + +HWND SHARED_EXPORT uCreateWindowEx(DWORD dwExStyle,const char * lpClassName,const char * lpWindowName,DWORD dwStyle,int x,int y,int nWidth,int nHeight,HWND hWndParent,HMENU hMenu,HINSTANCE hInstance,LPVOID lpParam); + +BOOL SHARED_EXPORT uGetSystemDirectory(pfc::string_base & out); +BOOL SHARED_EXPORT uGetWindowsDirectory(pfc::string_base & out); +BOOL SHARED_EXPORT uSetCurrentDirectory(const char * path); +BOOL SHARED_EXPORT uGetCurrentDirectory(pfc::string_base & out); +BOOL SHARED_EXPORT uExpandEnvironmentStrings(const char * src,pfc::string_base & out); +BOOL SHARED_EXPORT uGetUserName(pfc::string_base & out); +BOOL SHARED_EXPORT uGetShortPathName(const char * src,pfc::string_base & out); + +HSZ SHARED_EXPORT uDdeCreateStringHandle(DWORD ins,const char * src); +BOOL SHARED_EXPORT uDdeQueryString(DWORD ins,HSZ hsz,pfc::string_base & out); +UINT SHARED_EXPORT uDdeInitialize(LPDWORD pidInst,PFNCALLBACK pfnCallback,DWORD afCmd,DWORD ulRes); +BOOL SHARED_EXPORT uDdeAccessData_Text(HDDEDATA data,pfc::string_base & out); + +HIMAGELIST SHARED_EXPORT uImageList_LoadImage(HINSTANCE hi, const char * lpbmp, int cx, int cGrow, COLORREF crMask, UINT uType, UINT uFlags); + +#define uDdeFreeStringHandle DdeFreeStringHandle +#define uDdeCmpStringHandles DdeCmpStringHandles +#define uDdeKeepStringHandle DdeKeepStringHandle +#define uDdeUninitialize DdeUninitialize +#define uDdeNameService DdeNameService +#define uDdeFreeDataHandle DdeFreeDataHandle + + +typedef TVINSERTSTRUCTA uTVINSERTSTRUCT; + +HTREEITEM SHARED_EXPORT uTreeView_InsertItem(HWND wnd,const uTVINSERTSTRUCT * param); +LPARAM SHARED_EXPORT uTreeView_GetUserData(HWND wnd,HTREEITEM item); +bool SHARED_EXPORT uTreeView_GetText(HWND wnd,HTREEITEM item,pfc::string_base & out); + +#define uSetWindowsHookEx SetWindowsHookEx +#define uUnhookWindowsHookEx UnhookWindowsHookEx +#define uCallNextHookEx CallNextHookEx + +typedef TCITEMA uTCITEM; +int SHARED_EXPORT uTabCtrl_InsertItem(HWND wnd,t_size idx,const uTCITEM * item); +int SHARED_EXPORT uTabCtrl_SetItem(HWND wnd,t_size idx,const uTCITEM * item); + +int SHARED_EXPORT uGetKeyNameText(LONG lparam,pfc::string_base & out); + +void SHARED_EXPORT uFixAmpersandChars(const char * src,pfc::string_base & out);//for notification area icon +void SHARED_EXPORT uFixAmpersandChars_v2(const char * src,pfc::string_base & out);//for other controls + +//deprecated +t_size SHARED_EXPORT uPrintCrashInfo(LPEXCEPTION_POINTERS param,const char * extrainfo,char * out); +enum {uPrintCrashInfo_max_length = 1024}; + +void SHARED_EXPORT uPrintCrashInfo_Init(const char * name);//called only by the exe on startup +void SHARED_EXPORT uPrintCrashInfo_SetComponentList(const char * p_info);//called only by the exe on startup +void SHARED_EXPORT uPrintCrashInfo_AddEnvironmentInfo(const char * p_info);//called only by the exe on startup +void SHARED_EXPORT uPrintCrashInfo_SetDumpPath(const char * name);//called only by the exe on startup + +void SHARED_EXPORT uDumpCrashInfo(LPEXCEPTION_POINTERS param); + + + +void SHARED_EXPORT uPrintCrashInfo_OnEvent(const char * message, t_size length); + +BOOL SHARED_EXPORT uListBox_GetText(HWND listbox,UINT index,pfc::string_base & out); + +void SHARED_EXPORT uPrintfV(pfc::string_base & out,const char * fmt,va_list arglist); +static inline void uPrintf(pfc::string_base & out,const char * fmt,...) {va_list list;va_start(list,fmt);uPrintfV(out,fmt,list);va_end(list);} + + +class NOVTABLE uResource +{ +public: + virtual const void * GetPointer() = 0; + virtual unsigned GetSize() = 0; + virtual ~uResource() {} +}; + +typedef uResource* puResource; + +puResource SHARED_EXPORT uLoadResource(HMODULE hMod,const char * name,const char * type,WORD wLang = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) ); +puResource SHARED_EXPORT LoadResourceEx(HMODULE hMod,const TCHAR * name,const TCHAR * type,WORD wLang = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) ); +HRSRC SHARED_EXPORT uFindResource(HMODULE hMod,const char * name,const char * type,WORD wLang = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) ); + +BOOL SHARED_EXPORT uLoadString(HINSTANCE ins,UINT id,pfc::string_base & out); + +UINT SHARED_EXPORT uCharLower(UINT c); +UINT SHARED_EXPORT uCharUpper(UINT c); + +BOOL SHARED_EXPORT uGetMenuString(HMENU menu,UINT id,pfc::string_base & out,UINT flag); +BOOL SHARED_EXPORT uModifyMenu(HMENU menu,UINT id,UINT flags,UINT newitem,const char * data); +UINT SHARED_EXPORT uGetMenuItemType(HMENU menu,UINT position); + + +// New in 1.3.4 +// Load a system library safely - forcibly look in system directories, not elsewhere. +HMODULE SHARED_EXPORT LoadSystemLibrary(const TCHAR * name); +}//extern "C" + +static inline void uAddDebugEvent(const char * msg) {uPrintCrashInfo_OnEvent(msg, strlen(msg));} +static inline void uAddDebugEvent(pfc::string_formatter const & msg) {uPrintCrashInfo_OnEvent(msg, msg.length());} + +inline char * uCharNext(char * src) {return src+uCharLength(src);} +inline const char * uCharNext(const char * src) {return src+uCharLength(src);} + + +class string_utf8_from_window +{ +public: + string_utf8_from_window(HWND wnd) + { + uGetWindowText(wnd,m_data); + } + string_utf8_from_window(HWND wnd,UINT id) + { + uGetDlgItemText(wnd,id,m_data); + } + inline operator const char * () const {return m_data.get_ptr();} + inline t_size length() const {return m_data.length();} + inline bool is_empty() const {return length() == 0;} + inline const char * get_ptr() const {return m_data.get_ptr();} +private: + pfc::string8 m_data; +}; + +static pfc::string uGetWindowText(HWND wnd) { + pfc::string8 temp; + if (!uGetWindowText(wnd,temp)) return ""; + return temp.toString(); +} +static pfc::string uGetDlgItemText(HWND wnd,UINT id) { + pfc::string8 temp; + if (!uGetDlgItemText(wnd,id,temp)) return ""; + return temp.toString(); +} + +#define uMAKEINTRESOURCE(x) ((const char*)LOWORD(x)) + +//other + +#define uIsDialogMessage IsDialogMessage +#define uGetMessage GetMessage +#define uPeekMessage PeekMessage +#define uDispatchMessage DispatchMessage + +#define uCallWindowProc CallWindowProc +#define uDefWindowProc DefWindowProc +#define uGetWindowLong GetWindowLong +#define uSetWindowLong SetWindowLong + +#define uEndDialog EndDialog +#define uDestroyWindow DestroyWindow +#define uGetDlgItem GetDlgItem +#define uEnableWindow EnableWindow +#define uGetDlgItemInt GetDlgItemInt +#define uSetDlgItemInt SetDlgItemInt + +#define uSendMessage SendMessage +#define uSendDlgItemMessage SendDlgItemMessage +#define uSendMessageTimeout SendMessageTimeout +#define uSendNotifyMessage SendNotifyMessage +#define uSendMessageCallback SendMessageCallback +#define uPostMessage PostMessage +#define uPostThreadMessage PostThreadMessage + + +class uStringPrintf +{ +public: + inline explicit uStringPrintf(const char * fmt,...) + { + va_list list; + va_start(list,fmt); + uPrintfV(m_data,fmt,list); + va_end(list); + } + inline operator const char * () const {return m_data.get_ptr();} + inline t_size length() const {return m_data.length();} + inline bool is_empty() const {return length() == 0;} + inline const char * get_ptr() const {return m_data.get_ptr();} + const char * toString() const {return get_ptr();} +private: + pfc::string8_fastalloc m_data; +}; +#pragma deprecated(uStringPrintf, uPrintf, uPrintfV) + +inline LRESULT uButton_SetCheck(HWND wnd,UINT id,bool state) {return uSendDlgItemMessage(wnd,id,BM_SETCHECK,state ? BST_CHECKED : BST_UNCHECKED,0); } +inline bool uButton_GetCheck(HWND wnd,UINT id) {return uSendDlgItemMessage(wnd,id,BM_GETCHECK,0,0) == BST_CHECKED;} + + + +extern "C" { +int SHARED_EXPORT stricmp_utf8(const char * p1,const char * p2) throw(); +int SHARED_EXPORT stricmp_utf8_ex(const char * p1,t_size len1,const char * p2,t_size len2) throw(); +int SHARED_EXPORT stricmp_utf8_stringtoblock(const char * p1,const char * p2,t_size p2_bytes) throw(); +int SHARED_EXPORT stricmp_utf8_partial(const char * p1,const char * p2,t_size num = ~0) throw(); +int SHARED_EXPORT stricmp_utf8_max(const char * p1,const char * p2,t_size p1_bytes) throw(); +t_size SHARED_EXPORT uReplaceStringAdd(pfc::string_base & out,const char * src,t_size src_len,const char * s1,t_size len1,const char * s2,t_size len2,bool casesens); +t_size SHARED_EXPORT uReplaceCharAdd(pfc::string_base & out,const char * src,t_size src_len,unsigned c1,unsigned c2,bool casesens); +//all lengths in uReplaceString functions are optional, set to -1 if parameters is a simple null-terminated string +void SHARED_EXPORT uAddStringLower(pfc::string_base & out,const char * src,t_size len = ~0); +void SHARED_EXPORT uAddStringUpper(pfc::string_base & out,const char * src,t_size len = ~0); +} + +class comparator_stricmp_utf8 { +public: + static int compare(const char * p_string1,const char * p_string2) throw() {return stricmp_utf8(p_string1,p_string2);} +}; + +inline void uStringLower(pfc::string_base & out,const char * src,t_size len = ~0) {out.reset();uAddStringLower(out,src,len);} +inline void uStringUpper(pfc::string_base & out,const char * src,t_size len = ~0) {out.reset();uAddStringUpper(out,src,len);} + +inline t_size uReplaceString(pfc::string_base & out,const char * src,t_size src_len,const char * s1,t_size len1,const char * s2,t_size len2,bool casesens) +{ + out.reset(); + return uReplaceStringAdd(out,src,src_len,s1,len1,s2,len2,casesens); +} + +inline t_size uReplaceChar(pfc::string_base & out,const char * src,t_size src_len,unsigned c1,unsigned c2,bool casesens) +{ + out.reset(); + return uReplaceCharAdd(out,src,src_len,c1,c2,casesens); +} + +class string_lower +{ +public: + explicit string_lower(const char * ptr,t_size p_count = ~0) {uAddStringLower(m_data,ptr,p_count);} + inline operator const char * () const {return m_data.get_ptr();} + inline t_size length() const {return m_data.length();} + inline bool is_empty() const {return length() == 0;} + inline const char * get_ptr() const {return m_data.get_ptr();} +private: + pfc::string8 m_data; +}; + +class string_upper +{ +public: + explicit string_upper(const char * ptr,t_size p_count = ~0) {uAddStringUpper(m_data,ptr,p_count);} + inline operator const char * () const {return m_data.get_ptr();} + inline t_size length() const {return m_data.length();} + inline bool is_empty() const {return length() == 0;} + inline const char * get_ptr() const {return m_data.get_ptr();} +private: + pfc::string8 m_data; +}; + + +inline BOOL uGetLongPathNameEx(const char * name,pfc::string_base & out) +{ + if (uGetLongPathName(name,out)) return TRUE; + return uGetFullPathName(name,out); +} + +struct t_font_description +{ + enum + { + m_facename_length = LF_FACESIZE*2, + m_height_dpi = 480, + }; + + t_uint32 m_height; + t_uint32 m_weight; + t_uint8 m_italic; + t_uint8 m_charset; + char m_facename[m_facename_length]; + + bool operator==(const t_font_description & other) const {return g_equals(*this, other);} + bool operator!=(const t_font_description & other) const {return !g_equals(*this, other);} + + static bool g_equals(const t_font_description & v1, const t_font_description & v2) { + return v1.m_height == v2.m_height && v1.m_weight == v2.m_weight && v1.m_italic == v2.m_italic && v1.m_charset == v2.m_charset && pfc::strcmp_ex(v1.m_facename, m_facename_length, v2.m_facename, m_facename_length) == 0; + } + + HFONT SHARED_EXPORT create() const; + bool SHARED_EXPORT popup_dialog(HWND p_parent); + void SHARED_EXPORT from_font(HFONT p_font); + static t_font_description SHARED_EXPORT g_from_font(HFONT p_font); + static t_font_description SHARED_EXPORT g_from_logfont(LOGFONT const & lf); + static t_font_description SHARED_EXPORT g_from_system(int id = TMT_MENUFONT); + + template void to_stream(t_stream p_stream,t_abort & p_abort) const; + template void from_stream(t_stream p_stream,t_abort & p_abort); +}; + +/* relevant types not yet defined here */ template void t_font_description::to_stream(t_stream p_stream,t_abort & p_abort) const { + p_stream->write_lendian_t(m_height,p_abort); + p_stream->write_lendian_t(m_weight,p_abort); + p_stream->write_lendian_t(m_italic,p_abort); + p_stream->write_lendian_t(m_charset,p_abort); + p_stream->write_string(m_facename,PFC_TABSIZE(m_facename),p_abort); +} + +/* relevant types not yet defined here */ template void t_font_description::from_stream(t_stream p_stream,t_abort & p_abort) { + p_stream->read_lendian_t(m_height,p_abort); + p_stream->read_lendian_t(m_weight,p_abort); + p_stream->read_lendian_t(m_italic,p_abort); + p_stream->read_lendian_t(m_charset,p_abort); + pfc::string8 temp; + p_stream->read_string(temp,p_abort); + strncpy_s(m_facename,temp,PFC_TABSIZE(m_facename)); +} + + +struct t_modal_dialog_entry +{ + HWND m_wnd_to_poke; + bool m_in_use; +}; + +extern "C" { + void SHARED_EXPORT ModalDialog_Switch(t_modal_dialog_entry & p_entry); + void SHARED_EXPORT ModalDialog_PokeExisting(); + bool SHARED_EXPORT ModalDialog_CanCreateNew(); + + HWND SHARED_EXPORT FindOwningPopup(HWND p_wnd); + void SHARED_EXPORT PokeWindow(HWND p_wnd); +}; + +static bool ModalDialogPrologue() { + bool rv = ModalDialog_CanCreateNew(); + if (!rv) ModalDialog_PokeExisting(); + return rv; +} + +//! The purpose of modal_dialog_scope is to help to avoid the modal dialog recursion problem. Current toplevel modal dialog handle is stored globally, so when creation of a new modal dialog is blocked, it can be activated to indicate the reason for the task being blocked. +class modal_dialog_scope { +public: + //! This constructor initializes the modal dialog scope with specified dialog handle. + inline modal_dialog_scope(HWND p_wnd) throw() : m_initialized(false) {initialize(p_wnd);} + //! This constructor leaves the scope uninitialized (you can call initialize() later with your window handle). + inline modal_dialog_scope() throw() : m_initialized(false) {} + inline ~modal_dialog_scope() throw() {deinitialize();} + + //! Returns whether creation of a new modal dialog is allowed (false when there's another one active).\n + //! NOTE: when calling context is already inside a modal dialog that you own, you should not be checking this before creating a new modal dialog. + inline static bool can_create() throw(){return ModalDialog_CanCreateNew();} + //! Activates the top-level modal dialog existing, if one exists. + inline static void poke_existing() throw() {ModalDialog_PokeExisting();} + + //! Initializes the scope with specified window handle. + void initialize(HWND p_wnd) throw() + { + if (!m_initialized) + { + m_initialized = true; + m_entry.m_in_use = true; + m_entry.m_wnd_to_poke = p_wnd; + ModalDialog_Switch(m_entry); + } + } + + void deinitialize() throw() + { + if (m_initialized) + { + ModalDialog_Switch(m_entry); + m_initialized = false; + } + } + + + +private: + modal_dialog_scope(const modal_dialog_scope & p_scope) {assert(0);} + const modal_dialog_scope & operator=(const modal_dialog_scope &) {assert(0); return *this;} + + t_modal_dialog_entry m_entry; + + bool m_initialized; +}; + + + +#include "audio_math.h" +#include "win32_misc.h" + +#include "fb2kdebug.h" + +#if FB2K_LEAK_STATIC_OBJECTS +#define FB2K_STATIC_OBJECT(TYPE, NAME) static TYPE & NAME = * new TYPE; +#else +#define FB2K_STATIC_OBJECT(TYPE, NAME) static TYPE NAME; +#endif + +#endif //_SHARED_DLL__SHARED_H_ diff --git a/SDK/foobar2000/shared/win32_misc.h b/SDK/foobar2000/shared/win32_misc.h new file mode 100644 index 0000000..6d5f0b3 --- /dev/null +++ b/SDK/foobar2000/shared/win32_misc.h @@ -0,0 +1,38 @@ +class uDebugLog : public pfc::string_formatter { +public: + ~uDebugLog() {*this << "\n"; uOutputDebugString(get_ptr());} +}; + +#define FB2K_DebugLog() uDebugLog()._formatter() + + +class win32_font { +public: + win32_font(HFONT p_initval) : m_font(p_initval) {} + win32_font() : m_font(NULL) {} + ~win32_font() {release();} + + void release() { + HFONT temp = detach(); + if (temp != NULL) DeleteObject(temp); + } + + void set(HFONT p_font) {release(); m_font = p_font;} + HFONT get() const {return m_font;} + HFONT detach() {return pfc::replace_t(m_font,(HFONT)NULL);} + + void create(const t_font_description & p_desc) { + SetLastError(NO_ERROR); + HFONT temp = p_desc.create(); + if (temp == NULL) throw exception_win32(GetLastError()); + set(temp); + } + + bool is_valid() const {return m_font != NULL;} + +private: + win32_font(const win32_font&); + const win32_font & operator=(const win32_font &); + + HFONT m_font; +}; diff --git a/SDK/pfc/Android.mk b/SDK/pfc/Android.mk new file mode 100644 index 0000000..4303088 --- /dev/null +++ b/SDK/pfc/Android.mk @@ -0,0 +1,15 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := pfc + +LOCAL_ARM_MODE := arm + +LOCAL_SRC_FILES := audio_math.cpp audio_sample.cpp base64.cpp bit_array.cpp bsearch.cpp cpuid.cpp filehandle.cpp guid.cpp nix-objects.cpp other.cpp pathUtils.cpp printf.cpp selftest.cpp sort.cpp stdafx.cpp stringNew.cpp string_base.cpp string_conv.cpp synchro_nix.cpp threads.cpp timers.cpp utf8.cpp wildcard.cpp win-objects.cpp + +LOCAL_STATIC_LIBRARIES := cpufeatures + +include $(BUILD_SHARED_LIBRARY) + +$(call import-module,android/cpufeatures) diff --git a/SDK/pfc/alloc.h b/SDK/pfc/alloc.h new file mode 100644 index 0000000..c49ab52 --- /dev/null +++ b/SDK/pfc/alloc.h @@ -0,0 +1,537 @@ +namespace pfc { + + static void * raw_malloc(t_size p_size) { + return p_size > 0 ? new_ptr_check_t(malloc(p_size)) : NULL; + } + + static void raw_free(void * p_block) throw() {free(p_block);} + + static void* raw_realloc(void * p_ptr,t_size p_size) { + if (p_size == 0) {raw_free(p_ptr); return NULL;} + else if (p_ptr == NULL) return raw_malloc(p_size); + else return pfc::new_ptr_check_t(::realloc(p_ptr,p_size)); + } + + static bool raw_realloc_inplace(void * p_block,t_size p_size) throw() { + if (p_block == NULL) return p_size == 0; +#ifdef _MSC_VER + if (p_size == 0) return false; + return _expand(p_block,p_size) != NULL; +#else + return false; +#endif + } + + template + t_size calc_array_width(t_size p_width) { + return pfc::mul_safe_t(p_width,sizeof(T)); + } + + template + T * __raw_malloc_t(t_size p_size) { + return reinterpret_cast(raw_malloc(calc_array_width(p_size))); + } + + template + void __raw_free_t(T * p_block) throw() { + raw_free(reinterpret_cast(p_block)); + } + + template + T * __raw_realloc_t(T * p_block,t_size p_size) { + return reinterpret_cast(raw_realloc(p_block,calc_array_width(p_size))); + } + + template + bool __raw_realloc_inplace_t(T * p_block,t_size p_size) { + return raw_realloc_inplace(p_block,calc_array_width(p_size)); + } + + + template + inline t_int safe_shift_left_t(t_int p_val,t_size p_shift = 1) { + t_int newval = p_val << p_shift; + if (newval >> p_shift != p_val) throw t_exception(); + return newval; + } + + template class alloc_dummy { + private: typedef alloc_dummy t_self; + public: + alloc_dummy() {} + void set_size(t_size p_size) {throw pfc::exception_not_implemented();} + t_size get_size() const {throw pfc::exception_not_implemented();} + const t_item & operator[](t_size p_index) const {throw pfc::exception_not_implemented();} + t_item & operator[](t_size p_index) {throw pfc::exception_not_implemented();} + + bool is_ptr_owned(const void * p_item) const {return false;} + + //set to true when we prioritize speed over memory usage + enum { alloc_prioritizes_speed = false }; + + //not mandatory + const t_item * get_ptr() const {throw pfc::exception_not_implemented();} + t_item * get_ptr() {throw pfc::exception_not_implemented();} + void prealloc(t_size) {throw pfc::exception_not_implemented();} + void force_reset() {throw pfc::exception_not_implemented();} + void move_from(t_self &) {throw pfc::exception_not_implemented();} + private: + const t_self & operator=(const t_self &) {throw pfc::exception_not_implemented();} + alloc_dummy(const t_self&) {throw pfc::exception_not_implemented();} + }; + + template + bool is_pointer_in_range(const t_item * p_buffer,t_size p_buffer_size,const void * p_pointer) { + return p_pointer >= reinterpret_cast(p_buffer) && p_pointer < reinterpret_cast(p_buffer + p_buffer_size); + } + + + //! Simple inefficient fully portable allocator. + template class alloc_simple { + private: typedef alloc_simple t_self; + public: + alloc_simple() : m_data(NULL), m_size(0) {} + void set_size(t_size p_size) { + if (p_size != m_size) { + t_item * l_data = NULL; + if (p_size > 0) l_data = new t_item[p_size]; + try { + pfc::memcpy_t(l_data,m_data,pfc::min_t(m_size,p_size)); + } catch(...) { + delete[] l_data; + throw; + } + delete[] m_data; + m_data = l_data; + m_size = p_size; + } + } + t_size get_size() const {return m_size;} + const t_item & operator[](t_size p_index) const {PFC_ASSERT(p_index < m_size); return m_data[p_index];} + t_item & operator[](t_size p_index) {PFC_ASSERT(p_index < m_size); return m_data[p_index];} + bool is_ptr_owned(const void * p_item) const {return is_pointer_in_range(get_ptr(),get_size(),p_item);} + + enum { alloc_prioritizes_speed = false }; + + t_item * get_ptr() {return m_data;} + const t_item * get_ptr() const {return m_data;} + + void prealloc(t_size) {} + void force_reset() {set_size(0);} + + ~alloc_simple() {delete[] m_data;} + + void move_from(t_self & other) { + delete[] m_data; + m_data = replace_null_t(other.m_data); + m_size = replace_null_t(other.m_size); + } + private: + const t_self & operator=(const t_self &) {throw pfc::exception_not_implemented();} + alloc_simple(const t_self&) {throw pfc::exception_not_implemented();} + + t_item * m_data; + t_size m_size; + }; + + template class __array_fast_helper_t { + private: + typedef __array_fast_helper_t t_self; + public: + __array_fast_helper_t() : m_buffer(NULL), m_size(0), m_size_total(0) {} + + + void set_size(t_size p_size,t_size p_size_total) { + PFC_ASSERT(p_size <= p_size_total); + PFC_ASSERT(m_size <= m_size_total); + if (p_size_total > m_size_total) { + resize_storage(p_size_total); + resize_content(p_size); + } else { + resize_content(p_size); + resize_storage(p_size_total); + } + } + + + + t_size get_size() const {return m_size;} + t_size get_size_total() const {return m_size_total;} + const t_item & operator[](t_size p_index) const {PFC_ASSERT(p_index < m_size); return m_buffer[p_index];} + t_item & operator[](t_size p_index) {PFC_ASSERT(p_index < m_size); return m_buffer[p_index];} + ~__array_fast_helper_t() { + set_size(0,0); + } + t_item * get_ptr() {return m_buffer;} + const t_item * get_ptr() const {return m_buffer;} + bool is_ptr_owned(const void * p_item) const {return is_pointer_in_range(m_buffer,m_size_total,p_item);} + + void move_from(t_self & other) { + set_size(0,0); + m_buffer = replace_null_t(other.m_buffer); + m_size = replace_null_t(other.m_size); + m_size_total = replace_null_t(other.m_size_total); + } + private: + const t_self & operator=(const t_self &) {throw pfc::exception_not_implemented();} + __array_fast_helper_t(const t_self &) {throw pfc::exception_not_implemented();} + + + void resize_content(t_size p_size) { + if (traits_t::needs_constructor || traits_t::needs_destructor) { + if (p_size > m_size) {//expand + do { + __unsafe__in_place_constructor_t(m_buffer[m_size]); + m_size++; + } while(m_size < p_size); + } else if (p_size < m_size) { + __unsafe__in_place_destructor_array_t(m_buffer + p_size, m_size - p_size); + m_size = p_size; + } + } else { + m_size = p_size; + } + } + + void resize_storage(t_size p_size) { + PFC_ASSERT( m_size <= m_size_total ); + PFC_ASSERT( m_size <= p_size ); + if (m_size_total != p_size) { + if (pfc::traits_t::realloc_safe) { + m_buffer = pfc::__raw_realloc_t(m_buffer,p_size); + m_size_total = p_size; + } else if (__raw_realloc_inplace_t(m_buffer,p_size)) { + //success + m_size_total = p_size; + } else { + t_item * newbuffer = pfc::__raw_malloc_t(p_size); + try { + pfc::__unsafe__in_place_constructor_array_copy_t(newbuffer,m_size,m_buffer); + } catch(...) { + pfc::__raw_free_t(newbuffer); + throw; + } + pfc::__unsafe__in_place_destructor_array_t(m_buffer,m_size); + pfc::__raw_free_t(m_buffer); + m_buffer = newbuffer; + m_size_total = p_size; + } + } + } + + t_item * m_buffer; + t_size m_size,m_size_total; + }; + + template class __array_lite_helper_t { + private: + typedef __array_lite_helper_t t_self; + public: + __array_lite_helper_t() : m_buffer(NULL), m_size(0) {} + + + void set_size(t_size p_size) { + if (p_size > m_size) { // expand + resize_storage(p_size); + resize_content(p_size); + } else if (p_size < m_size) { // shrink + resize_content(p_size); + resize_storage(p_size); + } + } + + + + t_size get_size() const {return m_size;} + const t_item & operator[](t_size p_index) const {PFC_ASSERT(p_index < m_size); return m_buffer[p_index];} + t_item & operator[](t_size p_index) {PFC_ASSERT(p_index < m_size); return m_buffer[p_index];} + ~__array_lite_helper_t() { + set_size(0); + } + t_item * get_ptr() {return m_buffer;} + const t_item * get_ptr() const {return m_buffer;} + bool is_ptr_owned(const void * p_item) const {return is_pointer_in_range(m_buffer,m_size,p_item);} + + void move_from(t_self & other) { + set_size(0); + m_buffer = replace_null_t(other.m_buffer); + m_size = replace_null_t(other.m_size); + } + private: + const t_self & operator=(const t_self &) {throw pfc::exception_not_implemented();} + __array_lite_helper_t(const t_self &) {throw pfc::exception_not_implemented();} + + + void resize_content(t_size p_size) { + if (traits_t::needs_constructor || traits_t::needs_destructor) { + if (p_size > m_size) {//expand + do { + __unsafe__in_place_constructor_t(m_buffer[m_size]); + m_size++; + } while(m_size < p_size); + } else if (p_size < m_size) { + __unsafe__in_place_destructor_array_t(m_buffer + p_size, m_size - p_size); + m_size = p_size; + } + } else { + m_size = p_size; + } + } + + void resize_storage(t_size p_size) { + PFC_ASSERT( m_size <= p_size ); + if (pfc::traits_t::realloc_safe) { + m_buffer = pfc::__raw_realloc_t(m_buffer,p_size); + //m_size_total = p_size; + } else if (__raw_realloc_inplace_t(m_buffer,p_size)) { + //success + //m_size_total = p_size; + } else { + t_item * newbuffer = pfc::__raw_malloc_t(p_size); + try { + pfc::__unsafe__in_place_constructor_array_copy_t(newbuffer,m_size,m_buffer); + } catch(...) { + pfc::__raw_free_t(newbuffer); + throw; + } + pfc::__unsafe__in_place_destructor_array_t(m_buffer,m_size); + pfc::__raw_free_t(m_buffer); + m_buffer = newbuffer; + //m_size_total = p_size; + } + } + + t_item * m_buffer; + t_size m_size; + }; + + template class alloc_standard { + private: typedef alloc_standard t_self; + public: + alloc_standard() {} + void set_size(t_size p_size) {m_content.set_size(p_size);} + + t_size get_size() const {return m_content.get_size();} + + const t_item & operator[](t_size p_index) const {return m_content[p_index];} + t_item & operator[](t_size p_index) {return m_content[p_index];} + + const t_item * get_ptr() const {return m_content.get_ptr();} + t_item * get_ptr() {return m_content.get_ptr();} + + bool is_ptr_owned(const void * p_item) const {return m_content.is_ptr_owned(p_item);} + void prealloc(t_size p_size) {} + void force_reset() {set_size(0);} + + enum { alloc_prioritizes_speed = false }; + + void move_from(t_self & other) { m_content.move_from(other.m_content); } + private: + alloc_standard(const t_self &) {throw pfc::exception_not_implemented();} + const t_self & operator=(const t_self&) {throw pfc::exception_not_implemented();} + + __array_lite_helper_t m_content; + }; + + template class alloc_fast { + private: typedef alloc_fast t_self; + public: + alloc_fast() {} + + void set_size(t_size p_size) { + t_size size_base = m_data.get_size_total(); + if (size_base == 0) size_base = 1; + while(size_base < p_size) { + size_base = safe_shift_left_t(size_base,1); + } + while(size_base >> 2 > p_size) { + size_base >>= 1; + } + m_data.set_size(p_size,size_base); + } + + t_size get_size() const {return m_data.get_size();} + const t_item & operator[](t_size p_index) const {return m_data[p_index];} + t_item & operator[](t_size p_index) {return m_data[p_index];} + + const t_item * get_ptr() const {return m_data.get_ptr();} + t_item * get_ptr() {return m_data.get_ptr();} + bool is_ptr_owned(const void * p_item) const {return m_data.is_ptr_owned(p_item);} + void prealloc(t_size) {} + void force_reset() {m_data.set_size(0,0);} + + enum { alloc_prioritizes_speed = true }; + + void move_from(t_self & other) { m_data.move_from(other.m_data); } + private: + alloc_fast(const t_self &) {throw pfc::exception_not_implemented();} + const t_self & operator=(const t_self&) {throw pfc::exception_not_implemented();} + __array_fast_helper_t m_data; + }; + + template class alloc_fast_aggressive { + private: typedef alloc_fast_aggressive t_self; + public: + alloc_fast_aggressive() {} + + void set_size(t_size p_size) { + t_size size_base = m_data.get_size_total(); + if (size_base == 0) size_base = 1; + while(size_base < p_size) { + size_base = safe_shift_left_t(size_base,1); + } + m_data.set_size(p_size,size_base); + } + + void prealloc(t_size p_size) { + if (p_size > 0) { + t_size size_base = m_data.get_size_total(); + if (size_base == 0) size_base = 1; + while(size_base < p_size) { + size_base = safe_shift_left_t(size_base,1); + } + m_data.set_size(m_data.get_size(),size_base); + } + } + + t_size get_size() const {return m_data.get_size();} + const t_item & operator[](t_size p_index) const {;return m_data[p_index];} + t_item & operator[](t_size p_index) {return m_data[p_index];} + + const t_item * get_ptr() const {return m_data.get_ptr();} + t_item * get_ptr() {return m_data.get_ptr();} + bool is_ptr_owned(const void * p_item) const {return m_data.is_ptr_owned(p_item);} + void force_reset() {m_data.set_size(0,0);} + + enum { alloc_prioritizes_speed = true }; + + void move_from(t_self & other) { m_data.move_from(other.m_data); } + private: + alloc_fast_aggressive(const t_self &) {throw pfc::exception_not_implemented();} + const t_self & operator=(const t_self&) {throw pfc::exception_not_implemented();} + __array_fast_helper_t m_data; + }; + + template class alloc_fixed { + public: + template class alloc { + private: typedef alloc t_self; + public: + alloc() : m_size(0) {} + + void set_size(t_size p_size) { + static_assert_t(); + + if (p_size > p_width) throw pfc::exception_overflow(); + else if (p_size > m_size) { + __unsafe__in_place_constructor_array_t(get_ptr()+m_size,p_size-m_size); + m_size = p_size; + } else if (p_size < m_size) { + __unsafe__in_place_destructor_array_t(get_ptr()+p_size,m_size-p_size); + m_size = p_size; + } + } + + ~alloc() { + if (pfc::traits_t::needs_destructor) set_size(0); + } + + t_size get_size() const {return m_size;} + + t_item * get_ptr() {return reinterpret_cast(&m_array);} + const t_item * get_ptr() const {return reinterpret_cast(&m_array);} + + const t_item & operator[](t_size n) const {return get_ptr()[n];} + t_item & operator[](t_size n) {return get_ptr()[n];} + bool is_ptr_owned(const void * p_item) const {return is_pointer_in_range(get_ptr(),p_width,p_item);} + void prealloc(t_size) {} + void force_reset() {set_size(0);} + + enum { alloc_prioritizes_speed = false }; + + void move_from(t_self & other) { + const size_t count = other.get_size(); + set_size( count ); + for(size_t w = 0; w < count; ++w) this->get_ptr()[w] = other.get_ptr()[w]; + } + private: + alloc(const t_self&) {throw pfc::exception_not_implemented();} + const t_self& operator=(const t_self&) {throw pfc::exception_not_implemented();} + + t_uint8 m_array[sizeof(t_item[p_width])]; + t_size m_size; + }; + }; + + template class t_alloc = alloc_standard > class alloc_hybrid { + public: + template class alloc { + private: typedef alloc t_self; + public: + alloc() {} + + void set_size(t_size p_size) { + if (p_size > p_width) { + m_fixed.set_size(p_width); + m_variable.set_size(p_size - p_width); + } else { + m_fixed.set_size(p_size); + m_variable.set_size(0); + } + } + + t_item & operator[](t_size p_index) { + PFC_ASSERT(p_index < get_size()); + if (p_index < p_width) return m_fixed[p_index]; + else return m_variable[p_index - p_width]; + } + + const t_item & operator[](t_size p_index) const { + PFC_ASSERT(p_index < get_size()); + if (p_index < p_width) return m_fixed[p_index]; + else return m_variable[p_index - p_width]; + } + + t_size get_size() const {return m_fixed.get_size() + m_variable.get_size();} + bool is_ptr_owned(const void * p_item) const {return m_fixed.is_ptr_owned(p_item) || m_variable.is_ptr_owned(p_item);} + void prealloc(t_size p_size) { + if (p_size > p_width) m_variable.prealloc(p_size - p_width); + } + void force_reset() { + m_fixed.force_reset(); m_variable.force_reset(); + } + enum { alloc_prioritizes_speed = t_alloc::alloc_prioritizes_speed }; + + void move_from(t_self & other) { + m_fixed.move_from(other.m_fixed); + m_variable.move_from(other.m_variable); + } + private: + alloc(const t_self&) {throw pfc::exception_not_implemented();} + const t_self& operator=(const t_self&) {throw pfc::exception_not_implemented();} + + typename alloc_fixed::template alloc m_fixed; + t_alloc m_variable; + }; + }; + + template class traits_t > : public traits_default_movable {}; + template class traits_t<__array_fast_helper_t > : public traits_default_movable {}; + template class traits_t > : public pfc::traits_t<__array_fast_helper_t > {}; + template class traits_t > : public pfc::traits_t<__array_fast_helper_t > {}; + template class traits_t > : public pfc::traits_t<__array_fast_helper_t > {}; + +#if 0//not working (compiler bug?) + template class traits_t::template alloc > : public pfc::traits_t { + public: + enum { + needs_constructor = true, + }; + }; + + template class t_alloc,typename t_item> + class traits_t::template alloc > : public traits_combined::template alloc > {}; +#endif + + +}; diff --git a/SDK/pfc/array.h b/SDK/pfc/array.h new file mode 100644 index 0000000..692bfa3 --- /dev/null +++ b/SDK/pfc/array.h @@ -0,0 +1,325 @@ +#ifndef _PFC_ARRAY_H_ +#define _PFC_ARRAY_H_ + +namespace pfc { + + template class t_alloc = alloc_standard> class array_t; + + + //! Special simplififed version of array class that avoids stepping on landmines with classes without public copy operators/constructors. + template + class array_staticsize_t { + public: typedef _t_item t_item; + private: typedef array_staticsize_t t_self; + public: + array_staticsize_t() : m_array(NULL), m_size(0) {} + array_staticsize_t(t_size p_size) : m_array(new t_item[p_size]), m_size(p_size) {} + ~array_staticsize_t() {release_();} + + //! Copy constructor nonfunctional when data type is not copyable. + array_staticsize_t(const t_self & p_source) : m_size(0), m_array(NULL) { + *this = p_source; + } + + //! Copy operator nonfunctional when data type is not copyable. + const t_self & operator=(const t_self & p_source) { + release_(); + + //m_array = pfc::malloc_copy_t(p_source.get_size(),p_source.get_ptr()); + const t_size newsize = p_source.get_size(); + m_array = new t_item[newsize]; + m_size = newsize; + for(t_size n = 0; n < newsize; n++) m_array[n] = p_source[n]; + return *this; + } + + void set_size_discard(t_size p_size) { + release_(); + if (p_size > 0) { + m_array = new t_item[p_size]; + m_size = p_size; + } + } + //! Warning: buffer pointer must not point to buffer allocated by this array (fixme). + template + void set_data_fromptr(const t_source * p_buffer,t_size p_count) { + set_size_discard(p_count); + pfc::copy_array_loop_t(*this,p_buffer,p_count); + } + + + t_size get_size() const {return m_size;} + const t_item * get_ptr() const {return m_array;} + t_item * get_ptr() {return m_array;} + + const t_item & operator[](t_size p_index) const {PFC_ASSERT(p_index < get_size());return m_array[p_index];} + t_item & operator[](t_size p_index) {PFC_ASSERT(p_index < get_size());return m_array[p_index];} + + template bool is_owned(const t_source & p_item) {return pfc::is_pointer_in_range(get_ptr(),get_size(),&p_item);} + + template void enumerate(t_out & out) const { for(t_size walk = 0; walk < m_size; ++walk) out(m_array[walk]); } + private: + void release_() { + m_size = 0; + delete[] pfc::replace_null_t(m_array); + } + t_item * m_array; + t_size m_size; + }; + + template + void copy_array_t(t_to & p_to,const t_from & p_from) { + const t_size size = array_size_t(p_from); + if (p_to.has_owned_items(p_from)) {//avoid landmines with actual array data overlapping, or p_from being same as p_to + array_staticsize_t temp; + temp.set_size_discard(size); + pfc::copy_array_loop_t(temp,p_from,size); + p_to.set_size(size); + pfc::copy_array_loop_t(p_to,temp,size); + } else { + p_to.set_size(size); + pfc::copy_array_loop_t(p_to,p_from,size); + } + } + + template + void fill_array_t(t_array & p_array,const t_value & p_value) { + const t_size size = array_size_t(p_array); + for(t_size n=0;n class t_alloc> class array_t { + public: typedef _t_item t_item; + private: typedef array_t t_self; + public: + array_t() {} + array_t(const t_self & p_source) {copy_array_t(*this,p_source);} + template array_t(const t_source & p_source) {copy_array_t(*this,p_source);} + const t_self & operator=(const t_self & p_source) {copy_array_t(*this,p_source); return *this;} + template const t_self & operator=(const t_source & p_source) {copy_array_t(*this,p_source); return *this;} + + array_t(t_self && p_source) {move_from(p_source);} + const t_self & operator=(t_self && p_source) {move_from(p_source); return *this;} + + void set_size(t_size p_size) {m_alloc.set_size(p_size);} + + template + void set_size_fill(size_t p_size, fill_t const & filler) { + size_t before = get_size(); + set_size( p_size ); + for(size_t w = before; w < p_size; ++w) this->get_ptr()[w] = filler; + } + + void set_size_in_range(size_t minSize, size_t maxSize) { + if (minSize >= maxSize) { set_size( minSize); return; } + size_t walk = maxSize; + for(;;) { + try { + set_size(walk); + return; + } catch(std::bad_alloc) { + if (walk <= minSize) throw; + // go on + } + walk >>= 1; + if (walk < minSize) walk = minSize; + } + } + void set_size_discard(t_size p_size) {m_alloc.set_size(p_size);} + void set_count(t_size p_count) {m_alloc.set_size(p_count);} + t_size get_size() const {return m_alloc.get_size();} + t_size get_count() const {return m_alloc.get_size();} + void force_reset() {m_alloc.force_reset();} + + const t_item & operator[](t_size p_index) const {PFC_ASSERT(p_index < get_size());return m_alloc[p_index];} + t_item & operator[](t_size p_index) {PFC_ASSERT(p_index < get_size());return m_alloc[p_index];} + + //! Warning: buffer pointer must not point to buffer allocated by this array (fixme). + template + void set_data_fromptr(const t_source * p_buffer,t_size p_count) { + set_size(p_count); + pfc::copy_array_loop_t(*this,p_buffer,p_count); + } + + template + void append(const t_array & p_source) { + if (has_owned_items(p_source)) append(array_t(p_source)); + else { + const t_size source_size = array_size_t(p_source); + const t_size base = get_size(); + increase_size(source_size); + for(t_size n=0;n + void insert_multi(const t_insert & value, t_size base, t_size count) { + const t_size oldSize = get_size(); + if (base > oldSize) base = oldSize; + increase_size(count); + pfc::memmove_t(get_ptr() + base + count, get_ptr() + base, oldSize - base); + pfc::fill_ptr_t(get_ptr() + base, count, value); + } + template void append_multi(const t_append & value, t_size count) {insert_multi(value,~0,count);} + + //! Warning: buffer pointer must not point to buffer allocated by this array (fixme). + template + void append_fromptr(const t_append * p_buffer,t_size p_count) { + PFC_ASSERT( !is_owned(&p_buffer[0]) ); + t_size base = get_size(); + increase_size(p_count); + for(t_size n=0;n + void append_single_val( t_append item ) { + const t_size base = get_size(); + increase_size(1); + m_alloc[base] = item; + } + + template + void append_single(const t_append & p_item) { + if (is_owned(p_item)) append_single(t_append(p_item)); + else { + const t_size base = get_size(); + increase_size(1); + m_alloc[base] = p_item; + } + } + + template + void fill(const t_filler & p_filler) { + const t_size max = get_size(); + for(t_size n=0;n get_size()) set_size(p_size); + } + + //not supported by some allocs + const t_item * get_ptr() const {return m_alloc.get_ptr();} + t_item * get_ptr() {return m_alloc.get_ptr();} + + void prealloc(t_size p_size) {m_alloc.prealloc(p_size);} + + template + bool has_owned_items(const t_array & p_source) { + if (array_size_t(p_source) == 0) return false; + + //how the hell would we properly check if any of source items is owned by us, in case source array implements some weird mixing of references of items from different sources? + //the most obvious way means evil bottleneck here (whether it matters or not from caller's point of view which does something O(n) already is another question) + //at least this will work fine with all standard classes which don't crossreference anyhow and always use own storage + //perhaps we'll traitify this someday later + return is_owned(p_source[0]); + } + + template + bool is_owned(const t_source & p_item) { + return m_alloc.is_ptr_owned(&p_item); + } + + template + void set_single(const t_item & p_item) { + set_size(1); + (*this)[0] = p_item; + } + + template void enumerate(t_callback & p_callback) const { for(t_size n = 0; n < get_size(); n++ ) { p_callback((*this)[n]); } } + + void move_from(t_self & other) { + m_alloc.move_from(other.m_alloc); + } + private: + t_alloc m_alloc; + }; + + template class t_alloc = alloc_standard > + class array_hybrid_t : public array_t::template alloc > + {}; + + + template class traits_t > : public traits_default_movable {}; + template class t_alloc> class traits_t > : public pfc::traits_t > {}; + + + template + class comparator_array { + public: + template + static int compare(const t_array1 & p_array1, const t_array2 & p_array2) { + t_size walk = 0; + for(;;) { + if (walk >= p_array1.get_size() && walk >= p_array2.get_size()) return 0; + else if (walk >= p_array1.get_size()) return -1; + else if (walk >= p_array2.get_size()) return 1; + else { + int state = t_comparator::compare(p_array1[walk],p_array2[walk]); + if (state != 0) return state; + } + ++walk; + } + } + }; + + template + static bool array_equals(const t_a1 & arr1, const t_a2 & arr2) { + const t_size s = array_size_t(arr1); + if (s != array_size_t(arr2)) return false; + for(t_size walk = 0; walk < s; ++walk) { + if (arr1[walk] != arr2[walk]) return false; + } + return true; + } + + + + template class t_alloc = alloc_standard> class array_2d_t { + public: + array_2d_t() : m_d1(), m_d2() {} + void set_size(t_size d1, t_size d2) { + m_content.set_size(pfc::mul_safe_t(d1, d2)); + m_d1 = d1; m_d2 = d2; + } + t_size get_dim1() const {return m_d1;} + t_size get_dim2() const {return m_d2;} + + t_item & at(t_size i1, t_size i2) { + return * _transformPtr(m_content.get_ptr(), i1, i2); + } + const t_item & at(t_size i1, t_size i2) const { + return * _transformPtr(m_content.get_ptr(), i1, i2); + } + template void fill(const t_filler & p_filler) {m_content.fill(p_filler);} + void fill_null() {m_content.fill_null();} + + t_item * rowPtr(t_size i1) {return _transformPtr(m_content.get_ptr(), i1, 0);} + const t_item * rowPtr(t_size i1) const {return _transformPtr(m_content.get_ptr(), i1, 0);} + + const t_item * operator[](t_size i1) const {return rowPtr(i1);} + t_item * operator[](t_size i1) {return rowPtr(i1);} + private: + template t_ptr _transformPtr(t_ptr ptr, t_size i1, t_size i2) const { + PFC_ASSERT( i1 < m_d1 ); PFC_ASSERT( i2 < m_d2 ); + return ptr + i1 * m_d2 + i2; + } + pfc::array_t m_content; + t_size m_d1, m_d2; + }; + +} + + +#endif //_PFC_ARRAY_H_ diff --git a/SDK/pfc/audio_math.cpp b/SDK/pfc/audio_math.cpp new file mode 100644 index 0000000..f623839 --- /dev/null +++ b/SDK/pfc/audio_math.cpp @@ -0,0 +1,141 @@ +#include "pfc.h" + +static audio_sample noopt_calculate_peak(const audio_sample * p_src,t_size p_num) +{ + audio_sample peak = 0; + t_size num = p_num; + for(;num;num--) + { + audio_sample temp = (audio_sample)fabs(*(p_src++)); + if (temp>peak) peak = temp; + } + return peak; +} + + + + +static void noopt_convert_to_32bit(const audio_sample * p_source,t_size p_count,t_int32 * p_output,float p_scale) +{ + t_size num = p_count; + for(;num;--num) + { + t_int64 val = pfc::audio_math::rint64( *(p_source++) * p_scale ); + if (val < -(t_int64)0x80000000) val = -(t_int64)0x80000000; + else if (val > 0x7FFFFFFF) val = 0x7FFFFFFF; + *(p_output++) = (t_int32) val; + } +} + +inline static void noopt_convert_to_16bit(const audio_sample * p_source,t_size p_count,t_int16 * p_output,float p_scale) { + for(t_size n=0;n(p_buffer); + for(;p_count;p_count--) + { + t_uint32 t = *ptr; + if ((t & 0x007FFFFF) && !(t & 0x7F800000)) *ptr=0; + ptr++; + } +#elif audio_sample_size == 64 + t_uint64 * ptr = reinterpret_cast(p_buffer); + for(;p_count;p_count--) + { + t_uint64 t = *ptr; + if ((t & 0x000FFFFFFFFFFFFF) && !(t & 0x7FF0000000000000)) *ptr=0; + ptr++; + } +#else +#error unsupported +#endif + } + + void audio_math::add_offset(audio_sample * p_buffer,audio_sample p_delta,t_size p_count) { + for(t_size n=0;n(sourcePtr); + u.bytes[0] = 0; + u.bytes[1] = s[0]; + u.bytes[2] = s[1]; + u.bytes[3] = s[2]; + return u.v; + } + audio_sample audio_math::decodeFloat24ptrbs(const void * sourcePtr) { + PFC_STATIC_ASSERT(pfc::byte_order_is_little_endian); + union { + uint8_t bytes[4]; + float v; + } u; + const uint8_t * s = reinterpret_cast(sourcePtr); + u.bytes[0] = 0; + u.bytes[1] = s[2]; + u.bytes[2] = s[1]; + u.bytes[3] = s[0]; + return u.v; + } + + audio_sample audio_math::decodeFloat16(uint16_t source) { + const unsigned fractionBits = 10; + const unsigned widthBits = 16; + typedef uint16_t source_t; + + /* typedef uint64_t out_t; typedef double retval_t; + enum { + outExponent = 11, + outFraction = 52, + outExponentShift = (1 << (outExponent-1))-1 + };*/ + + typedef uint32_t out_t; typedef float retval_t; + enum { + outExponent = 8, + outFraction = 23, + outExponentShift = (1 << (outExponent-1))-1 + }; + + const unsigned exponentBits = widthBits - fractionBits - 1; + // 1 bit sign | exponent | fraction + source_t fraction = source & (((source_t)1 << fractionBits)-1); + source >>= fractionBits; + int exponent = (int)( source & (((source_t)1 << exponentBits)-1) ) - (int)((1 << (exponentBits-1))-1); + source >>= exponentBits; + + if (outExponent + outExponentShift <= 0) return 0; + + out_t output = (out_t)( source&1 ); + output <<= outExponent; + output |= (unsigned) (exponent + outExponentShift) & ( (1<> -shift); + else output |= (out_t) (fraction << shift); + return *(retval_t*)&output / pfc::audio_math::float16scale; + } +} diff --git a/SDK/pfc/audio_sample.h b/SDK/pfc/audio_sample.h new file mode 100644 index 0000000..52c1d3b --- /dev/null +++ b/SDK/pfc/audio_sample.h @@ -0,0 +1,88 @@ +#include + +#include +#if SIZE_MAX < UINT64_MAX +#define audio_sample_size 32 +#else +#define audio_sample_size 64 +#endif + +#if audio_sample_size == 32 +typedef float audio_sample; +#define audio_sample_asm dword +#elif audio_sample_size == 64 +typedef double audio_sample; +#define audio_sample_asm qword +#else +#error wrong audio_sample_size +#endif + +#define audio_sample_bytes (audio_sample_size/8) + +namespace pfc { + // made a class so it can be redirected to an alternate class more easily than with namespacing + // in win desktop fb2k these are implemented in a DLL + class audio_math { + public: + + //! p_source/p_output can point to same buffer + static void scale(const audio_sample * p_source, t_size p_count, audio_sample * p_output, audio_sample p_scale); + static void convert_to_int16(const audio_sample * p_source, t_size p_count, t_int16 * p_output, audio_sample p_scale); + static void convert_to_int32(const audio_sample * p_source, t_size p_count, t_int32 * p_output, audio_sample p_scale); + static audio_sample convert_to_int16_calculate_peak(const audio_sample * p_source, t_size p_count, t_int16 * p_output, audio_sample p_scale); + static void convert_from_int16(const t_int16 * p_source, t_size p_count, audio_sample * p_output, audio_sample p_scale); + static void convert_from_int32(const t_int32 * p_source, t_size p_count, audio_sample * p_output, audio_sample p_scale); + static audio_sample convert_to_int32_calculate_peak(const audio_sample * p_source, t_size p_count, t_int32 * p_output, audio_sample p_scale); + static audio_sample calculate_peak(const audio_sample * p_source, t_size p_count); + static void remove_denormals(audio_sample * p_buffer, t_size p_count); + static void add_offset(audio_sample * p_buffer, audio_sample p_delta, t_size p_count); + + static inline t_uint64 time_to_samples(double p_time, t_uint32 p_sample_rate) { + return (t_uint64)floor((double)p_sample_rate * p_time + 0.5); + } + + static inline double samples_to_time(t_uint64 p_samples, t_uint32 p_sample_rate) { + PFC_ASSERT(p_sample_rate > 0); + return (double)p_samples / (double)p_sample_rate; + } + + +#if defined(_MSC_VER) && defined(_M_IX86) + inline static t_int64 rint64(audio_sample val) { + t_int64 rv; + _asm { + fld val; + fistp rv; + } + return rv; + } + inline static t_int32 rint32(audio_sample val) { + t_int32 rv; + _asm { + fld val; + fistp rv; + } + return rv; + } +#elif defined(_MSC_VER) && defined(_M_X64) + inline static t_int64 rint64(audio_sample val) { return (t_int64)floor(val + 0.5); } + static inline t_int32 rint32(float p_val) { + return (t_int32)_mm_cvtss_si32(_mm_load_ss(&p_val)); + } +#else + inline static t_int64 rint64(audio_sample val) { return (t_int64)floor(val + 0.5); } + inline static t_int32 rint32(audio_sample val) { return (t_int32)floor(val + 0.5); } +#endif + + + static inline audio_sample gain_to_scale(double p_gain) { return (audio_sample)pow(10.0, p_gain / 20.0); } + static inline double scale_to_gain(double scale) { return 20.0*log10(scale); } + + static const audio_sample float16scale; + + static audio_sample decodeFloat24ptr(const void * sourcePtr); + static audio_sample decodeFloat24ptrbs(const void * sourcePtr); + static audio_sample decodeFloat16(uint16_t source); + }; // class audio_math + +} // namespace pfc diff --git a/SDK/pfc/avltree.h b/SDK/pfc/avltree.h new file mode 100644 index 0000000..77b3724 --- /dev/null +++ b/SDK/pfc/avltree.h @@ -0,0 +1,551 @@ +namespace pfc { + + template + class _avltree_node : public _list_node { + public: + typedef _list_node t_node; + typedef _avltree_node t_self; + template _avltree_node(t_param const& param) : t_node(param), m_left(), m_right(), m_depth() {} + + typedef refcounted_object_ptr_t t_ptr; + typedef t_self* t_rawptr; + + t_ptr m_left, m_right; + t_rawptr m_parent; + + t_size m_depth; + + void link_left(t_self* ptr) throw() { + m_left = ptr; + if (ptr != NULL) ptr->m_parent = this; + } + void link_right(t_self* ptr) throw() { + m_right = ptr; + if (ptr != NULL) ptr->m_parent = this; + } + + void link_child(bool which,t_self* ptr) throw() { + (which ? m_right : m_left) = ptr; + if (ptr != NULL) ptr->m_parent = this; + } + + void unlink() throw() { + m_left.release(); m_right.release(); m_parent = NULL; m_depth = 0; + } + + inline void add_ref() throw() {this->refcount_add_ref();} + inline void release() throw() {this->refcount_release();} + + inline t_rawptr child(bool which) const throw() {return which ? m_right.get_ptr() : m_left.get_ptr();} + inline bool which_child(const t_self* ptr) const throw() {return ptr == m_right.get_ptr();} + + + + t_rawptr step(bool direction) throw() { + t_self* walk = this; + for(;;) { + t_self* t = walk->child(direction); + if (t != NULL) return t->peakchild(!direction); + for(;;) { + t = walk->m_parent; + if (t == NULL) return NULL; + if (t->which_child(walk) != direction) return t; + walk = t; + } + } + } + t_rawptr peakchild(bool direction) throw() { + t_self* walk = this; + for(;;) { + t_rawptr next = walk->child(direction); + if (next == NULL) return walk; + walk = next; + } + } + t_node * prev() throw() {return step(false);} + t_node * next() throw() {return step(true);} + private: + ~_avltree_node() throw() {} + }; + + + template + class avltree_t { + public: + typedef avltree_t t_self; + typedef pfc::const_iterator const_iterator; + typedef pfc::iterator iterator; + typedef t_storage t_item; + private: + typedef _avltree_node t_node; +#if 1//MSVC8 bug fix + typedef refcounted_object_ptr_t t_nodeptr; + typedef t_node * t_noderawptr; +#else + typedef typename t_node::t_ptr t_nodeptr; + typedef typename t_node::t_rawptr t_noderawptr; +#endif + + static bool is_ptr_valid(t_nodeptr const & p) { return p.is_valid(); } + static bool is_ptr_valid(t_node const * p) { return p != NULL; } + + template + inline static int compare(const t_item1 & p_item1, const t_item2 & p_item2) { + return t_comparator::compare(p_item1,p_item2); + } + + t_nodeptr m_root; + + static t_size calc_depth(const t_nodeptr & ptr) + { + return ptr.is_valid() ? 1+ptr->m_depth : 0; + } + + static void recalc_depth(t_nodeptr const& ptr) { + ptr->m_depth = pfc::max_t(calc_depth(ptr->m_left), calc_depth(ptr->m_right)); + } + + static void assert_children(t_nodeptr ptr) { + PFC_ASSERT(ptr->m_depth == pfc::max_t(calc_depth(ptr->m_left),calc_depth(ptr->m_right)) ); + } + + static t_ssize test_depth(t_nodeptr const& ptr) + { + if (ptr==0) return 0; + else return calc_depth(ptr->m_right) - calc_depth(ptr->m_left); + } + + static t_nodeptr extract_left_leaf(t_nodeptr & p_base) { + if (is_ptr_valid(p_base->m_left)) { + t_nodeptr ret = extract_left_leaf(p_base->m_left); + recalc_depth(p_base); + g_rebalance(p_base); + return ret; + } else { + t_nodeptr node = p_base; + p_base = node->m_right; + if (p_base.is_valid()) p_base->m_parent = node->m_parent; + node->m_right.release(); + node->m_depth = 0; + node->m_parent = NULL; + return node; + } + } + + static t_nodeptr extract_right_leaf(t_nodeptr & p_base) { + if (is_ptr_valid(p_base->m_right)) { + t_nodeptr ret = extract_right_leaf(p_base->m_right); + recalc_depth(p_base); + g_rebalance(p_base); + return ret; + } else { + t_nodeptr node = p_base; + p_base = node->m_left; + if (p_base.is_valid()) p_base->m_parent = node->m_parent; + node->m_left.release(); + node->m_depth = 0; + node->m_parent = NULL; + return node; + } + } + + static void remove_internal(t_nodeptr & p_node) { + t_nodeptr oldval = p_node; + if (p_node->m_left.is_empty()) { + p_node = p_node->m_right; + if (p_node.is_valid()) p_node->m_parent = oldval->m_parent; + } else if (p_node->m_right.is_empty()) { + p_node = p_node->m_left; + if (p_node.is_valid()) p_node->m_parent = oldval->m_parent; + } else { + t_nodeptr swap = extract_left_leaf(p_node->m_right); + + swap->link_left(oldval->m_left.get_ptr()); + swap->link_right(oldval->m_right.get_ptr()); + swap->m_parent = oldval->m_parent; + recalc_depth(swap); + p_node = swap; + } + oldval->unlink(); + } + + template + static void __enum_items_recur(t_nodewalk * p_node,t_callback & p_callback) { + if (is_ptr_valid(p_node)) { + __enum_items_recur(p_node->m_left.get_ptr(),p_callback); + p_callback (p_node->m_content); + __enum_items_recur(p_node->m_right.get_ptr(),p_callback); + } + } + template + static t_node * g_find_or_add_node(t_nodeptr & p_base,t_node * parent,t_search const & p_search,bool & p_new) + { + if (p_base.is_empty()) { + p_base = new t_node(p_search); + p_base->m_parent = parent; + p_new = true; + return p_base.get_ptr(); + } + + PFC_ASSERT( p_base->m_parent == parent ); + + int result = compare(p_base->m_content,p_search); + if (result > 0) { + t_node * ret = g_find_or_add_node(p_base->m_left,p_base.get_ptr(),p_search,p_new); + if (p_new) { + recalc_depth(p_base); + g_rebalance(p_base); + } + return ret; + } else if (result < 0) { + t_node * ret = g_find_or_add_node(p_base->m_right,p_base.get_ptr(),p_search,p_new); + if (p_new) { + recalc_depth(p_base); + g_rebalance(p_base); + } + return ret; + } else { + p_new = false; + return p_base.get_ptr(); + } + } + + + + template + static t_storage * g_find_or_add(t_nodeptr & p_base,t_node * parent,t_search const & p_search,bool & p_new) { + return &g_find_or_add_node(p_base,parent,p_search,p_new)->m_content; + } + + + static void g_rotate_right(t_nodeptr & oldroot) { + t_nodeptr newroot ( oldroot->m_right ); + oldroot->link_child(true, newroot->m_left.get_ptr()); + newroot->m_left = oldroot; + newroot->m_parent = oldroot->m_parent; + oldroot->m_parent = newroot.get_ptr(); + recalc_depth(oldroot); + recalc_depth(newroot); + oldroot = newroot; + } + + static void g_rotate_left(t_nodeptr & oldroot) { + t_nodeptr newroot ( oldroot->m_left ); + oldroot->link_child(false, newroot->m_right.get_ptr()); + newroot->m_right = oldroot; + newroot->m_parent = oldroot->m_parent; + oldroot->m_parent = newroot.get_ptr(); + recalc_depth(oldroot); + recalc_depth(newroot); + oldroot = newroot; + } + + static void g_rebalance(t_nodeptr & p_node) { + t_ssize balance = test_depth(p_node); + if (balance > 1) { + //right becomes root + if (test_depth(p_node->m_right) < 0) { + g_rotate_left(p_node->m_right); + } + g_rotate_right(p_node); + } else if (balance < -1) { + //left becomes root + if (test_depth(p_node->m_left) > 0) { + g_rotate_right(p_node->m_left); + } + g_rotate_left(p_node); + } + selftest(p_node); + } + + template + static bool g_remove(t_nodeptr & p_node,t_search const & p_search) { + if (p_node.is_empty()) return false; + + int result = compare(p_node->m_content,p_search); + if (result == 0) { + remove_internal(p_node); + if (is_ptr_valid(p_node)) { + recalc_depth(p_node); + g_rebalance(p_node); + } + return true; + } else { + if (g_remove(result > 0 ? p_node->m_left : p_node->m_right,p_search)) { + recalc_depth(p_node); + g_rebalance(p_node); + return true; + } else { + return false; + } + } + } + + static void selftest(t_nodeptr const& p_node) { + #if 0 //def _DEBUG//SLOW! + if (is_ptr_valid(p_node)) { + selftest(p_node->m_left); + selftest(p_node->m_right); + assert_children(p_node); + t_ssize delta = test_depth(p_node); + PFC_ASSERT(delta >= -1 && delta <= 1); + + if (p_node->m_left.is_valid()) { + PFC_ASSERT( p_node.get_ptr() == p_node->m_left->m_parent ); + } + if (p_node->m_right.is_valid()) { + PFC_ASSERT( p_node.get_ptr() == p_node->m_right->m_parent ); + } + + if (is_ptr_valid(p_node->m_parent)) { + PFC_ASSERT(p_node == p_node->m_parent->m_left || p_node == p_node->m_parent->m_right); + } + } + #endif + } + + + static t_size calc_count(const t_node * p_node) throw() { + if (is_ptr_valid(p_node)) { + return 1 + calc_count(p_node->m_left.get_ptr()) + calc_count(p_node->m_right.get_ptr()); + } else { + return 0; + } + } + + template + t_storage * _find_item_ptr(t_param const & p_item) const { + t_node* ptr = m_root.get_ptr(); + while(is_ptr_valid(ptr)) { + int result = compare(ptr->m_content,p_item); + if (result > 0) ptr=ptr->m_left.get_ptr(); + else if (result < 0) ptr=ptr->m_right.get_ptr(); + else return &ptr->m_content; + } + return NULL; + } + + template + t_node * _find_node_ptr(t_param const & p_item) const { + t_node* ptr = m_root.get_ptr(); + while(is_ptr_valid(ptr)) { + int result = compare(ptr->m_content,p_item); + if (result > 0) ptr=ptr->m_left.get_ptr(); + else if (result < 0) ptr=ptr->m_right.get_ptr(); + else return ptr; + } + return NULL; + } + + template t_storage * __find_nearest(const t_search & p_search) const { + t_node * ptr = m_root.get_ptr(); + t_storage * found = NULL; + while(is_ptr_valid(ptr)) { + int result = compare(ptr->m_content,p_search); + if (above) result = -result; + if (inclusive && result == 0) { + //direct hit + found = &ptr->m_content; + break; + } else if (result < 0) { + //match + found = &ptr->m_content; + ptr = ptr->child(!above); + } else { + //mismatch + ptr = ptr->child(above); + } + } + return found; + } + public: + avltree_t() : m_root(NULL) {} + ~avltree_t() {reset();} + const t_self & operator=(const t_self & p_other) {__copy(p_other);return *this;} + avltree_t(const t_self & p_other) : m_root(NULL) {try{__copy(p_other);} catch(...) {remove_all(); throw;}} + + template const t_self & operator=(const t_other & p_other) {copy_list_enumerated(*this,p_other);return *this;} + template avltree_t(const t_other & p_other) : m_root(NULL) {try{copy_list_enumerated(*this,p_other);}catch(...){remove_all(); throw;}} + + + template const t_storage * find_nearest_item(const t_search & p_search) const { + return __find_nearest(p_search); + } + + template t_storage * find_nearest_item(const t_search & p_search) { + return __find_nearest(p_search); + } + + template + t_storage & add_item(t_param const & p_item) { + bool dummy; + return add_item_ex(p_item,dummy); + } + + template + t_self & operator+=(const t_param & p_item) {add_item(p_item);return *this;} + + template + t_self & operator-=(const t_param & p_item) {remove_item(p_item);return *this;} + + //! Returns true when the list has been altered, false when the item was already present before. + template + bool add_item_check(t_param const & item) { + bool isNew = false; + g_find_or_add(m_root,NULL,item,isNew); + selftest(m_root); + return isNew; + } + template + t_storage & add_item_ex(t_param const & p_item,bool & p_isnew) { + t_storage * ret = g_find_or_add(m_root,NULL,p_item,p_isnew); + selftest(m_root); + return *ret; + } + + template + void set_item(const t_param & p_item) { + bool isnew; + t_storage & found = add_item_ex(p_item,isnew); + if (isnew) found = p_item; + } + + template + const t_storage * find_item_ptr(t_param const & p_item) const {return _find_item_ptr(p_item);} + + //! Unsafe! Caller must not modify items in a way that changes sort order! + template + t_storage * find_item_ptr(t_param const & p_item) { return _find_item_ptr(p_item); } + + template const_iterator find(t_param const & item) const { return _find_node_ptr(item);} + + //! Unsafe! Caller must not modify items in a way that changes sort order! + template iterator find(t_param const & item) { return _find_node_ptr(item);} + + + template + bool contains(const t_param & p_item) const { + return find_item_ptr(p_item) != NULL; + } + + //! Same as contains(). + template + bool have_item(const t_param & p_item) const {return contains(p_item);} + + void remove_all() throw() { + _unlink_recur(m_root); + m_root.release(); + } + + bool remove(const_iterator const& iter) { + PFC_ASSERT(iter.is_valid()); + return remove_item(*iter);//OPTIMIZEME + //should never return false unless there's a bug in calling code + } + + template + bool remove_item(t_param const & p_item) { + bool ret = g_remove(m_root,p_item); + selftest(m_root); + return ret; + } + + t_size get_count() const throw() { + return calc_count(m_root.get_ptr()); + } + + template + void enumerate(t_callback & p_callback) const { + __enum_items_recur(m_root.get_ptr(),p_callback); + } + + //! Allows callback to modify the tree content. + //! Unsafe! Caller must not modify items in a way that changes sort order! + template + void _enumerate_var(t_callback & p_callback) { __enum_items_recur(m_root.get_ptr(),p_callback); } + + template iterator insert(const t_param & p_item) { + bool isNew; + t_node * ret = g_find_or_add_node(m_root,NULL,p_item,isNew); + selftest(m_root); + return ret; + } + + //deprecated backwards compatibility method wrappers + template t_storage & add(const t_param & p_item) {return add_item(p_item);} + template t_storage & add_ex(const t_param & p_item,bool & p_isnew) {return add_item_ex(p_item,p_isnew);} + template const t_storage * find_ptr(t_param const & p_item) const {return find_item_ptr(p_item);} + template t_storage * find_ptr(t_param const & p_item) {return find_item_ptr(p_item);} + template bool exists(t_param const & p_item) const {return have_item(p_item);} + void reset() {remove_all();} + + + + + const_iterator first() const throw() {return _firstlast(false);} + const_iterator last() const throw() {return _firstlast(true);} + //! Unsafe! Caller must not modify items in a way that changes sort order! + iterator _first_var() { return _firstlast(false); } + //! Unsafe! Caller must not modify items in a way that changes sort order! + iterator _last_var() { return _firstlast(true); } + + template bool get_first(t_param & p_item) const throw() { + const_iterator iter = first(); + if (!iter.is_valid()) return false; + p_item = *iter; + return true; + } + template bool get_last(t_param & p_item) const throw() { + const_iterator iter = last(); + if (!iter.is_valid()) return false; + p_item = *iter; + return true; + } + + static bool equals(const t_self & v1, const t_self & v2) { + return listEquals(v1,v2); + } + bool operator==(const t_self & other) const {return equals(*this,other);} + bool operator!=(const t_self & other) const {return !equals(*this,other);} + + private: + static void _unlink_recur(t_nodeptr & node) { + if (node.is_valid()) { + _unlink_recur(node->m_left); + _unlink_recur(node->m_right); + node->unlink(); + } + } + t_node* _firstlast(bool which) const throw() { + if (m_root.is_empty()) return NULL; + for(t_node * walk = m_root.get_ptr(); ; ) { + t_node * next = walk->child(which); + if (next == NULL) return walk; + PFC_ASSERT( next->m_parent == walk ); + walk = next; + } + } + static t_nodeptr __copy_recur(t_node * p_source,t_node * parent) { + if (p_source == NULL) { + return NULL; + } else { + t_nodeptr newnode = new t_node(p_source->m_content); + newnode->m_depth = p_source->m_depth; + newnode->m_left = __copy_recur(p_source->m_left.get_ptr(),newnode.get_ptr()); + newnode->m_right = __copy_recur(p_source->m_right.get_ptr(),newnode.get_ptr()); + newnode->m_parent = parent; + return newnode; + } + } + + void __copy(const t_self & p_other) { + reset(); + m_root = __copy_recur(p_other.m_root.get_ptr(),NULL); + selftest(m_root); + } + }; + + + template + class traits_t > : public traits_default_movable {}; +} diff --git a/SDK/pfc/base64.cpp b/SDK/pfc/base64.cpp new file mode 100644 index 0000000..08b0be6 --- /dev/null +++ b/SDK/pfc/base64.cpp @@ -0,0 +1,99 @@ +#include "pfc.h" + +namespace bitWriter { + static void set_bit(t_uint8 * p_stream,size_t p_offset, bool state) { + t_uint8 mask = 1 << (7-(p_offset&7)); + t_uint8 & byte = p_stream[p_offset>>3]; + byte = (byte & ~mask) | (state ? mask : 0); + } + static void set_bits(t_uint8 * stream, t_size offset, t_size word, t_size bits) { + for(t_size walk = 0; walk < bits; ++walk) { + t_uint8 bit = (t_uint8)((word >> (bits - walk - 1))&1); + set_bit(stream, offset+walk, bit != 0); + } + } +}; + +namespace pfc { + t_size base64_decode_estimate(const char * text) { + t_size textLen = strlen(text); + if (textLen % 4 != 0) throw pfc::exception_invalid_params(); + t_size outLen = (textLen / 4) * 3; + + if (textLen >= 4) { + if (text[textLen-1] == '=') { + textLen--; outLen--; + if (text[textLen-1] == '=') { + textLen--; outLen--; + } + } + } + return outLen; + } + + + + void base64_decode(const char * text, void * out) { + static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + t_uint8 alphabetRev[256]; + for(t_size walk = 0; walk < PFC_TABSIZE(alphabetRev); ++walk) alphabetRev[walk] = 0xFF; + for(t_size walk = 0; walk < PFC_TABSIZE(alphabet); ++walk) alphabetRev[ (unsigned) alphabet[walk]] = (t_uint8)walk; + const t_size textLen = strlen(text); + + if (textLen % 4 != 0) throw pfc::exception_invalid_params(); + if (textLen == 0) return; + + t_size outWritePtr = 0; + + { + const t_size max = textLen - 4; + t_size textWalk = 0; + for(; textWalk < max; textWalk ++) { + const t_uint8 v = alphabetRev[(t_uint8)text[textWalk]]; + if (v == 0xFF) throw pfc::exception_invalid_params(); + bitWriter::set_bits(reinterpret_cast(out),outWritePtr,v,6); + outWritePtr += 6; + } + + t_uint8 temp[3]; + t_size tempWritePtr = 0; + for(; textWalk < textLen; textWalk ++) { + const char c = text[textWalk]; + if (c == '=') break; + const t_uint8 v = alphabetRev[(t_uint8)c]; + if (v == 0xFF) throw pfc::exception_invalid_params(); + bitWriter::set_bits(temp,tempWritePtr,v,6); + tempWritePtr += 6; + } + for(; textWalk < textLen; textWalk ++) { + if (text[textWalk] != '=') throw pfc::exception_invalid_params(); + } + memcpy(reinterpret_cast(out) + (outWritePtr/8), temp, tempWritePtr/8); + } + } + void base64_encode(pfc::string_base & out, const void * in, t_size inSize) { + out.reset(); base64_encode_append(out, in, inSize); + } + void base64_encode_append(pfc::string_base & out, const void * in, t_size inSize) { + static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + int shift = 0; + int accum = 0; + const t_uint8 * inPtr = reinterpret_cast(in); + + for(t_size walk = 0; walk < inSize; ++walk) { + accum <<= 8; + shift += 8; + accum |= inPtr[walk]; + while ( shift >= 6 ) { + shift -= 6; + out << format_char( alphabet[(accum >> shift) & 0x3F] ); + } + } + if (shift == 4) { + out << format_char( alphabet[(accum & 0xF)<<2] ) << "="; + } else if (shift == 2) { + out << format_char( alphabet[(accum & 0x3)<<4] ) << "=="; + } + } + +} diff --git a/SDK/pfc/base64.h b/SDK/pfc/base64.h new file mode 100644 index 0000000..ed5dc26 --- /dev/null +++ b/SDK/pfc/base64.h @@ -0,0 +1,13 @@ +namespace pfc { + class string_base; + void base64_encode(pfc::string_base & out, const void * in, t_size inSize); + void base64_encode_append(pfc::string_base & out, const void * in, t_size inSize); + t_size base64_decode_estimate(const char * text); + void base64_decode(const char * text, void * out); + + template void base64_decode_array(t_buffer & out, const char * text) { + PFC_STATIC_ASSERT( sizeof(out[0]) == 1 ); + out.set_size_discard( base64_decode_estimate(text) ); + base64_decode(text, out.get_ptr()); + } +} diff --git a/SDK/pfc/binary_search.h b/SDK/pfc/binary_search.h new file mode 100644 index 0000000..7c52e99 --- /dev/null +++ b/SDK/pfc/binary_search.h @@ -0,0 +1,81 @@ +namespace pfc { + class comparator_default; + + template + class binarySearch { + public: + + template + static bool run(const t_container & p_container,t_size p_base,t_size p_count,const t_param & p_param,t_size & p_result) { + t_size max = p_base + p_count; + t_size min = p_base; + while(min> 1); + int state = t_comparator::compare(p_param,p_container[ptr]); + if (state > 0) min = ptr + 1; + else if (state < 0) max = ptr; + else { + p_result = ptr; + return true; + } + } + p_result = min; + return false; + } + + + template + static bool runGroupBegin(const t_container & p_container,t_size p_base,t_size p_count,const t_param & p_param,t_size & p_result) { + t_size max = p_base + p_count; + t_size min = p_base; + bool found = false; + while(min> 1); + int state = t_comparator::compare(p_param,p_container[ptr]); + if (state > 0) min = ptr + 1; + else if (state < 0) max = ptr; + else { + found = true; max = ptr; + } + } + p_result = min; + return found; + } + + template + static bool runGroupEnd(const t_container & p_container,t_size p_base,t_size p_count,const t_param & p_param,t_size & p_result) { + t_size max = p_base + p_count; + t_size min = p_base; + bool found = false; + while(min> 1); + int state = t_comparator::compare(p_param,p_container[ptr]); + if (state > 0) min = ptr + 1; + else if (state < 0) max = ptr; + else { + found = true; min = ptr + 1; + } + } + p_result = min; + return found; + } + + template + static bool runGroup(const t_container & p_container,t_size p_base,t_size p_count,const t_param & p_param,t_size & p_result,t_size & p_resultCount) { + if (!runGroupBegin(p_container,p_base,p_count,p_param,p_result)) { + p_resultCount = 0; + return false; + } + t_size groupEnd; + if (!runGroupEnd(p_container,p_result,p_count - p_result,p_param,groupEnd)) { + //should not happen.. + PFC_ASSERT(0); + p_resultCount = 0; + return false; + } + PFC_ASSERT(groupEnd > p_result); + p_resultCount = groupEnd - p_result; + return true; + } + }; +}; diff --git a/SDK/pfc/bit_array.cpp b/SDK/pfc/bit_array.cpp new file mode 100644 index 0000000..edd94ad --- /dev/null +++ b/SDK/pfc/bit_array.cpp @@ -0,0 +1,88 @@ +#include "pfc.h" + +namespace pfc { + bit_array_var_impl::bit_array_var_impl( const bit_array & source, size_t sourceCount) { + for(size_t w = source.find_first( true, 0, sourceCount); w < sourceCount; w = source.find_next( true, w, sourceCount ) ) { + set(w, true); + } + } + + bool bit_array_var_impl::get(t_size n) const { + return m_data.have_item(n); + } + t_size bit_array_var_impl::find(bool val,t_size start,t_ssize count) const { + if (!val) { + return bit_array::find(false, start, count); //optimizeme. + } else if (count > 0) { + const t_size * v = m_data.find_nearest_item(start); + if (v == NULL || *v > start+count) return start + count; + return *v; + } else if (count < 0) { + const t_size * v = m_data.find_nearest_item(start); + if (v == NULL || *v < start+count) return start + count; + return *v; + } else return start; + } + + void bit_array_var_impl::set(t_size n,bool val) { + if (val) m_data += n; + else m_data -= n; + } + + + bit_array_flatIndexList::bit_array_flatIndexList() { + m_content.prealloc( 1024 ); + } + + void bit_array_flatIndexList::add( size_t n ) { + m_content.append_single_val( n ); + } + + bool bit_array_flatIndexList::get(t_size n) const { + size_t dummy; + return _find( n, dummy ); + } + t_size bit_array_flatIndexList::find(bool val,t_size start,t_ssize count) const { + if (val == false) { + // unoptimized but not really used + return bit_array::find(val, start, count); + } + + if (count==0) return start; + else if (count<0) { + size_t idx; + if (!_findNearestDown( start, idx ) || m_content[idx] < start+count) return start + count; + return m_content[idx]; + } else { // count > 0 + size_t idx; + if (!_findNearestUp( start, idx ) || m_content[idx] > start+count) return start + count; + return m_content[idx]; + } + } + + bool bit_array_flatIndexList::_findNearestUp( size_t val, size_t & outIdx ) const { + size_t idx; + if (_find( val, idx )) { outIdx = idx; return true; } + // we have a valid outIdx at where the bsearch gave up + PFC_ASSERT ( idx == 0 || m_content [ idx - 1 ] < val ); + PFC_ASSERT ( idx == m_content.get_size() || m_content[ idx ] > val ); + if (idx == m_content.get_size()) return false; + outIdx = idx; + return true; + } + bool bit_array_flatIndexList::_findNearestDown( size_t val, size_t & outIdx ) const { + size_t idx; + if (_find( val, idx )) { outIdx = idx; return true; } + // we have a valid outIdx at where the bsearch gave up + PFC_ASSERT ( idx == 0 || m_content [ idx - 1 ] < val ); + PFC_ASSERT ( idx == m_content.get_size() || m_content[ idx ] > val ); + if (idx == 0) return false; + outIdx = idx - 1; + return true; + } + + void bit_array_flatIndexList::presort() { + pfc::sort_t( m_content, pfc::compare_t< size_t, size_t >, m_content.get_size( ) ); + } + +} \ No newline at end of file diff --git a/SDK/pfc/bit_array.h b/SDK/pfc/bit_array.h new file mode 100644 index 0000000..6016868 --- /dev/null +++ b/SDK/pfc/bit_array.h @@ -0,0 +1,71 @@ +#ifndef _PFC_BIT_ARRAY_H_ +#define _PFC_BIT_ARRAY_H_ +namespace pfc { + //! Bit array interface class, constant version (you can only retrieve values). \n + //! Range of valid indexes depends on the context. When passing a bit_array as a parameter to some code, valid index range must be signaled independently. + class NOVTABLE bit_array { + public: + virtual bool get(t_size n) const = 0; + //! Returns the first occurance of val between start and start+count (excluding start+count), or start+count if not found; count may be negative to search back rather than forward. \n + //! Can be overridden by bit_array implementations for improved speed in specific cases. + virtual t_size find(bool val,t_size start,t_ssize count) const + { + t_ssize d, todo, ptr = start; + if (count==0) return start; + else if (count<0) {d = -1; todo = -count;} + else {d = 1; todo = count;} + while(todo>0 && get(ptr)!=val) {ptr+=d;todo--;} + return ptr; + } + inline bool operator[](t_size n) const {return get(n);} + + t_size calc_count(bool val,t_size start,t_size count,t_size count_max = ~0) const//counts number of vals for start<=n +class bit_array_table_t : public bit_array +{ + const T * data; + t_size count; + bool after; +public: + inline bit_array_table_t(const T * p_data,t_size p_count,bool p_after = false) + : data(p_data), count(p_count), after(p_after) + { + } + + bool get(t_size n) const + { + if (n +class bit_array_var_table_t : public bit_array_var +{ + T * data; + t_size count; + bool after; +public: + inline bit_array_var_table_t(T * p_data,t_size p_count,bool p_after = false) + : data(p_data), count(p_count), after(p_after) + { + } + + bool get(t_size n) const { + if (n bit_array_table; +typedef bit_array_var_table_t bit_array_var_table; + +class bit_array_range : public bit_array +{ + t_size begin,end; + bool state; +public: + bit_array_range(t_size first,t_size count,bool p_state = true) : begin(first), end(first+count), state(p_state) {} + + bool get(t_size n) const + { + bool rv = n>=begin && n0) + return (val>=start && valstart+count) ? val : start+count; + } + else + { + if (start == val) return count>0 ? start+1 : start-1; + else return start; + } + } +}; + +//! Generic variable bit_array implementation. \n +//! Needs to be initialized with requested array size before use. +class bit_array_bittable : public bit_array_var +{ + pfc::array_t m_data; + t_size m_count; +public: + //helpers + template + inline static bool g_get(const t_array & p_array,t_size idx) + { + return !! (p_array[idx>>3] & (1<<(idx&7))); + } + + template + inline static void g_set(t_array & p_array,t_size idx,bool val) + { + unsigned char & dst = p_array[idx>>3]; + unsigned char mask = 1<<(idx&7); + dst = val ? dst|mask : dst&~mask; + } + + inline static t_size g_estimate_size(t_size p_count) {return (p_count+7)>>3;} + + void resize(t_size p_count) + { + t_size old_bytes = g_estimate_size(m_count); + m_count = p_count; + t_size bytes = g_estimate_size(m_count); + m_data.set_size(bytes); + if (bytes > old_bytes) pfc::memset_null_t(m_data.get_ptr()+old_bytes,bytes-old_bytes); + } + + bit_array_bittable(t_size p_count) : m_count(0) {resize(p_count);} + bit_array_bittable(const pfc::bit_array & in, size_t inSize) : m_count() { + resize(inSize); + for(size_t w = in.find_first(true, 0, inSize); w < inSize; w = in.find_next(true, w, inSize) ) { + set( w, true ); + } + } + bit_array_bittable() : m_count() {} + + void set(t_size n,bool val) + { + if (n m_data; + }; + + + //! Specialized implementation of bit_array. \n + //! Indended for scenarios where fast searching for true values in a large list is needed, combined with low footprint regardless of the amount of items. + //! Call add() repeatedly with the true val indexes. If the indexes were not added in increasing order, call presort() when done with adding. + class bit_array_flatIndexList : public bit_array { + public: + bit_array_flatIndexList(); + + void add( size_t n ); + + bool get(t_size n) const; + t_size find(bool val,t_size start,t_ssize count) const; + + void presort(); + + private: + bool _findNearestUp( size_t val, size_t & outIdx ) const; + bool _findNearestDown( size_t val, size_t & outIdx ) const; + bool _find( size_t val, size_t & outIdx ) const { + return pfc::bsearch_simple_inline_t( m_content, m_content.get_size(), val, outIdx); + } + + pfc::array_t< size_t, pfc::alloc_fast > m_content; + }; +} diff --git a/SDK/pfc/bsearch.cpp b/SDK/pfc/bsearch.cpp new file mode 100644 index 0000000..699740f --- /dev/null +++ b/SDK/pfc/bsearch.cpp @@ -0,0 +1,19 @@ +#include "pfc.h" + +//deprecated + +/* +class NOVTABLE bsearch_callback +{ +public: + virtual int test(t_size p_index) const = 0; +}; +*/ + +namespace pfc { + + bool bsearch(t_size p_count, bsearch_callback const & p_callback,t_size & p_result) { + return bsearch_inline_t(p_count,p_callback,p_result); + } + +} \ No newline at end of file diff --git a/SDK/pfc/bsearch.h b/SDK/pfc/bsearch.h new file mode 100644 index 0000000..c2f3cdb --- /dev/null +++ b/SDK/pfc/bsearch.h @@ -0,0 +1,87 @@ +namespace pfc { + + //deprecated + + class NOVTABLE bsearch_callback + { + public: + virtual int test(t_size n) const = 0; + }; + + bool bsearch(t_size p_count, bsearch_callback const & p_callback,t_size & p_result); + + template + class bsearch_callback_impl_simple_t : public bsearch_callback { + public: + int test(t_size p_index) const { + return m_compare(m_container[p_index],m_param); + } + bsearch_callback_impl_simple_t(const t_container & p_container,t_compare p_compare,const t_param & p_param) + : m_container(p_container), m_compare(p_compare), m_param(p_param) + { + } + private: + const t_container & m_container; + t_compare m_compare; + const t_param & m_param; + }; + + template + class bsearch_callback_impl_permutation_t : public bsearch_callback { + public: + int test(t_size p_index) const { + return m_compare(m_container[m_permutation[p_index]],m_param); + } + bsearch_callback_impl_permutation_t(const t_container & p_container,t_compare p_compare,const t_param & p_param,const t_permutation & p_permutation) + : m_container(p_container), m_compare(p_compare), m_param(p_param), m_permutation(p_permutation) + { + } + private: + const t_container & m_container; + t_compare m_compare; + const t_param & m_param; + const t_permutation & m_permutation; + }; + + + template + bool bsearch_t(t_size p_count,const t_container & p_container,t_compare p_compare,const t_param & p_param,t_size & p_index) { + return bsearch( + p_count, + bsearch_callback_impl_simple_t(p_container,p_compare,p_param), + p_index); + } + + template + bool bsearch_permutation_t(t_size p_count,const t_container & p_container,t_compare p_compare,const t_param & p_param,const t_permutation & p_permutation,t_size & p_index) { + t_size index; + if (bsearch( + p_count, + bsearch_callback_impl_permutation_t(p_container,p_compare,p_param,p_permutation), + index)) + { + p_index = p_permutation[index]; + return true; + } else { + return false; + } + } + + template + bool bsearch_range_t(const t_size p_count,const t_container & p_container,t_compare p_compare,const t_param & p_param,t_size & p_range_base,t_size & p_range_count) + { + t_size probe; + if (!bsearch( + p_count, + bsearch_callback_impl_simple_t(p_container,p_compare,p_param), + probe)) return false; + + t_size base = probe, count = 1; + while(base > 0 && p_compare(p_container[base-1],p_param) == 0) {base--; count++;} + while(base + count < p_count && p_compare(p_container[base+count],p_param) == 0) {count++;} + p_range_base = base; + p_range_count = count; + return true; + } + +} diff --git a/SDK/pfc/bsearch_inline.h b/SDK/pfc/bsearch_inline.h new file mode 100644 index 0000000..a3ba80f --- /dev/null +++ b/SDK/pfc/bsearch_inline.h @@ -0,0 +1,48 @@ +namespace pfc { + + //deprecated + +template +inline bool bsearch_inline_t(t_size p_count, const t_callback & p_callback,t_size & p_result) +{ + t_size max = p_count; + t_size min = 0; + t_size ptr; + while(min> 1); + int result = p_callback.test(ptr); + if (result<0) min = ptr + 1; + else if (result>0) max = ptr; + else + { + p_result = ptr; + return true; + } + } + p_result = min; + return false; +} + +template +inline bool bsearch_simple_inline_t(const t_buffer & p_buffer,t_size p_count,t_value const & p_value,t_size & p_result) +{ + t_size max = p_count; + t_size min = 0; + t_size ptr; + while(min> 1); + if (p_value > p_buffer[ptr]) min = ptr + 1; + else if (p_value < p_buffer[ptr]) max = ptr; + else + { + p_result = ptr; + return true; + } + } + p_result = min; + return false; +} + +} diff --git a/SDK/pfc/byte_order_helper.h b/SDK/pfc/byte_order_helper.h new file mode 100644 index 0000000..c28edf1 --- /dev/null +++ b/SDK/pfc/byte_order_helper.h @@ -0,0 +1,243 @@ +#ifndef _PFC_BYTE_ORDER_HELPER_ +#define _PFC_BYTE_ORDER_HELPER_ + +namespace pfc { + void byteswap_raw(void * p_buffer,t_size p_bytes); + + template T byteswap_t(T p_source); + + template<> inline char byteswap_t(char p_source) {return p_source;} + template<> inline unsigned char byteswap_t(unsigned char p_source) {return p_source;} + template<> inline signed char byteswap_t(signed char p_source) {return p_source;} + + template T byteswap_int_t(T p_source) { + enum { width = sizeof(T) }; + typedef typename sized_int_t::t_unsigned tU; + tU in = p_source, out = 0; + for(unsigned walk = 0; walk < width; ++walk) { + out |= ((in >> (walk * 8)) & 0xFF) << ((width - 1 - walk) * 8); + } + return out; + } + +#ifdef _MSC_VER//does this even help with performance/size? + template<> inline wchar_t byteswap_t(wchar_t p_source) {return _byteswap_ushort(p_source);} + + template<> inline short byteswap_t(short p_source) {return _byteswap_ushort(p_source);} + template<> inline unsigned short byteswap_t(unsigned short p_source) {return _byteswap_ushort(p_source);} + + template<> inline int byteswap_t(int p_source) {return _byteswap_ulong(p_source);} + template<> inline unsigned int byteswap_t(unsigned int p_source) {return _byteswap_ulong(p_source);} + + template<> inline long byteswap_t(long p_source) {return _byteswap_ulong(p_source);} + template<> inline unsigned long byteswap_t(unsigned long p_source) {return _byteswap_ulong(p_source);} + + template<> inline long long byteswap_t(long long p_source) {return _byteswap_uint64(p_source);} + template<> inline unsigned long long byteswap_t(unsigned long long p_source) {return _byteswap_uint64(p_source);} +#else + template<> inline wchar_t byteswap_t(wchar_t p_source) {return byteswap_int_t(p_source);} + + template<> inline short byteswap_t(short p_source) {return byteswap_int_t(p_source);} + template<> inline unsigned short byteswap_t(unsigned short p_source) {return byteswap_int_t(p_source);} + + template<> inline int byteswap_t(int p_source) {return byteswap_int_t(p_source);} + template<> inline unsigned int byteswap_t(unsigned int p_source) {return byteswap_int_t(p_source);} + + template<> inline long byteswap_t(long p_source) {return byteswap_int_t(p_source);} + template<> inline unsigned long byteswap_t(unsigned long p_source) {return byteswap_int_t(p_source);} + + template<> inline long long byteswap_t(long long p_source) {return byteswap_int_t(p_source);} + template<> inline unsigned long long byteswap_t(unsigned long long p_source) {return byteswap_int_t(p_source);} +#endif + + template<> inline float byteswap_t(float p_source) { + float ret; + *(t_uint32*) &ret = byteswap_t(*(const t_uint32*)&p_source ); + return ret; + } + + template<> inline double byteswap_t(double p_source) { + double ret; + *(t_uint64*) &ret = byteswap_t(*(const t_uint64*)&p_source ); + return ret; + } + + //blargh at GUID byteswap issue + template<> inline GUID byteswap_t(GUID p_guid) { + GUID ret; + ret.Data1 = pfc::byteswap_t(p_guid.Data1); + ret.Data2 = pfc::byteswap_t(p_guid.Data2); + ret.Data3 = pfc::byteswap_t(p_guid.Data3); + ret.Data4[0] = p_guid.Data4[0]; + ret.Data4[1] = p_guid.Data4[1]; + ret.Data4[2] = p_guid.Data4[2]; + ret.Data4[3] = p_guid.Data4[3]; + ret.Data4[4] = p_guid.Data4[4]; + ret.Data4[5] = p_guid.Data4[5]; + ret.Data4[6] = p_guid.Data4[6]; + ret.Data4[7] = p_guid.Data4[7]; + return ret; + } + + + +}; + +#ifdef _MSC_VER + +#if defined(_M_IX86) || defined(_M_X64) || defined(_M_ARM) +#define PFC_BYTE_ORDER_IS_BIG_ENDIAN 0 +#endif + +#else//_MSC_VER + +#if defined(__APPLE__) +#include +#else +#include +#endif + +#if __BYTE_ORDER == __LITTLE_ENDIAN +#define PFC_BYTE_ORDER_IS_BIG_ENDIAN 0 +#else +#define PFC_BYTE_ORDER_IS_BIG_ENDIAN 1 +#endif + +#endif//_MSC_VER + +#ifdef PFC_BYTE_ORDER_IS_BIG_ENDIAN +#define PFC_BYTE_ORDER_IS_LITTLE_ENDIAN (!(PFC_BYTE_ORDER_IS_BIG_ENDIAN)) +#else +#error please update byte order #defines +#endif + + +namespace pfc { + static const bool byte_order_is_big_endian = !!PFC_BYTE_ORDER_IS_BIG_ENDIAN; + static const bool byte_order_is_little_endian = !!PFC_BYTE_ORDER_IS_LITTLE_ENDIAN; + + template T byteswap_if_be_t(T p_param) {return byte_order_is_big_endian ? byteswap_t(p_param) : p_param;} + template T byteswap_if_le_t(T p_param) {return byte_order_is_little_endian ? byteswap_t(p_param) : p_param;} +} + +namespace byte_order { + +#if PFC_BYTE_ORDER_IS_BIG_ENDIAN//big endian + template inline void order_native_to_le_t(T& param) {param = pfc::byteswap_t(param);} + template inline void order_native_to_be_t(T& param) {} + template inline void order_le_to_native_t(T& param) {param = pfc::byteswap_t(param);} + template inline void order_be_to_native_t(T& param) {} +#else//little endian + template inline void order_native_to_le_t(T& param) {} + template inline void order_native_to_be_t(T& param) {param = pfc::byteswap_t(param);} + template inline void order_le_to_native_t(T& param) {} + template inline void order_be_to_native_t(T& param) {param = pfc::byteswap_t(param);} +#endif +}; + + + +namespace pfc { + template + class __EncodeIntHelper { + public: + inline static void Run(TInt p_value,t_uint8 * p_out) { + *p_out = (t_uint8)(p_value); + __EncodeIntHelper::Run(p_value >> 8,p_out + (IsBigEndian ? -1 : 1)); + } + }; + + template + class __EncodeIntHelper { + public: + inline static void Run(TInt p_value,t_uint8* p_out) { + *p_out = (t_uint8)(p_value); + } + }; + template + class __EncodeIntHelper { + public: + inline static void Run(TInt,t_uint8*) {} + }; + + template + inline void encode_little_endian(t_uint8 * p_buffer,TInt p_value) { + __EncodeIntHelper::Run(p_value,p_buffer); + } + template + inline void encode_big_endian(t_uint8 * p_buffer,TInt p_value) { + __EncodeIntHelper::Run(p_value,p_buffer + (sizeof(TInt) - 1)); + } + + + template + class __DecodeIntHelper { + public: + inline static TInt Run(const t_uint8 * p_in) { + return (__DecodeIntHelper::Run(p_in + (IsBigEndian ? -1 : 1)) << 8) + *p_in; + } + }; + + template + class __DecodeIntHelper { + public: + inline static TInt Run(const t_uint8* p_in) {return *p_in;} + }; + + template + class __DecodeIntHelper { + public: + inline static TInt Run(const t_uint8*) {return 0;} + }; + + template + inline void decode_little_endian(TInt & p_out,const t_uint8 * p_buffer) { + p_out = __DecodeIntHelper::Run(p_buffer); + } + + template + inline void decode_big_endian(TInt & p_out,const t_uint8 * p_buffer) { + p_out = __DecodeIntHelper::Run(p_buffer + (sizeof(TInt) - 1)); + } + + template + inline TInt decode_little_endian(const t_uint8 * p_buffer) { + TInt temp; + decode_little_endian(temp,p_buffer); + return temp; + } + + template + inline TInt decode_big_endian(const t_uint8 * p_buffer) { + TInt temp; + decode_big_endian(temp,p_buffer); + return temp; + } + + template + inline void decode_endian(TInt & p_out,const t_uint8 * p_buffer) { + if (IsBigEndian) decode_big_endian(p_out,p_buffer); + else decode_little_endian(p_out,p_buffer); + } + template + inline void encode_endian(t_uint8 * p_buffer,TInt p_in) { + if (IsBigEndian) encode_big_endian(p_in,p_buffer); + else encode_little_endian(p_in,p_buffer); + } + + + + template + inline void reverse_bytes(t_uint8 * p_buffer) { + pfc::swap_t(p_buffer[0],p_buffer[width-1]); + reverse_bytes(p_buffer+1); + } + + template<> inline void reverse_bytes<1>(t_uint8 * p_buffer) { } + template<> inline void reverse_bytes<0>(t_uint8 * p_buffer) { } + +} + + + +#endif diff --git a/SDK/pfc/chain_list_v2.h b/SDK/pfc/chain_list_v2.h new file mode 100644 index 0000000..f67e241 --- /dev/null +++ b/SDK/pfc/chain_list_v2.h @@ -0,0 +1,274 @@ +namespace pfc { + + template + class __chain_list_elem : public _list_node { + public: + typedef _list_node t_node; + TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD_WITH_INITIALIZER(__chain_list_elem,t_node, {m_prev = m_next = NULL;}); + + typedef __chain_list_elem t_self; + + t_self * m_prev, * m_next; + + t_node * prev() throw() {return m_prev;} + t_node * next() throw() {return m_next;} + + //helper wrappers + void add_ref() throw() {this->refcount_add_ref();} + void release() throw() {this->refcount_release();} + //workaround for cross-list-relinking case - never actually deletes p_elem + void __release_temporary() throw() {this->_refcount_release_temporary();} + }; + + //! Differences between chain_list_v2_t<> and old chain_list_t<>: \n + //! Iterators pointing to removed items as well as to items belonging to no longer existing list objects remain valid but they're no longer walkable - as if the referenced item was the only item in the list. The old class invalidated iterators on deletion instead. + template + class chain_list_v2_t { + public: + typedef _t_item t_item; + typedef chain_list_v2_t t_self; + typedef ::pfc::iterator iterator; + typedef ::pfc::const_iterator const_iterator; + typedef __chain_list_elem t_elem; + + chain_list_v2_t() : m_first(), m_last(), m_count() {} + chain_list_v2_t(const t_self & p_source) : m_first(), m_last(), m_count() { + try { + *this = p_source; + } catch(...) { + remove_all(); + throw; + } + } + template void _set(const t_in & in) { + remove_all(); _add(in); + } + template void _add(const t_in & in) { + for(typename t_in::const_iterator iter = in.first(); iter.is_valid(); ++in) add_item(*iter); + } + template t_self & operator=(const t_in & in) {_set(in); return *this;} + + t_self & operator=(const t_self & p_other) { + remove_all(); + for(t_elem * walk = p_other.m_first; walk != NULL; walk = walk->m_next) { + add_item(walk->m_content); + } + return *this; + } + // templated constructors = spawn of satan + // template chain_list_v2_t(const t_other & in) { try {_add(in);} catch(...) {remove_all(); throw;} } + + t_size get_count() const {return m_count;} + + iterator first() {return iterator(m_first);} + iterator last() {return iterator(m_last);} + const_iterator first() const {return const_iterator(m_first);} + const_iterator last() const {return const_iterator(m_last);} + + void remove_single(const_iterator const & p_iter) { + PFC_ASSERT(p_iter.is_valid()); + __unlink(_elem(p_iter)); + } + + void remove(const_iterator const & p_iter) { + PFC_ASSERT(p_iter.is_valid()); + __unlink(_elem(p_iter)); + } + + void remove_all() throw() { + while(m_first != NULL) __unlink(m_first); + PFC_ASSERT(m_count == 0); + } + void remove_range(const_iterator const & p_from,const_iterator const & p_to) { + for(t_elem * walk = _elem(p_from);;) { + if (walk == NULL) {PFC_ASSERT(!"Should not get here"); break;}//should not happen unless there is a bug in calling code + t_elem * next = walk->m_next; + __unlink(walk); + if (walk == _elem(p_to)) break; + walk = next; + } + } + + template void enumerate(t_callback & p_callback) const {__enumerate_chain(m_first,p_callback);} + template void enumerate(t_callback & p_callback) {__enumerate_chain(m_first,p_callback);} + + template bool remove_item(const t_source & p_item) { + t_elem * elem; + if (__find(elem,p_item)) { + __unlink(elem); + return true; + } else { + return false; + } + } + + ~chain_list_v2_t() {remove_all();} + + template + inline void add_item(const t_source & p_source) { + __link_last(new t_elem(p_source)); + } + template + inline t_self & operator+=(const t_source & p_source) { + add_item(p_source); return *this; + } + iterator insert_last() {return __link_last(new t_elem);} + iterator insert_first() {return __link_first(new t_elem);} + iterator insert_after(const_iterator const & p_iter) {return __link_next(_elem(p_iter),new t_elem);} + iterator insert_before(const_iterator const & p_iter) {return __link_prev(_elem(p_iter),new t_elem);} + template iterator insert_last(const t_source & p_source) {return __link_last(new t_elem(p_source));} + template iterator insert_first(const t_source & p_source) {return __link_first(new t_elem(p_source));} + template iterator insert_after(const_iterator const & p_iter,const t_source & p_source) {return __link_next(_elem(p_iter),new t_elem(p_source));} + template iterator insert_before(const_iterator const & p_iter,const t_source & p_source) {return __link_prev(_elem(p_iter),new t_elem(p_source));} + + template const_iterator find_item(const t_source & p_item) const { + t_elem * elem; + if (!__find(elem,p_item)) return const_iterator(); + return const_iterator(elem); + } + + template iterator find_item(const t_source & p_item) { + t_elem * elem; + if (!__find(elem,p_item)) return iterator(); + return iterator(elem); + } + + template bool have_item(const t_source & p_item) const { + t_elem * dummy; + return __find(dummy,p_item); + } + template void set_single(const t_source & p_item) { + remove_all(); add_item(p_item); + } + + //! Slow! + const_iterator by_index(t_size p_index) const {return __by_index(p_index);} + //! Slow! + iterator by_index(t_size p_index) {return __by_index(p_index);} + + t_self & operator<<(t_self & p_other) { + while(p_other.m_first != NULL) { + __link_last( p_other.__unlink_temporary(p_other.m_first) ); + } + return *this; + } + t_self & operator>>(t_self & p_other) { + while(m_last != NULL) { + p_other.__link_first(__unlink_temporary(m_last)); + } + return p_other; + } + //! Links an object that has been unlinked from another list. Unsafe. + void _link_last(const_iterator const& iter) { + PFC_ASSERT(iter.is_valid()); + PFC_ASSERT( _elem(iter)->m_prev == NULL && _elem(iter)->m_next == NULL ); + __link_last(_elem(iter)); + } + //! Links an object that has been unlinked from another list. Unsafe. + void _link_first(const_iterator const& iter) { + PFC_ASSERT(iter.is_valid()); + PFC_ASSERT( _elem(iter)->m_prev == NULL && _elem(iter)->m_next == NULL ); + __link_first(_elem(iter)); + } + private: + static t_elem * _elem(const_iterator const & iter) { + return static_cast(iter._node()); + } + t_elem * __by_index(t_size p_index) const { + t_elem * walk = m_first; + while(p_index > 0 && walk != NULL) { + p_index--; + walk = walk->m_next; + } + return walk; + } + template + static void __enumerate_chain(t_elemwalk * p_elem,t_callback & p_callback) { + t_elemwalk * walk = p_elem; + while(walk != NULL) { + p_callback(walk->m_content); + walk = walk->m_next; + } + } + + template bool __find(t_elem * & p_elem,const t_source & p_item) const { + for(t_elem * walk = m_first; walk != NULL; walk = walk->m_next) { + if (walk->m_content == p_item) { + p_elem = walk; return true; + } + } + return false; + } + + void __unlink_helper(t_elem * p_elem) throw() { + (p_elem->m_prev == NULL ? m_first : p_elem->m_prev->m_next) = p_elem->m_next; + (p_elem->m_next == NULL ? m_last : p_elem->m_next->m_prev) = p_elem->m_prev; + p_elem->m_next = p_elem->m_prev = NULL; + } + + //workaround for cross-list-relinking case - never actually deletes p_elem + t_elem * __unlink_temporary(t_elem * p_elem) throw() { + __unlink_helper(p_elem); + --m_count; p_elem->__release_temporary(); + return p_elem; + } + + t_elem * __unlink(t_elem * p_elem) throw() { + __unlink_helper(p_elem); + --m_count; p_elem->release(); + return p_elem; + } + void __on_link(t_elem * p_elem) throw() { + p_elem->add_ref(); ++m_count; + } + t_elem * __link_first(t_elem * p_elem) throw() { + __on_link(p_elem); + p_elem->m_next = m_first; + p_elem->m_prev = NULL; + (m_first == NULL ? m_last : m_first->m_prev) = p_elem; + m_first = p_elem; + return p_elem; + } + t_elem * __link_last(t_elem * p_elem) throw() { + __on_link(p_elem); + p_elem->m_prev = m_last; + p_elem->m_next = NULL; + (m_last == NULL ? m_first : m_last->m_next) = p_elem; + m_last = p_elem; + return p_elem; + } + t_elem * __link_next(t_elem * p_prev,t_elem * p_elem) throw() { + __on_link(p_elem); + p_elem->m_prev = p_prev; + p_elem->m_next = p_prev->m_next; + (p_prev->m_next != NULL ? p_prev->m_next->m_prev : m_last) = p_elem; + p_prev->m_next = p_elem; + return p_elem; + } + t_elem * __link_prev(t_elem * p_next,t_elem * p_elem) throw() { + __on_link(p_elem); + p_elem->m_next = p_next; + p_elem->m_prev = p_next->m_prev; + (p_next->m_prev != NULL ? p_next->m_prev->m_next : m_first) = p_elem; + p_next->m_prev = p_elem; + return p_elem; + } + t_elem * m_first, * m_last; + t_size m_count; + }; + + + template class traits_t > : public traits_default_movable {}; + + class __chain_list_iterator_traits : public traits_default_movable { + public: + enum { + constructor_may_fail = false + }; + }; + + template class traits_t > : public traits_t > > {}; + + template class traits_t > : public traits_t > {}; + +}//namespace pfc diff --git a/SDK/pfc/com_ptr_t.h b/SDK/pfc/com_ptr_t.h new file mode 100644 index 0000000..ed9b847 --- /dev/null +++ b/SDK/pfc/com_ptr_t.h @@ -0,0 +1,83 @@ +#ifdef _WIN32 +namespace pfc { + + template static void _COM_AddRef(what * ptr) { + if (ptr != NULL) ptr->AddRef(); + } + template static void _COM_Release(what * ptr) { + if (ptr != NULL) ptr->Release(); + } + + template + class com_ptr_t { + public: + typedef com_ptr_t t_self; + + inline com_ptr_t() throw() : m_ptr() {} + template inline com_ptr_t(source * p_ptr) throw() : m_ptr(p_ptr) {_COM_AddRef(m_ptr);} + inline com_ptr_t(const t_self & p_source) throw() : m_ptr(p_source.m_ptr) {_COM_AddRef(m_ptr);} + template inline com_ptr_t(const com_ptr_t & p_source) throw() : m_ptr(p_source.get_ptr()) {_COM_AddRef(m_ptr);} + + inline ~com_ptr_t() throw() {_COM_Release(m_ptr);} + + inline void copy(T * p_ptr) throw() { + _COM_Release(m_ptr); + m_ptr = p_ptr; + _COM_AddRef(m_ptr); + } + + template inline void copy(const com_ptr_t & p_source) throw() {copy(p_source.get_ptr());} + + inline void attach(T * p_ptr) throw() { + _COM_Release(m_ptr); + m_ptr = p_ptr; + } + + inline const t_self & operator=(const t_self & p_source) throw() {copy(p_source); return *this;} + inline const t_self & operator=(T* p_source) throw() {copy(p_source); return *this;} + template inline const t_self & operator=(const com_ptr_t & p_source) throw() {copy(p_source); return *this;} + template inline const t_self & operator=(source * p_ptr) throw() {copy(p_ptr); return *this;} + + inline void release() throw() { + _COM_Release(m_ptr); + m_ptr = NULL; + } + + + inline T* operator->() const throw() {PFC_ASSERT(m_ptr);return m_ptr;} + + inline T* get_ptr() const throw() {return m_ptr;} + + inline T* duplicate_ptr() const throw() //should not be used ! temporary ! + { + _COM_AddRef(m_ptr); + return m_ptr; + } + + inline T* detach() throw() { + return replace_null_t(m_ptr); + } + + inline bool is_valid() const throw() {return m_ptr != 0;} + inline bool is_empty() const throw() {return m_ptr == 0;} + + inline bool operator==(const com_ptr_t & p_item) const throw() {return m_ptr == p_item.m_ptr;} + inline bool operator!=(const com_ptr_t & p_item) const throw() {return m_ptr != p_item.m_ptr;} + inline bool operator>(const com_ptr_t & p_item) const throw() {return m_ptr > p_item.m_ptr;} + inline bool operator<(const com_ptr_t & p_item) const throw() {return m_ptr < p_item.m_ptr;} + + inline static void g_swap(com_ptr_t & item1, com_ptr_t & item2) throw() { + pfc::swap_t(item1.m_ptr,item2.m_ptr); + } + + inline T** receive_ptr() throw() {release();return &m_ptr;} + inline void** receive_void_ptr() throw() {return (void**) receive_ptr();} + + inline t_self & operator<<(t_self & p_source) throw() {attach(p_source.detach());return *this;} + inline t_self & operator>>(t_self & p_dest) throw() {p_dest.attach(detach());return *this;} + private: + T* m_ptr; + }; + +} +#endif diff --git a/SDK/pfc/cpuid.cpp b/SDK/pfc/cpuid.cpp new file mode 100644 index 0000000..b98c34a --- /dev/null +++ b/SDK/pfc/cpuid.cpp @@ -0,0 +1,57 @@ +#include "pfc.h" + + +#if PFC_HAVE_CPUID + +namespace pfc { + bool query_cpu_feature_set(unsigned p_value) { +#ifdef _MSC_VER + __try { +#endif + if (p_value & (CPU_HAVE_SSE | CPU_HAVE_SSE2 | CPU_HAVE_SSE3 | CPU_HAVE_SSSE3 | CPU_HAVE_SSE41 | CPU_HAVE_SSE42)) { + int buffer[4]; + __cpuid(buffer,1); + if (p_value & CPU_HAVE_SSE) { + if ((buffer[3]&(1<<25)) == 0) return false; + } + if (p_value & CPU_HAVE_SSE2) { + if ((buffer[3]&(1<<26)) == 0) return false; + } + if (p_value & CPU_HAVE_SSE3) { + if ((buffer[2]&(1<<0)) == 0) return false; + } + if (p_value & CPU_HAVE_SSSE3) { + if ((buffer[2]&(1<<9)) == 0) return false; + } + if (p_value & CPU_HAVE_SSE41) { + if ((buffer[2]&(1<<19)) == 0) return false; + } + if (p_value & CPU_HAVE_SSE42) { + if ((buffer[2]&(1<<20)) == 0) return false; + } + } + #ifdef _M_IX86 + if (p_value & (CPU_HAVE_3DNOW_EX | CPU_HAVE_3DNOW)) { + int buffer_amd[4]; + __cpuid(buffer_amd,0x80000000); + if ((unsigned)buffer_amd[0] < 0x80000001) return false; + __cpuid(buffer_amd,0x80000001); + + if (p_value & CPU_HAVE_3DNOW) { + if ((buffer_amd[3]&(1<<31)) == 0) return false; + } + if (p_value & CPU_HAVE_3DNOW_EX) { + if ((buffer_amd[3]&(1<<30)) == 0) return false; + } + } + #endif + return true; +#ifdef _MSC_VER + } __except(1) { + return false; + } +#endif + } +} + +#endif diff --git a/SDK/pfc/cpuid.h b/SDK/pfc/cpuid.h new file mode 100644 index 0000000..b8e056e --- /dev/null +++ b/SDK/pfc/cpuid.h @@ -0,0 +1,23 @@ + +// CPUID stuff supported only on MSVC for now, irrelevant for non x86 +#if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) +#define PFC_HAVE_CPUID 1 +namespace pfc { + enum { + CPU_HAVE_3DNOW = 1 << 0, + CPU_HAVE_3DNOW_EX = 1 << 1, + CPU_HAVE_SSE = 1 << 2, + CPU_HAVE_SSE2 = 1 << 3, + CPU_HAVE_SSE3 = 1 << 4, + CPU_HAVE_SSSE3 = 1 << 5, + CPU_HAVE_SSE41 = 1 << 6, + CPU_HAVE_SSE42 = 1 << 7, + }; + + bool query_cpu_feature_set(unsigned p_value); +}; +#endif + +#ifndef PFC_HAVE_CPUID +#define PFC_HAVE_CPUID 0 +#endif \ No newline at end of file diff --git a/SDK/pfc/event.h b/SDK/pfc/event.h new file mode 100644 index 0000000..dee0d73 --- /dev/null +++ b/SDK/pfc/event.h @@ -0,0 +1,19 @@ +namespace pfc { +#ifdef _WIN32 + + typedef HANDLE eventHandle_t; + + class event : public win32_event { + public: + event() { create(true, false); } + + HANDLE get_handle() const {return win32_event::get();} + }; +#else + + typedef int eventHandle_t; + + typedef nix_event event; + +#endif +} diff --git a/SDK/pfc/filehandle.cpp b/SDK/pfc/filehandle.cpp new file mode 100644 index 0000000..0da7f3a --- /dev/null +++ b/SDK/pfc/filehandle.cpp @@ -0,0 +1,33 @@ +#include "pfc.h" + +#ifndef _WIN32 +#include +#endif + +namespace pfc { +void fileHandleClose( fileHandle_t h ) { + if (h == fileHandleInvalid) return; +#ifdef _WIN32 + CloseHandle( h ); +#else + close( h ); +#endif +} + +fileHandle_t fileHandleDup( fileHandle_t h ) { +#ifdef _WIN32 + auto proc = GetCurrentProcess(); + HANDLE out; + if (!DuplicateHandle ( proc, h, proc, &out, 0, FALSE, DUPLICATE_SAME_ACCESS )) return fileHandleInvalid; + return out; +#else + return dup( h ); +#endif +} + +void fileHandle::close() { + fileHandleClose( h ); + clear(); +} + +} \ No newline at end of file diff --git a/SDK/pfc/filehandle.h b/SDK/pfc/filehandle.h new file mode 100644 index 0000000..26e5ac1 --- /dev/null +++ b/SDK/pfc/filehandle.h @@ -0,0 +1,29 @@ +namespace pfc { +#ifdef _WIN32 + typedef HANDLE fileHandle_t; + const fileHandle_t fileHandleInvalid = INVALID_HANDLE_VALUE; +#else + typedef int fileHandle_t; + const fileHandle_t fileHandleInvalid = -1; +#endif + + void fileHandleClose( fileHandle_t h ); + fileHandle_t fileHandleDup( fileHandle_t h ); + + class fileHandle { + public: + fileHandle( fileHandle_t val ) : h(val) {} + fileHandle() : h ( fileHandleInvalid ) {} + ~fileHandle() { close(); } + fileHandle( fileHandle && other ) { h = other.h; other.clear(); } + void operator=( fileHandle && other ) { close(); h = other.h; other.clear(); } + void operator=( fileHandle_t other ) { close(); h = other; } + void close(); + void clear() { h = fileHandleInvalid; } + bool isValid() { return h != fileHandleInvalid; } + fileHandle_t h; + private: + fileHandle( const fileHandle & ); + void operator=( const fileHandle & ); + }; +} diff --git a/SDK/pfc/guid.cpp b/SDK/pfc/guid.cpp new file mode 100644 index 0000000..fd45549 --- /dev/null +++ b/SDK/pfc/guid.cpp @@ -0,0 +1,176 @@ +#include "pfc.h" + +#ifdef _WIN32 +#include +#endif + +/* +6B29FC40-CA47-1067-B31D-00DD010662DA +. +typedef struct _GUID { // size is 16 + DWORD Data1; + WORD Data2; + WORD Data3; + BYTE Data4[8]; +} GUID; + +// {B296CF59-4D51-466f-8E0B-E57D3F91D908} +static const GUID <> = +{ 0xb296cf59, 0x4d51, 0x466f, { 0x8e, 0xb, 0xe5, 0x7d, 0x3f, 0x91, 0xd9, 0x8 } }; + +*/ +namespace { + class _GUID_from_text : public GUID + { + unsigned read_hex(char c); + unsigned read_byte(const char * ptr); + unsigned read_word(const char * ptr); + unsigned read_dword(const char * ptr); + void read_bytes(unsigned char * out,unsigned num,const char * ptr); + + public: + _GUID_from_text(const char * text); + }; + + unsigned _GUID_from_text::read_hex(char c) + { + if (c>='0' && c<='9') return (unsigned)c - '0'; + else if (c>='a' && c<='f') return 0xa + (unsigned)c - 'a'; + else if (c>='A' && c<='F') return 0xa + (unsigned)c - 'A'; + else return 0; + } + + unsigned _GUID_from_text::read_byte(const char * ptr) + { + return (read_hex(ptr[0])<<4) | read_hex(ptr[1]); + } + unsigned _GUID_from_text::read_word(const char * ptr) + { + return (read_byte(ptr)<<8) | read_byte(ptr+2); + } + + unsigned _GUID_from_text::read_dword(const char * ptr) + { + return (read_word(ptr)<<16) | read_word(ptr+4); + } + + void _GUID_from_text::read_bytes(uint8_t * out,unsigned num,const char * ptr) + { + for(;num;num--) + { + *out = read_byte(ptr); + out++;ptr+=2; + } + } + + + _GUID_from_text::_GUID_from_text(const char * text) + { + if (*text=='{') text++; + const char * max; + + { + const char * t = strchr(text,'}'); + if (t) max = t; + else max = text + strlen(text); + } + + (GUID)*this = pfc::guid_null; + + + do { + if (text+8>max) break; + Data1 = read_dword(text); + text += 8; + while(*text=='-') text++; + if (text+4>max) break; + Data2 = read_word(text); + text += 4; + while(*text=='-') text++; + if (text+4>max) break; + Data3 = read_word(text); + text += 4; + while(*text=='-') text++; + if (text+4>max) break; + read_bytes(Data4,2,text); + text += 4; + while(*text=='-') text++; + if (text+12>max) break; + read_bytes(Data4+2,6,text); + } while(false); + } +} + +namespace pfc { + +GUID GUID_from_text(const char * text) { + return _GUID_from_text( text ); +} + +static inline char print_hex_digit(unsigned val) +{ + static const char table[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; + PFC_ASSERT((val & ~0xF) == 0); + return table[val]; +} + +static void print_hex(unsigned val,char * &out,unsigned bytes) +{ + unsigned n; + for(n=0;n> ((bytes - 1 - n) << 3)) & 0xFF); + *(out++) = print_hex_digit( c >> 4 ); + *(out++) = print_hex_digit( c & 0xF ); + } + *out = 0; +} + + +print_guid::print_guid(const GUID & p_guid) +{ + char * out = m_data; + print_hex(p_guid.Data1,out,4); + *(out++) = '-'; + print_hex(p_guid.Data2,out,2); + *(out++) = '-'; + print_hex(p_guid.Data3,out,2); + *(out++) = '-'; + print_hex(p_guid.Data4[0],out,1); + print_hex(p_guid.Data4[1],out,1); + *(out++) = '-'; + print_hex(p_guid.Data4[2],out,1); + print_hex(p_guid.Data4[3],out,1); + print_hex(p_guid.Data4[4],out,1); + print_hex(p_guid.Data4[5],out,1); + print_hex(p_guid.Data4[6],out,1); + print_hex(p_guid.Data4[7],out,1); + *out = 0; +} + + +void print_hex_raw(const void * buffer,unsigned bytes,char * p_out) +{ + char * out = p_out; + const unsigned char * in = (const unsigned char *) buffer; + unsigned n; + for(n=0;n inline int compare_t(const GUID & p_item1,const GUID & p_item2) {return guid_compare(p_item1,p_item2);} + + extern const GUID guid_null; + + void print_hex_raw(const void * buffer,unsigned bytes,char * p_out); + + inline GUID makeGUID(t_uint32 Data1, t_uint16 Data2, t_uint16 Data3, t_uint8 Data4_1, t_uint8 Data4_2, t_uint8 Data4_3, t_uint8 Data4_4, t_uint8 Data4_5, t_uint8 Data4_6, t_uint8 Data4_7, t_uint8 Data4_8) { + GUID guid = { Data1, Data2, Data3, {Data4_1, Data4_2, Data4_3, Data4_4, Data4_5, Data4_6, Data4_7, Data4_8 } }; + return guid; + } + inline GUID xorGUID(const GUID & v1, const GUID & v2) { + GUID temp; memxor(&temp, &v1, &v2, sizeof(GUID)); return temp; + } + + class format_guid_cpp : public pfc::string_formatter { + public: + format_guid_cpp(const GUID & guid) { + *this << "{0x" << pfc::format_hex(guid.Data1,8) << ", 0x" << pfc::format_hex(guid.Data2, 4) << ", 0x" << pfc::format_hex(guid.Data3,4) << ", {0x" << pfc::format_hex(guid.Data4[0],2); + for(int n = 1; n < 8; ++n) { + *this << ", 0x" << pfc::format_hex(guid.Data4[n],2); + } + *this << "}}"; + } + }; + + GUID createGUID(); +} + + +#endif diff --git a/SDK/pfc/instance_tracker.h b/SDK/pfc/instance_tracker.h new file mode 100644 index 0000000..e0e952f --- /dev/null +++ b/SDK/pfc/instance_tracker.h @@ -0,0 +1,49 @@ +namespace pfc { + template + class instance_tracker_server_t { + public: + void add(t_object * p_object) { + m_list.add_item(p_object); + } + void remove(t_object * p_object) { + m_list.remove_item(p_object); + } + + t_size get_count() const {return m_list.get_count();} + t_object * get_item(t_size p_index) {return m_list[p_index];} + t_object * operator[](t_size p_index) {return m_list[p_index];} + + private: + ptr_list_hybrid_t m_list; + }; + + + template & p_server> + class instance_tracker_client_t { + public: + instance_tracker_client_t(t_object* p_ptr) : m_ptr(NULL), m_added(false) {initialize(p_ptr);} + instance_tracker_client_t() : m_ptr(NULL), m_added(false) {} + + void initialize(t_object * p_ptr) { + uninitialize(); + p_server.add(p_ptr); + m_ptr = p_ptr; + m_added = true; + } + + void uninitialize() { + if (m_added) { + p_server.remove(m_ptr); + m_ptr = NULL; + m_added = false; + } + } + + ~instance_tracker_client_t() { + uninitialize(); + } + private: + bool m_added; + t_object * m_ptr; + }; +} \ No newline at end of file diff --git a/SDK/pfc/int_types.h b/SDK/pfc/int_types.h new file mode 100644 index 0000000..b0ea307 --- /dev/null +++ b/SDK/pfc/int_types.h @@ -0,0 +1,93 @@ +#include +typedef int64_t t_int64; +typedef uint64_t t_uint64; +typedef int32_t t_int32; +typedef uint32_t t_uint32; +typedef int16_t t_int16; +typedef uint16_t t_uint16; +typedef int8_t t_int8; +typedef uint8_t t_uint8; + +typedef int t_int; +typedef unsigned int t_uint; + +typedef float t_float32; +typedef double t_float64; + + + +namespace pfc { + template + class sized_int_t; + + template<> class sized_int_t<1> { + public: + typedef t_uint8 t_unsigned; + typedef t_int8 t_signed; + }; + + template<> class sized_int_t<2> { + public: + typedef t_uint16 t_unsigned; + typedef t_int16 t_signed; + }; + + template<> class sized_int_t<4> { + public: + typedef t_uint32 t_unsigned; + typedef t_int32 t_signed; + }; + + template<> class sized_int_t<8> { + public: + typedef t_uint64 t_unsigned; + typedef t_int64 t_signed; + }; +} + +typedef size_t t_size; +typedef pfc::sized_int_t< sizeof(size_t) >::t_signed t_ssize; + + +inline t_size MulDiv_Size(t_size x,t_size y,t_size z) {return (t_size) ( ((t_uint64)x * (t_uint64)y) / (t_uint64)z );} + +#define pfc_infinite (~0) + +namespace pfc { + const t_uint16 infinite16 = (t_uint16)(~0); + const t_uint32 infinite32 = (t_uint32)(~0); + const t_uint64 infinite64 = (t_uint64)(~0); + const t_size infinite_size = (t_size)(~0); + + template class int_specs_t; + + template + class int_specs_signed_t { + public: + inline static T get_min() {return ((T)1<<(sizeof(T)*8-1));} + inline static T get_max() {return ~((T)1<<(sizeof(T)*8-1));} + enum {is_signed = true}; + }; + + template + class int_specs_unsigned_t { + public: + inline static T get_min() {return (T)0;} + inline static T get_max() {return (T)~0;} + enum {is_signed = false}; + }; + + template<> class int_specs_t : public int_specs_signed_t {}; + template<> class int_specs_t : public int_specs_unsigned_t {}; + template<> class int_specs_t : public int_specs_signed_t {}; + template<> class int_specs_t : public int_specs_unsigned_t {}; + template<> class int_specs_t : public int_specs_signed_t {}; + template<> class int_specs_t : public int_specs_unsigned_t {}; + template<> class int_specs_t : public int_specs_signed_t {}; + template<> class int_specs_t : public int_specs_unsigned_t {}; + template<> class int_specs_t : public int_specs_signed_t {}; + template<> class int_specs_t : public int_specs_unsigned_t {}; + + template<> class int_specs_t : public int_specs_unsigned_t {}; + +}; diff --git a/SDK/pfc/iterators.h b/SDK/pfc/iterators.h new file mode 100644 index 0000000..0cc203d --- /dev/null +++ b/SDK/pfc/iterators.h @@ -0,0 +1,115 @@ +namespace pfc { + //! Base class for list nodes. Implemented by list implementers. + template class _list_node : public refcounted_object_root { + public: + typedef _list_node t_self; + + TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(_list_node,m_content) + + t_item m_content; + + virtual t_self * prev() throw() {return NULL;} + virtual t_self * next() throw() {return NULL;} + + t_self * walk(bool forward) throw() {return forward ? next() : prev();} + }; + + template class const_iterator { + public: + typedef _list_node t_node; + typedef refcounted_object_ptr_t t_nodeptr; + typedef const_iterator t_self; + + bool is_empty() const throw() {return m_content.is_empty();} + bool is_valid() const throw() {return m_content.is_valid();} + void invalidate() throw() {m_content = NULL;} + + void walk(bool forward) throw() {m_content = m_content->walk(forward);} + void prev() throw() {m_content = m_content->prev();} + void next() throw() {m_content = m_content->next();} + + //! For internal use / list implementations only! Do not call! + t_node* _node() const throw() {return m_content.get_ptr();} + + const_iterator() {} + const_iterator(t_node* source) : m_content(source) {} + const_iterator(t_nodeptr const & source) : m_content(source) {} + const_iterator(t_self const & other) : m_content(other.m_content) {} + const_iterator(t_self && other) : m_content(std::move(other.m_content)) {} + + t_self const & operator=(t_self const & other) {m_content = other.m_content; return *this;} + t_self const & operator=(t_self && other) {m_content = std::move(other.m_content); return *this;} + + const t_item& operator*() const throw() {return m_content->m_content;} + const t_item* operator->() const throw() {return &m_content->m_content;} + + const t_self & operator++() throw() {this->next(); return *this;} + const t_self & operator--() throw() {this->prev(); return *this;} + t_self operator++(int) throw() {t_self old = *this; this->next(); return old;} + t_self operator--(int) throw() {t_self old = *this; this->prev(); return old;} + + bool operator==(const t_self & other) const throw() {return this->m_content == other.m_content;} + bool operator!=(const t_self & other) const throw() {return this->m_content != other.m_content;} + protected: + t_nodeptr m_content; + }; + template class iterator : public const_iterator { + public: + typedef const_iterator t_selfConst; + typedef iterator t_self; + typedef _list_node t_node; + typedef refcounted_object_ptr_t t_nodeptr; + + iterator() {} + iterator(t_node* source) : t_selfConst(source) {} + iterator(t_nodeptr const & source) : t_selfConst(source) {} + iterator(t_self const & other) : t_selfConst(other) {} + iterator(t_self && other) : t_selfConst(std::move(other)) {} + + t_self const & operator=(t_self const & other) {this->m_content = other.m_content; return *this;} + t_self const & operator=(t_self && other) {this->m_content = std::move(other.m_content); return *this;} + + t_item& operator*() const throw() {return this->m_content->m_content;} + t_item* operator->() const throw() {return &this->m_content->m_content;} + + const t_self & operator++() throw() {this->next(); return *this;} + const t_self & operator--() throw() {this->prev(); return *this;} + t_self operator++(int) throw() {t_self old = *this; this->next(); return old;} + t_self operator--(int) throw() {t_self old = *this; this->prev(); return old;} + + bool operator==(const t_self & other) const throw() {return this->m_content == other.m_content;} + bool operator!=(const t_self & other) const throw() {return this->m_content != other.m_content;} + }; + + template + class comparator_list { + public: + template + static int compare(const t_list1 & p_list1, const t_list2 & p_list2) { + typename t_list1::const_iterator iter1 = p_list1.first(); + typename t_list2::const_iterator iter2 = p_list2.first(); + for(;;) { + if (iter1.is_empty() && iter2.is_empty()) return 0; + else if (iter1.is_empty()) return -1; + else if (iter2.is_empty()) return 1; + else { + int state = t_comparator::compare(*iter1,*iter2); + if (state != 0) return state; + } + ++iter1; ++iter2; + } + } + }; + + template + static bool listEquals(const t_list1 & p_list1, const t_list2 & p_list2) { + typename t_list1::const_iterator iter1 = p_list1.first(); + typename t_list2::const_iterator iter2 = p_list2.first(); + for(;;) { + if (iter1.is_empty() && iter2.is_empty()) return true; + else if (iter1.is_empty() || iter2.is_empty()) return false; + else if (*iter1 != *iter2) return false; + ++iter1; ++iter2; + } + } +} diff --git a/SDK/pfc/list.h b/SDK/pfc/list.h new file mode 100644 index 0000000..43e3ba4 --- /dev/null +++ b/SDK/pfc/list.h @@ -0,0 +1,642 @@ +#ifndef _PFC_LIST_H_ +#define _PFC_LIST_H_ + +namespace pfc { + +template +class NOVTABLE list_base_const_t { +private: typedef list_base_const_t t_self; +public: + typedef T t_item; + virtual t_size get_count() const = 0; + virtual void get_item_ex(T& p_out, t_size n) const = 0; + + inline t_size get_size() const {return get_count();} + + inline T get_item(t_size n) const {T temp; get_item_ex(temp,n); return std::move(temp);} + inline T operator[](t_size n) const {T temp; get_item_ex(temp,n); return std::move(temp);} + + template + t_size find_duplicates_sorted_t(t_compare p_compare,bit_array_var & p_out) const + { + return ::pfc::find_duplicates_sorted_t const &,t_compare>(*this,get_count(),p_compare,p_out); + } + + template + t_size find_duplicates_sorted_permutation_t(t_compare p_compare,t_permutation const & p_permutation,bit_array_var & p_out) + { + return ::pfc::find_duplicates_sorted_permutation_t const &,t_compare,t_permutation>(*this,get_count(),p_compare,p_permutation,p_out); + } + + template + t_size find_item(const t_search & p_item) const//returns index of first occurance, infinite if not found + { + t_size n,max = get_count(); + for(n=0;n + inline bool have_item(const t_search & p_item) const {return find_item(p_item)!=~0;} + + + template + bool bsearch_t(t_compare p_compare,t_param const & p_param,t_size &p_index) const { + return ::pfc::bsearch_t(get_count(),*this,p_compare,p_param,p_index); + } + + template + bool bsearch_permutation_t(t_compare p_compare,t_param const & p_param,const t_permutation & p_permutation,t_size & p_index) const { + return ::pfc::bsearch_permutation_t(get_count(),*this,p_compare,p_param,p_permutation,p_index); + } + + template + void sort_get_permutation_t(t_compare p_compare,t_permutation const & p_permutation) const { + ::pfc::sort_get_permutation_t,t_compare,t_permutation>(*this,p_compare,get_count(),p_permutation); + } + + template + void sort_stable_get_permutation_t(t_compare p_compare,t_permutation const & p_permutation) const { + ::pfc::sort_stable_get_permutation_t,t_compare,t_permutation>(*this,p_compare,get_count(),p_permutation); + } + + template + void enumerate(t_callback & p_callback) const { + for(t_size n = 0, m = get_count(); n < m; ++n ) { + p_callback( (*this)[n] ); + } + } + + static bool g_equals(const t_self & item1, const t_self & item2) { + const t_size count = item1.get_count(); + if (count != item2.get_count()) return false; + for(t_size walk = 0; walk < count; ++walk) if (item1[walk] != item2[walk]) return false; + return true; + } + bool operator==(const t_self & item2) const {return g_equals(*this,item2);} + bool operator!=(const t_self & item2) const {return !g_equals(*this,item2);} + +protected: + list_base_const_t() {} + ~list_base_const_t() {} + + list_base_const_t(const t_self &) {} + void operator=(const t_self &) {} + +}; + + +template +class list_single_ref_t : public list_base_const_t +{ +public: + list_single_ref_t(const T & p_item,t_size p_count = 1) : m_item(p_item), m_count(p_count) {} + t_size get_count() const {return m_count;} + void get_item_ex(T& p_out,t_size n) const {PFC_ASSERT(n +class list_partial_ref_t : public list_base_const_t +{ +public: + list_partial_ref_t(const list_base_const_t & p_list,t_size p_base,t_size p_count) + : m_list(p_list), m_base(p_base), m_count(p_count) + { + PFC_ASSERT(m_base + m_count <= m_list.get_count()); + } + +private: + const list_base_const_t & m_list; + t_size m_base,m_count; + + t_size get_count() const {return m_count;} + void get_item_ex(T & p_out,t_size n) const {m_list.get_item_ex(p_out,n+m_base);} +}; + +template +class list_const_array_t : public list_base_const_t +{ +public: + inline list_const_array_t(A p_data,t_size p_count) : m_data(p_data), m_count(p_count) {} + t_size get_count() const {return m_count;} + void get_item_ex(T & p_out,t_size n) const {p_out = m_data[n];} +private: + A m_data; + t_size m_count; +}; +template +class list_const_array_ref_t : public list_base_const_t { +public: + list_const_array_ref_t(const t_array & data) : m_data(data) {} + t_size get_count() const {return m_data.get_size();} + void get_item_ex(typename t_array::t_item & out, t_size n) const {out = m_data[n];} +private: + const t_array & m_data; +}; + +template +class list_const_cast_t : public list_base_const_t +{ +public: + list_const_cast_t(const list_base_const_t & p_from) : m_from(p_from) {} + t_size get_count() const {return m_from.get_count();} + void get_item_ex(to & p_out,t_size n) const + { + from temp; + m_from.get_item_ex(temp,n); + p_out = temp; + } +private: + const list_base_const_t & m_from; +}; + +template +class ptr_list_const_array_t : public list_base_const_t +{ +public: + inline ptr_list_const_array_t(A p_data,t_size p_count) : m_data(p_data), m_count(p_count) {} + t_size get_count() const {return m_count;} + void get_item_ex(T* & p_out,t_size n) const {p_out = &m_data[n];} +private: + A m_data; + t_size m_count; +}; +template +class list_const_ptr_t : public list_base_const_t +{ +public: + inline list_const_ptr_t(const T * p_data,t_size p_count) : m_data(p_data), m_count(p_count) {} + t_size get_count() const {return m_count;} + void get_item_ex(T & p_out,t_size n) const {p_out = m_data[n];} +private: + const T * m_data; + t_size m_count; +}; + +template +class NOVTABLE list_base_t : public list_base_const_t { +private: + typedef list_base_t t_self; + typedef const list_base_const_t t_self_const; +public: + class NOVTABLE sort_callback + { + public: + virtual int compare(const T& p_item1,const T& p_item2) = 0; + }; + + virtual void filter_mask(const bit_array & mask) = 0; + virtual t_size insert_items(const list_base_const_t & items,t_size base) = 0; + virtual void reorder_partial(t_size p_base,const t_size * p_data,t_size p_count) = 0; + virtual void sort(sort_callback & p_callback) = 0; + virtual void sort_stable(sort_callback & p_callback) = 0; + virtual void replace_item(t_size p_index,const T& p_item) = 0; + virtual void swap_item_with(t_size p_index,T & p_item) = 0; + virtual void swap_items(t_size p_index1,t_size p_index2) = 0; + + inline void reorder(const t_size * p_data) {reorder_partial(0,p_data,this->get_count());} + + inline t_size insert_item(const T & item,t_size base) {return insert_items(list_single_ref_t(item),base);} + t_size insert_items_repeat(const T & item,t_size num,t_size base) {return insert_items(list_single_ref_t(item,num),base);} + inline t_size add_items_repeat(T item,t_size num) {return insert_items_repeat(item,num,~0);} + t_size insert_items_fromptr(const T* source,t_size num,t_size base) {return insert_items(list_const_ptr_t(source,num),base);} + inline t_size add_items_fromptr(const T* source,t_size num) {return insert_items_fromptr(source,num,~0);} + + inline t_size add_items(const list_base_const_t & items) {return insert_items(items,~0);} + inline t_size add_item(const T& item) {return insert_item(item,~0);} + + inline void remove_mask(const bit_array & mask) {filter_mask(bit_array_not(mask));} + inline void remove_all() {filter_mask(bit_array_false());} + inline void truncate(t_size val) {if (val < this->get_count()) remove_mask(bit_array_range(val,this->get_count()-val,true));} + + inline T replace_item_ex(t_size p_index,const T & p_item) {T ret = p_item;swap_item_with(p_index,ret);return ret;} + + inline T operator[](t_size n) const {return this->get_item(n);} + + template + class sort_callback_impl_t : public sort_callback + { + public: + sort_callback_impl_t(t_compare p_compare) : m_compare(p_compare) {} + int compare(const T& p_item1,const T& p_item2) {return m_compare(p_item1,p_item2);} + private: + t_compare m_compare; + }; + + class sort_callback_auto : public sort_callback + { + public: + int compare(const T& p_item1,const T& p_item2) {return ::pfc::compare_t(p_item1,p_item2);} + }; + + void sort() {sort(sort_callback_auto());} + template void sort_t(t_compare p_compare) {sort(sort_callback_impl_t(p_compare));} + template void sort_stable_t(t_compare p_compare) {sort_stable(sort_callback_impl_t(p_compare));} + + template void sort_remove_duplicates_t(t_compare p_compare) + { + sort_t(p_compare); + bit_array_bittable array(this->get_count()); + if (this->template find_duplicates_sorted_t(p_compare,array) > 0) + remove_mask(array); + } + + template void sort_stable_remove_duplicates_t(t_compare p_compare) + { + sort_stable_t(p_compare); + bit_array_bittable array(this->get_count()); + if (this->template find_duplicates_sorted_t(p_compare,array) > 0) + remove_mask(array); + } + + + template void remove_duplicates_t(t_compare p_compare) + { + order_helper order(this->get_count()); + sort_get_permutation_t(p_compare,order); + bit_array_bittable array(this->get_count()); + if (this->template find_duplicates_sorted_permutation_t(p_compare,order,array) > 0) + remove_mask(array); + } + + template + void for_each(t_func p_func) { + t_size n,max=this->get_count(); + for(n=0;nget_item(n)); + } + + template + void for_each(t_func p_func,const bit_array & p_mask) { + t_size n,max=this->get_count(); + for(n=p_mask.find(true,0,max);nget_item(n)); + } + } + + template + void remove_mask_ex(const bit_array & p_mask,t_releasefunc p_func) { + this->template for_each(p_func,p_mask); + remove_mask(p_mask); + } + + template + void remove_all_ex(t_releasefunc p_func) { + this->template for_each(p_func); + remove_all(); + } + + template t_self & operator=(t_in const & source) {remove_all(); add_items(source); return *this;} + template t_self & operator+=(t_in const & p_source) {add_item(p_source); return *this;} + template t_self & operator|=(t_in const & p_source) {add_items(p_source); return *this;} + +protected: + list_base_t() {} + ~list_base_t() {} + list_base_t(const t_self&) {} + void operator=(const t_self&) {} +}; + + +template +class list_impl_t : public list_base_t +{ +public: + typedef list_base_t t_base; + typedef list_impl_t t_self; + list_impl_t() {} + list_impl_t(const t_self & p_source) { add_items(p_source); } + + void prealloc(t_size count) {m_buffer.prealloc(count);} + + void set_count(t_size p_count) {m_buffer.set_size(p_count);} + void set_size(t_size p_count) {m_buffer.set_size(p_count);} + + template + t_size _insert_item_t(const t_in & item, t_size idx) { + return ::pfc::insert_t(m_buffer, item, idx); + } + template + t_size insert_item(const t_in & item, t_size idx) { + return _insert_item_t(item, idx); + } + + t_size insert_item(const T& item,t_size idx) { + return _insert_item_t(item, idx); + } + + T remove_by_idx(t_size idx) + { + T ret = m_buffer[idx]; + t_size n; + t_size max = m_buffer.get_size(); + for(n=idx+1;n=0); + PFC_ASSERT(n=0); + PFC_ASSERT(n= 0); + PFC_ASSERT(n < get_size() ); + return m_buffer[n]; + }; + + inline t_size get_count() const {return m_buffer.get_size();} + inline t_size get_size() const {return m_buffer.get_size();} + + inline const T & operator[](t_size n) const + { + PFC_ASSERT(n>=0); + PFC_ASSERT(n & source,t_size base) { //workaround for inefficient operator[] on virtual-interface-accessed lists + t_size count = get_size(); + if (base>count) base = count; + t_size num = source.get_count(); + m_buffer.set_size(count+num); + if (count > base) { + for(t_size n=count-1;(int)n>=(int)base;n--) { + ::pfc::move_t(m_buffer[n+num],m_buffer[n]); + } + } + + for(t_size n=0;n & source,t_size base) {return _insert_items_v(source, base);} + t_size insert_items(const list_base_t & source,t_size base) {return _insert_items_v(source, base);} + + template + t_size insert_items(const t_in & source,t_size base) { + t_size count = get_size(); + if (base>count) base = count; + t_size num = array_size_t(source); + m_buffer.set_size(count+num); + if (count > base) { + for(t_size n=count-1;(int)n>=(int)base;n--) { + ::pfc::move_t(m_buffer[n+num],m_buffer[n]); + } + } + + for(t_size n=0;n + void add_items(const t_in & in) {insert_items(in, ~0);} + + void get_items_mask(list_impl_t & out,const bit_array & mask) + { + t_size n,count = get_size(); + for_each_bit_array(n,mask,true,0,count) + out.add_item(m_buffer[n]); + } + + void filter_mask(const bit_array & mask) + { + t_size n,count = get_size(), total = 0; + + n = total = mask.find(false,0,count); + + if (n=0); + PFC_ASSERT(idx wrapper(m_buffer); + ::pfc::sort(wrapper,get_size()); + } + + template + void sort_t(t_compare p_compare) + { + ::pfc::sort_callback_impl_simple_wrap_t wrapper(m_buffer,p_compare); + ::pfc::sort(wrapper,get_size()); + } + + template + void sort_stable_t(t_compare p_compare) + { + ::pfc::sort_callback_impl_simple_wrap_t wrapper(m_buffer,p_compare); + ::pfc::sort_stable(wrapper,get_size()); + } + inline void reorder_partial(t_size p_base,const t_size * p_order,t_size p_count) + { + PFC_ASSERT(p_base+p_count<=get_size()); + ::pfc::reorder_partial_t(m_buffer,p_base,p_order,p_count); + } + + template + t_size find_duplicates_sorted_t(t_compare p_compare,bit_array_var & p_out) const + { + return ::pfc::find_duplicates_sorted_t const &,t_compare>(*this,get_size(),p_compare,p_out); + } + + template + t_size find_duplicates_sorted_permutation_t(t_compare p_compare,t_permutation p_permutation,bit_array_var & p_out) + { + return ::pfc::find_duplicates_sorted_permutation_t const &,t_compare,t_permutation>(*this,get_size(),p_compare,p_permutation,p_out); + } + + + void move_from(t_self & other) { + remove_all(); + m_buffer = std::move(other.m_buffer); + } + +private: + class sort_callback_wrapper + { + public: + explicit inline sort_callback_wrapper(typename t_base::sort_callback & p_callback) : m_callback(p_callback) {} + inline int operator()(const T& item1,const T& item2) const {return m_callback.compare(item1,item2);} + private: + typename t_base::sort_callback & m_callback; + }; +public: + void sort(typename t_base::sort_callback & p_callback) + { + sort_t(sort_callback_wrapper(p_callback)); + } + + void sort_stable(typename t_base::sort_callback & p_callback) + { + sort_stable_t(sort_callback_wrapper(p_callback)); + } + + void remove_mask(const bit_array & mask) {filter_mask(bit_array_not(mask));} + + void remove_mask(const bool * mask) {remove_mask(bit_array_table(mask,get_size()));} + void filter_mask(const bool * mask) {filter_mask(bit_array_table(mask,get_size()));} + + t_size add_item(const T& item) { + return insert_item(item, ~0); + } + + template t_size add_item(const t_in & item) { + return insert_item(item, ~0); + } + + void remove_all() {remove_mask(bit_array_true());} + + void remove_item(const T& item) + { + t_size n,max = get_size(); + bit_array_bittable mask(max); + for(n=0;n & p_item1,list_impl_t & p_item2) + { + swap_t(p_item1.m_buffer,p_item2.m_buffer); + } + + template + t_size find_item(const t_search & p_item) const//returns index of first occurance, infinite if not found + { + t_size n,max = get_size(); + for(n=0;n + inline bool have_item(const t_search & p_item) const {return this->template find_item(p_item)!=~0;} + + template t_self & operator=(t_in const & source) {remove_all(); add_items(source); return *this;} + template t_self & operator+=(t_in const & p_source) {add_item(p_source); return *this;} + template t_self & operator|=(t_in const & p_source) {add_items(p_source); return *this;} +protected: + t_storage m_buffer; +}; + +template class t_alloc = alloc_fast > +class list_t : public list_impl_t > { +public: + typedef list_t t_self; + template t_self & operator=(t_in const & source) {this->remove_all(); this->add_items(source); return *this;} + template t_self & operator+=(t_in const & p_source) {this->add_item(p_source); return *this;} + template t_self & operator|=(t_in const & p_source) {this->add_items(p_source); return *this;} +}; + +template class t_alloc = alloc_fast > +class list_hybrid_t : public list_impl_t > { +public: + typedef list_hybrid_t t_self; + template t_self & operator=(t_in const & source) {this->remove_all(); this->add_items(source); return *this;} + template t_self & operator+=(t_in const & p_source) {this->add_item(p_source); return *this;} + template t_self & operator|=(t_in const & p_source) {this->add_items(p_source); return *this;} +}; + +template +class ptr_list_const_cast_t : public list_base_const_t +{ +public: + inline ptr_list_const_cast_t(const list_base_const_t & p_param) : m_param(p_param) {} + t_size get_count() const {return m_param.get_count();} + void get_item_ex(const T * & p_out,t_size n) const {T* temp; m_param.get_item_ex(temp,n); p_out = temp;} +private: + const list_base_const_t & m_param; + +}; + + +template +class list_const_permutation_t : public list_base_const_t +{ +public: + inline list_const_permutation_t(const list_base_const_t & p_list,P p_permutation) : m_list(p_list), m_permutation(p_permutation) {} + t_size get_count() const {return m_list.get_count();} + void get_item_ex(T & p_out,t_size n) const {m_list.get_item_ex(p_out,m_permutation[n]);} +private: + P m_permutation; + const list_base_const_t & m_list; +}; + + +template +class list_permutation_t : public list_base_const_t +{ +public: + t_size get_count() const {return m_count;} + void get_item_ex(T & p_out,t_size n) const {m_base.get_item_ex(p_out,m_order[n]);} + list_permutation_t(const list_base_const_t & p_base,const t_size * p_order,t_size p_count) + : m_base(p_base), m_order(p_order), m_count(p_count) + { + PFC_ASSERT(m_base.get_count() >= m_count); + } +private: + const list_base_const_t & m_base; + const t_size * m_order; + t_size m_count; +}; + +template class alloc> class traits_t > : public combine_traits >, traits_vtable> {}; + +} +#endif //_PFC_LIST_H_ diff --git a/SDK/pfc/makefile b/SDK/pfc/makefile new file mode 100644 index 0000000..9c4a711 --- /dev/null +++ b/SDK/pfc/makefile @@ -0,0 +1,23 @@ +CXXFLAGS += -fPIC -std=c++11 +SOURCES_CPP = audio_math.cpp audio_sample.cpp base64.cpp bit_array.cpp bsearch.cpp cpuid.cpp filehandle.cpp guid.cpp nix-objects.cpp other.cpp pathUtils.cpp printf.cpp selftest.cpp sort.cpp stdafx.cpp stringNew.cpp string_base.cpp string_conv.cpp synchro_nix.cpp threads.cpp timers.cpp utf8.cpp wildcard.cpp win-objects.cpp + +UNAME_S := $(shell uname -s) +ifeq ($(UNAME_S),Darwin) +SOURCES_OBJC = obj-c.mm +CXXFLAGS += -stdlib=libc++ +endif + +OBJECTS=$(SOURCES_CPP:.cpp=.o) $(SOURCES_OBJC:.mm=.o) +SOURCES=$(SOURCES_CPP) $(SOURCES_OBJC) +OUTPUT=pfc.a + +all: $(SOURCES) $(OUTPUT) + +$(OUTPUT): $(OBJECTS) + ar rcs $(OUTPUT) $(OBJECTS) + +%.o: %.mm + $(CXX) $(CXXFLAGS) $< -c -o $@ + +clean: + rm -f $(OBJECTS) $(OUTPUT) diff --git a/SDK/pfc/map.h b/SDK/pfc/map.h new file mode 100644 index 0000000..c63d104 --- /dev/null +++ b/SDK/pfc/map.h @@ -0,0 +1,256 @@ +#ifndef _MAP_T_H_INCLUDED_ +#define _MAP_T_H_INCLUDED_ + +namespace pfc { + PFC_DECLARE_EXCEPTION(exception_map_entry_not_found,exception,"Map entry not found"); + + template class __map_overwrite_wrapper { + public: + __map_overwrite_wrapper(t_destination & p_destination) : m_destination(p_destination) {} + template void operator() (const t_key & p_key,const t_value & p_value) {m_destination.set(p_key,p_value);} + private: + t_destination & m_destination; + }; + + template + class map_t { + private: + typedef map_t t_self; + public: + typedef t_storage_key t_key; typedef t_storage_value t_value; + template + void set(const _t_key & p_key, const _t_value & p_value) { + bool isnew; + t_storage & storage = m_data.add_ex(t_search_set<_t_key,_t_value>(p_key,p_value), isnew); + if (!isnew) storage.m_value = p_value; + } + + template + t_storage_value & find_or_add(_t_key const & p_key) { + return m_data.add(t_search_query<_t_key>(p_key)).m_value; + } + + template + t_storage_value & find_or_add_ex(_t_key const & p_key,bool & p_isnew) { + return m_data.add_ex(t_search_query<_t_key>(p_key),p_isnew).m_value; + } + + template + bool have_item(const _t_key & p_key) const { + return m_data.have_item(t_search_query<_t_key>(p_key)); + } + + template + bool query(const _t_key & p_key,_t_value & p_value) const { + const t_storage * storage = m_data.find_ptr(t_search_query<_t_key>(p_key)); + if (storage == NULL) return false; + p_value = storage->m_value; + return true; + } + + template + const t_storage_value & operator[] (const _t_key & p_key) const { + const t_storage_value * ptr = query_ptr(p_key); + if (ptr == NULL) throw exception_map_entry_not_found(); + return *ptr; + } + + template + t_storage_value & operator[] (const _t_key & p_key) { + return find_or_add(p_key); + } + + template + const t_storage_value * query_ptr(const _t_key & p_key) const { + const t_storage * storage = m_data.find_ptr(t_search_query<_t_key>(p_key)); + if (storage == NULL) return NULL; + return &storage->m_value; + } + + template + t_storage_value * query_ptr(const _t_key & p_key) { + t_storage * storage = m_data.find_ptr(t_search_query<_t_key>(p_key)); + if (storage == NULL) return NULL; + return &storage->m_value; + } + + template + bool query_ptr(const _t_key & p_key, const t_storage_value * & out) const { + const t_storage * storage = m_data.find_ptr(t_search_query<_t_key>(p_key)); + if (storage == NULL) return false; + out = &storage->m_value; + return true; + } + + template + bool query_ptr(const _t_key & p_key, t_storage_value * & out) { + t_storage * storage = m_data.find_ptr(t_search_query<_t_key>(p_key)); + if (storage == NULL) return false; + out = &storage->m_value; + return true; + } + + template + const t_storage_value * query_nearest_ptr(_t_key & p_key) const { + const t_storage * storage = m_data.template find_nearest_item(t_search_query<_t_key>(p_key)); + if (storage == NULL) return NULL; + p_key = storage->m_key; + return &storage->m_value; + } + + template + t_storage_value * query_nearest_ptr(_t_key & p_key) { + t_storage * storage = m_data.template find_nearest_item(t_search_query<_t_key>(p_key)); + if (storage == NULL) return NULL; + p_key = storage->m_key; + return &storage->m_value; + } + + template + bool query_nearest(_t_key & p_key,_t_value & p_value) const { + const t_storage * storage = m_data.template find_nearest_item(t_search_query<_t_key>(p_key)); + if (storage == NULL) return false; + p_key = storage->m_key; + p_value = storage->m_value; + return true; + } + + + template + bool remove(const _t_key & p_key) { + return m_data.remove_item(t_search_query<_t_key>(p_key)); + } + + template + void enumerate(t_callback & p_callback) const { + enumeration_wrapper cb(p_callback); + m_data.enumerate(cb); + } + + template + void enumerate(t_callback & p_callback) { + enumeration_wrapper_var cb(p_callback); + m_data._enumerate_var(cb); + } + + + t_size get_count() const throw() {return m_data.get_count();} + + void remove_all() throw() {m_data.remove_all();} + + template + void overwrite(const t_source & p_source) { + __map_overwrite_wrapper wrapper(*this); + p_source.enumerate(wrapper); + } + + //backwards compatibility method wrappers + template bool exists(const _t_key & p_key) const {return have_item(p_key);} + + + template bool get_first(_t_key & p_out) const { + return m_data.get_first(t_retrieve_key<_t_key>(p_out)); + } + + template bool get_last(_t_key & p_out) const { + return m_data.get_last(t_retrieve_key<_t_key>(p_out)); + } + + private: + template + struct t_retrieve_key { + typedef t_retrieve_key<_t_key> t_self; + t_retrieve_key(_t_key & p_key) : m_key(p_key) {} + template const t_self & operator=(const t_what & p_what) {m_key = p_what.m_key; return *this;} + _t_key & m_key; + }; + template + struct t_search_query { + t_search_query(const _t_key & p_key) : m_key(p_key) {} + _t_key const & m_key; + }; + template + struct t_search_set { + t_search_set(const _t_key & p_key, const _t_value & p_value) : m_key(p_key), m_value(p_value) {} + + _t_key const & m_key; + _t_value const & m_value; + }; + + struct t_storage { + const t_storage_key m_key; + t_storage_value m_value; + + template + t_storage(t_search_query<_t_key> const & p_source) : m_key(p_source.m_key), m_value() {} + + template + t_storage(t_search_set<_t_key,_t_value> const & p_source) : m_key(p_source.m_key), m_value(p_source.m_value) {} + + static bool equals(const t_storage & v1, const t_storage & v2) {return v1.m_key == v2.m_key && v1.m_value == v2.m_value;} + bool operator==(const t_storage & other) const {return equals(*this,other);} + bool operator!=(const t_storage & other) const {return !equals(*this,other);} + }; + + class comparator_wrapper { + public: + template + inline static int compare(const t1 & p_item1,const t2 & p_item2) { + return t_comparator::compare(p_item1.m_key,p_item2.m_key); + } + }; + + template + class enumeration_wrapper { + public: + enumeration_wrapper(t_callback & p_callback) : m_callback(p_callback) {} + void operator()(const t_storage & p_item) {m_callback(p_item.m_key,p_item.m_value);} + private: + t_callback & m_callback; + }; + + template + class enumeration_wrapper_var { + public: + enumeration_wrapper_var(t_callback & p_callback) : m_callback(p_callback) {} + void operator()(t_storage & p_item) {m_callback(implicit_cast(p_item.m_key),p_item.m_value);} + private: + t_callback & m_callback; + }; + + typedef avltree_t t_content; + + t_content m_data; + public: + typedef traits_t traits; + typedef typename t_content::const_iterator const_iterator; + typedef typename t_content::iterator iterator; + + iterator first() throw() {return m_data._first_var();} + iterator last() throw() {return m_data._last_var();} + const_iterator first() const throw() {return m_data.first();} + const_iterator last() const throw() {return m_data.last();} + + template iterator find(const _t_key & key) {return m_data.find(t_search_query<_t_key>(key));} + template const_iterator find(const _t_key & key) const {return m_data.find(t_search_query<_t_key>(key));} + + static bool equals(const t_self & v1, const t_self & v2) { + return t_content::equals(v1.m_data,v2.m_data); + } + bool operator==(const t_self & other) const {return equals(*this,other);} + bool operator!=(const t_self & other) const {return !equals(*this,other);} + + bool remove(iterator const& iter) { + PFC_ASSERT(iter.is_valid()); + return m_data.remove(iter); + //should never return false unless there's a bug in calling code + } + bool remove(const_iterator const& iter) { + PFC_ASSERT(iter.is_valid()); + return m_data.remove(iter); + //should never return false unless there's a bug in calling code + } + }; +} + +#endif //_MAP_T_H_INCLUDED_ diff --git a/SDK/pfc/mem_block_mgr.h b/SDK/pfc/mem_block_mgr.h new file mode 100644 index 0000000..ad5b7e8 --- /dev/null +++ b/SDK/pfc/mem_block_mgr.h @@ -0,0 +1,71 @@ +#ifndef _MEM_BLOCK_MGR_H_ +#define _MEM_BLOCK_MGR_H_ + +#error DEPRECATED + + +template +class mem_block_manager +{ + struct entry + { + mem_block_t block; + bool used; + }; + ptr_list_t list; +public: + T * copy(const T* ptr,int size) + { + int n; + int found_size = -1,found_index = -1; + for(n=0;nused) + { + int block_size = list[n]->block.get_size(); + if (found_size<0) + { + found_index=n; found_size = block_size; + } + else if (found_sizefound_size) + { + found_index=n; found_size = block_size; + } + } + else if (found_size>size) + { + if (block_size>=size && block_size=0) + { + list[found_index]->used = true; + return list[found_index]->block.copy(ptr,size); + } + entry * new_entry = new entry; + new_entry->used = true; + list.add_item(new_entry); + return new_entry->block.copy(ptr,size); + } + + void mark_as_free() + { + int n; + for(n=0;nused = false; + } + } + + ~mem_block_manager() {list.delete_all();} +}; + +#endif \ No newline at end of file diff --git a/SDK/pfc/memalign.h b/SDK/pfc/memalign.h new file mode 100644 index 0000000..29463dd --- /dev/null +++ b/SDK/pfc/memalign.h @@ -0,0 +1,139 @@ +#ifndef _MSC_VER +#include +#endif + +namespace pfc { + template + class mem_block_aligned { + public: + typedef mem_block_aligned self_t; + mem_block_aligned() : m_ptr(), m_size() {} + + void * ptr() {return m_ptr;} + const void * ptr() const {return m_ptr;} + void * get_ptr() {return m_ptr;} + const void * get_ptr() const {return m_ptr;} + size_t size() const {return m_size;} + size_t get_size() const {return m_size;} + + void resize(size_t s) { + if (s == m_size) { + // nothing to do + } else if (s == 0) { + _free(m_ptr); + m_ptr = NULL; + } else { + void * ptr; +#ifdef _MSC_VER + if (m_ptr == NULL) ptr = _aligned_malloc(s, alignBytes); + else ptr = _aligned_realloc(m_ptr, s, alignBytes); + if ( ptr == NULL ) throw std::bad_alloc(); +#else +#ifdef __ANDROID__ + if ((ptr = memalign( alignBytes, s )) == NULL) throw std::bad_alloc(); +#else + if (posix_memalign( &ptr, alignBytes, s ) < 0) throw std::bad_alloc(); +#endif + if (m_ptr != NULL) { + memcpy( ptr, m_ptr, min_t( m_size, s ) ); + _free( m_ptr ); + } +#endif + m_ptr = ptr; + } + m_size = s; + } + void set_size(size_t s) {resize(s);} + + ~mem_block_aligned() { + _free(m_ptr); + } + + self_t const & operator=(self_t const & other) { + assign(other); + return *this; + } + mem_block_aligned(self_t const & other) : m_ptr(), m_size() { + assign(other); + } + void assign(self_t const & other) { + resize(other.size()); + memcpy(ptr(), other.ptr(), size()); + } + mem_block_aligned(self_t && other) { + m_ptr = other.m_ptr; + m_size = other.m_size; + other.m_ptr = NULL; other.m_size = 0; + } + self_t const & operator=(self_t && other) { + _free(m_ptr); + m_ptr = other.m_ptr; + m_size = other.m_size; + other.m_ptr = NULL; other.m_size = 0; + return *this; + } + + private: + static void _free(void * ptr) { +#ifdef _MSC_VER + _aligned_free(ptr); +#else + free(ptr); +#endif + } + + void * m_ptr; + size_t m_size; + }; + + template + class mem_block_aligned_t { + public: + typedef mem_block_aligned_t self_t; + void resize(size_t s) { m.resize( multiply_guarded(s, sizeof(obj_t) ) ); } + void set_size(size_t s) {resize(s);} + size_t size() const { return m.size() / sizeof(obj_t); } + size_t get_size() const {return size();} + obj_t * ptr() { return reinterpret_cast(m.ptr()); } + const obj_t * ptr() const { return reinterpret_cast(m.ptr()); } + obj_t * get_ptr() { return reinterpret_cast(m.ptr()); } + const obj_t * get_ptr() const { return reinterpret_cast(m.ptr()); } + mem_block_aligned_t() {} + mem_block_aligned_t(self_t const & other) : m(other.m) {} + mem_block_aligned_t(self_t && other) : m(std::move(other.m)) {} + self_t const & operator=(self_t const & other) {m = other.m; return *this;} + self_t const & operator=(self_t && other) {m = std::move(other.m); return *this;} + private: + mem_block_aligned m; + }; + + template + class mem_block_aligned_incremental_t { + public: + typedef mem_block_aligned_t self_t; + + void resize(size_t s) { + if (s > m.size()) { + m.resize( multiply_guarded(s, 3) / 2 ); + } + m_size = s; + } + void set_size(size_t s) {resize(s);} + + size_t size() const { return m_size; } + size_t get_size() const {return m_size; } + + obj_t * ptr() { return m.ptr(); } + const obj_t * ptr() const { return m.ptr(); } + obj_t * get_ptr() { return m.ptr(); } + const obj_t * get_ptr() const { return m.ptr(); } + mem_block_aligned_incremental_t() : m_size() {} + mem_block_aligned_incremental_t(self_t const & other) : m(other.m), m_size(other.m_size) {} + mem_block_aligned_incremental_t(self_t && other) : m(std::move(other.m)), m_size(other.m_size) { other.m_size = 0; } + self_t const & operator=(self_t const & other) {m = other.m; m_size = other.m_size; return *this;} + self_t const & operator=(self_t && other) {m = std::move(other.m); m_size = other.m_size; other.m_size = 0; return *this;} + private: + mem_block_aligned_t m; + size_t m_size; + }; +} diff --git a/SDK/pfc/nix-objects.cpp b/SDK/pfc/nix-objects.cpp new file mode 100644 index 0000000..46cbe53 --- /dev/null +++ b/SDK/pfc/nix-objects.cpp @@ -0,0 +1,266 @@ +#include "pfc.h" + +#ifndef _WIN32 +#include +#include +#include +#include +#include + +#ifdef __APPLE__ +#include +#endif + +namespace pfc { + void nixFormatError( string_base & str, int code ) { + char buffer[512] = {}; + strerror_r(code, buffer, sizeof(buffer)); + str = buffer; + } + + void setNonBlocking( int fd, bool bNonBlocking ) { + int flags = fcntl(fd, F_GETFL, 0); + int flags2 = flags; + if (bNonBlocking) flags2 |= O_NONBLOCK; + else flags2 &= ~O_NONBLOCK; + if (flags2 != flags) fcntl(fd, F_SETFL, flags2); + } + + void setCloseOnExec( int fd, bool bCloseOnExec ) { + int flags = fcntl(fd, F_GETFD); + int flags2 = flags; + if (bCloseOnExec) flags2 |= FD_CLOEXEC; + else flags2 &= ~FD_CLOEXEC; + if (flags != flags2) fcntl(fd, F_SETFD, flags2); + } + + void setInheritable( int fd, bool bInheritable ) { + setCloseOnExec( fd, !bInheritable ); + } + + void createPipe( int fd[2], bool bInheritable ) { +#if defined(__linux__) && defined(O_CLOEXEC) + if (pipe2(fd, bInheritable ? 0 : O_CLOEXEC) < 0) throw exception_nix(); +#else + if (pipe(fd) < 0) throw exception_nix(); + if (!bInheritable) { + setInheritable( fd[0], false ); + setInheritable( fd[1], false ); + } +#endif + } + + exception_nix::exception_nix() { + _init(errno); + } + exception_nix::exception_nix(int code) { + _init(code); + } + void exception_nix::_init(int code) { + m_code = code; + nixFormatError(m_msg, code); + } + + timeval makeTimeVal( double timeSeconds ) { + timeval tv = {}; + uint64_t temp = (uint64_t) floor( timeSeconds * 1000000.0 + 0.5); + tv.tv_usec = (uint32_t) (temp % 1000000); + tv.tv_sec = (uint32_t) (temp / 1000000); + return tv; + } + double importTimeval(const timeval & in) { + return (double)in.tv_sec + (double)in.tv_usec / 1000000.0; + } + + void fdSet::operator+=( int fd ) { + m_fds.insert( fd ); + } + void fdSet::operator-=( int fd ) { + m_fds.erase(fd); + } + bool fdSet::operator[] (int fd ) { + return m_fds.find( fd ) != m_fds.end(); + } + void fdSet::clear() { + m_fds.clear(); + } + + void fdSet::operator+=( fdSet const & other ) { + for(auto i = other.m_fds.begin(); i != other.m_fds.end(); ++ i ) { + (*this) += *i; + } + } + + int fdSelect::Select() { + return Select_( -1 ); + } + int fdSelect::Select( double timeOutSeconds ) { + int ms; + if (timeOutSeconds < 0) { + ms = -1; + } else if (timeOutSeconds == 0) { + ms = 0; + } else { + ms = pfc::rint32( timeOutSeconds * 1000 ); + if (ms < 1) ms = 1; + } + return Select_( ms ); + } + + int fdSelect::Select_( int timeOutMS ) { + fdSet total = Reads; + total += Writes; + total += Errors; + const size_t count = total.m_fds.size(); + pfc::array_t< pollfd > v; + v.set_size_discard( count ); + size_t walk = 0; + for( auto i = total.m_fds.begin(); i != total.m_fds.end(); ++ i ) { + const int fd = *i; + auto & f = v[walk++]; + f.fd = fd; + f.events = (Reads[fd] ? POLLIN : 0) | (Writes[fd] ? POLLOUT : 0); + f.revents = 0; + } + int status = poll(v.get_ptr(), (int)count, timeOutMS); + if (status < 0) throw exception_nix(); + + Reads.clear(); Writes.clear(); Errors.clear(); + + if (status > 0) { + for(walk = 0; walk < count; ++walk) { + auto & f = v[walk]; + if (f.revents & POLLIN) Reads += f.fd; + if (f.events & POLLOUT) Writes += f.fd; + if (f.events & POLLERR) Errors += f.fd; + } + } + + return status; + } + + bool fdCanRead( int fd ) { + return fdWaitRead( fd, 0 ); + } + bool fdCanWrite( int fd ) { + return fdWaitWrite( fd, 0 ); + } + + bool fdWaitRead( int fd, double timeOutSeconds ) { + fdSelect sel; sel.Reads += fd; + return sel.Select( timeOutSeconds ) > 0; + } + bool fdWaitWrite( int fd, double timeOutSeconds ) { + fdSelect sel; sel.Writes += fd; + return sel.Select( timeOutSeconds ) > 0; + } + + nix_event::nix_event() { + createPipe( m_fd ); + setNonBlocking( m_fd[0] ); + setNonBlocking( m_fd[1] ); + } + nix_event::~nix_event() { + close( m_fd[0] ); + close( m_fd[1] ); + } + + void nix_event::set_state( bool state ) { + if (state) { + // Ensure that there is a byte in the pipe + if (!fdCanRead(m_fd[0] ) ) { + uint8_t dummy = 0; + write( m_fd[1], &dummy, 1); + } + } else { + // Keep reading until clear + for(;;) { + uint8_t dummy; + if (read(m_fd[0], &dummy, 1 ) != 1) break; + } + } + } + + bool nix_event::wait_for( double p_timeout_seconds ) { + return fdWaitRead( m_fd[0], p_timeout_seconds ); + } + bool nix_event::g_wait_for( int p_event, double p_timeout_seconds ) { + return fdWaitRead( p_event, p_timeout_seconds ); + } + int nix_event::g_twoEventWait( int h1, int h2, double timeout ) { + fdSelect sel; + sel.Reads += h1; + sel.Reads += h2; + int state = sel.Select( timeout ); + if (state < 0) throw exception_nix(); + if (state == 0) return 0; + if (sel.Reads[ h1 ] ) return 1; + if (sel.Reads[ h2 ] ) return 2; + crash(); // should not get here + return 0; + } + int nix_event::g_twoEventWait( nix_event & ev1, nix_event & ev2, double timeout ) { + return g_twoEventWait( ev1.get_handle(), ev2.get_handle(), timeout ); + } + + void nixSleep(double seconds) { + fdSelect sel; sel.Select( seconds ); + } + + double nixGetTime() { + timeval tv = {}; + gettimeofday(&tv, NULL); + return importTimeval(tv); + } + + bool nixReadSymLink( string_base & strOut, const char * path ) { + size_t l = 1024; + for(;;) { + array_t buffer; buffer.set_size( l + 1 ); + ssize_t rv = (size_t) readlink(path, buffer.get_ptr(), l); + if (rv < 0) return false; + if ((size_t)rv <= l) { + buffer.get_ptr()[rv] = 0; + strOut = buffer.get_ptr(); + return true; + } + l *= 2; + } + } + bool nixSelfProcessPath( string_base & strOut ) { +#ifdef __APPLE__ + uint32_t len = 0; + _NSGetExecutablePath(NULL, &len); + array_t temp; temp.set_size( len + 1 ); temp.fill_null(); + _NSGetExecutablePath(temp.get_ptr(), &len); + strOut = temp.get_ptr(); + return true; +#else + return nixReadSymLink( strOut, PFC_string_formatter() << "/proc/" << (unsigned) getpid() << "/exe"); +#endif + } + + void nixGetRandomData( void * outPtr, size_t outBytes ) { + try { + fileHandle randomData; + randomData = open("/dev/urandom", O_RDONLY); + if (randomData.h < 0) throw exception_nix(); + if (read(randomData.h, outPtr, outBytes) != outBytes) throw exception_nix(); + } + catch (std::exception const & e) { + throw std::runtime_error("getRandomData failure"); + } + } + +#ifndef __APPLE__ // for Apple they are implemented in Obj-C + bool isShiftKeyPressed() {return false;} + bool isCtrlKeyPressed() {return false;} + bool isAltKeyPressed() {return false;} +#endif +} + +void uSleepSeconds( double seconds, bool ) { + pfc::nixSleep( seconds ); +} +#endif // _WIN32 + diff --git a/SDK/pfc/nix-objects.h b/SDK/pfc/nix-objects.h new file mode 100644 index 0000000..5687aa5 --- /dev/null +++ b/SDK/pfc/nix-objects.h @@ -0,0 +1,108 @@ +#include +#include +#include + +namespace pfc { + + void nixFormatError( string_base & str, int code ); + + class exception_nix : public std::exception { + public: + exception_nix(); + exception_nix(int code); + + ~exception_nix() throw() { } + + int code() const throw() {return m_code;} + const char * what() const throw() {return m_msg.get_ptr();} + private: + void _init(int code); + int m_code; + string8 m_msg; + }; + + // Toggles non-blocking mode on a file descriptor. + void setNonBlocking( int fd, bool bNonBlocking = true ); + + // Toggles close-on-exec mode on a file descriptor. + void setCloseOnExec( int fd, bool bCloseOnExec = true ); + + // Toggles inheritable mode on a file descriptor. Reverse of close-on-exec. + void setInheritable( int fd, bool bInheritable = true ); + + // Creates a pipe. The pipe is NOT inheritable by default (close-on-exec set). + void createPipe( int fd[2], bool bInheritable = false ); + + timeval makeTimeVal( double seconds ); + double importTimeval(const timeval & tv); + + class fdSet { + public: + + void operator+=( int fd ); + void operator-=( int fd ); + bool operator[] (int fd ); + void clear(); + + void operator+=( fdSet const & other ); + + std::set m_fds; + }; + + + bool fdCanRead( int fd ); + bool fdCanWrite( int fd ); + + bool fdWaitRead( int fd, double timeOutSeconds ); + bool fdWaitWrite( int fd, double timeOutSeconds ); + + class fdSelect { + public: + + int Select(); + int Select( double timeOutSeconds ); + int Select_( int timeOutMS ); + + fdSet Reads, Writes, Errors; + }; + + void nixSleep(double seconds); + + class nix_event { + public: + nix_event(); + ~nix_event(); + + void set_state( bool state ); + + bool is_set( ) {return wait_for(0); } + + bool wait_for( double p_timeout_seconds ); + + static bool g_wait_for( int p_event, double p_timeout_seconds ); + + int get_handle() const {return m_fd[0]; } + + // Two-wait event functions, return 0 on timeout, 1 on evt1 set, 2 on evt2 set + static int g_twoEventWait( nix_event & ev1, nix_event & ev2, double timeout ); + static int g_twoEventWait( int h1, int h2, double timeOut ); + + private: + nix_event(nix_event const&); + void operator=(nix_event const&); + int m_fd[2]; + }; + + double nixGetTime(); + + bool nixReadSymLink( string_base & strOut, const char * path ); + bool nixSelfProcessPath( string_base & strOut ); + + void nixGetRandomData( void * outPtr, size_t outBytes ); + + bool isShiftKeyPressed(); + bool isCtrlKeyPressed(); + bool isAltKeyPressed(); +} + +void uSleepSeconds( double seconds, bool ); diff --git a/SDK/pfc/obj-c.mm b/SDK/pfc/obj-c.mm new file mode 100644 index 0000000..275f715 --- /dev/null +++ b/SDK/pfc/obj-c.mm @@ -0,0 +1,55 @@ +// +// PFC-ObjC.m +// pfc-test +// +// Created by PEPE on 28/07/14. +// Copyright (c) 2014 PEPE. All rights reserved. +// +#ifdef __APPLE__ +#import + + +#include + +#if TARGET_OS_MAC && !TARGET_OS_IPHONE +#import +#endif + +#include "pfc.h" + + +namespace pfc { + void * thread::g_entry(void * arg) { + @autoreleasepool { + reinterpret_cast(arg)->entry(); + } + return NULL; + } + void thread::appleStartThreadPrologue() { + if (![NSThread isMultiThreaded]) [[[NSThread alloc] init] start]; + } + + bool isShiftKeyPressed() { +#if TARGET_OS_MAC && !TARGET_OS_IPHONE + return ( [NSEvent modifierFlags] & NSShiftKeyMask ) != 0; +#else + return false; +#endif + } + bool isCtrlKeyPressed() { +#if TARGET_OS_MAC && !TARGET_OS_IPHONE + return ( [NSEvent modifierFlags] & NSControlKeyMask ) != 0; +#else + return false; +#endif + } + bool isAltKeyPressed() { +#if TARGET_OS_MAC && !TARGET_OS_IPHONE + return ( [NSEvent modifierFlags] & NSAlternateKeyMask ) != 0; +#else + return false; +#endif + } +} + +#endif diff --git a/SDK/pfc/order_helper.h b/SDK/pfc/order_helper.h new file mode 100644 index 0000000..575989d --- /dev/null +++ b/SDK/pfc/order_helper.h @@ -0,0 +1,68 @@ +namespace pfc { + PFC_DECLARE_EXCEPTION( exception_invalid_permutation, exception_invalid_params, "Invalid permutation" ); + t_size permutation_find_reverse(t_size const * order, t_size count, t_size value); + + //! For critical sanity checks. Speed: O(n), allocates memory. + bool permutation_is_valid(t_size const * order, t_size count); + //! For critical sanity checks. Speed: O(n), allocates memory. + void permutation_validate(t_size const * order, t_size count); + + //! Creates a permutation that moves selected items in a list box by the specified delta-offset. + void create_move_items_permutation(t_size * p_output,t_size p_count,const class bit_array & p_selection,int p_delta); +} + +class order_helper +{ + pfc::array_t m_data; +public: + order_helper(t_size p_size) { + m_data.set_size(p_size); + for(t_size n=0;n static bool g_is_identity(const t_array & p_array) { + const t_size count = pfc::array_size_t(p_array); + for(t_size walk = 0; walk < count; ++walk) if (p_array[walk] != walk) return false; + return true; + } + + template + static void g_fill(t_int * p_order,const t_size p_count) { + t_size n; for(n=0;n + static void g_fill(t_array & p_array) { + t_size n; const t_size max = pfc::array_size_t(p_array); + for(n=0;n +#include +#endif +#ifndef _MSC_VER +#include +#endif + +#if defined(__ANDROID__) +#include +#endif + +#include + +namespace pfc { + bool permutation_is_valid(t_size const * order, t_size count) { + bit_array_bittable found(count); + for(t_size walk = 0; walk < count; ++walk) { + if (order[walk] >= count) return false; + if (found[walk]) return false; + found.set(walk,true); + } + return true; + } + void permutation_validate(t_size const * order, t_size count) { + if (!permutation_is_valid(order,count)) throw exception_invalid_permutation(); + } + + t_size permutation_find_reverse(t_size const * order, t_size count, t_size value) { + if (value >= count) return ~0; + for(t_size walk = 0; walk < count; ++walk) { + if (order[walk] == value) return walk; + } + return ~0; + } + + void create_move_items_permutation(t_size * p_output,t_size p_count,const bit_array & p_selection,int p_delta) { + t_size * const order = p_output; + const t_size count = p_count; + + pfc::array_t selection; selection.set_size(p_count); + + for(t_size walk = 0; walk < count; ++walk) { + order[walk] = walk; + selection[walk] = p_selection[walk]; + } + + if (p_delta<0) + { + for(;p_delta<0;p_delta++) + { + t_size idx; + for(idx=1;idx0;p_delta--) + { + t_size idx; + for(idx=count-2;(int)idx>=0;idx--) + { + if (selection[idx] && !selection[idx+1]) + { + pfc::swap_t(order[idx],order[idx+1]); + pfc::swap_t(selection[idx],selection[idx+1]); + } + } + } + } + } +} + +void order_helper::g_swap(t_size * data,t_size ptr1,t_size ptr2) +{ + t_size temp = data[ptr1]; + data[ptr1] = data[ptr2]; + data[ptr2] = temp; +} + + +t_size order_helper::g_find_reverse(const t_size * order,t_size val) +{ + t_size prev = val, next = order[val]; + while(next != val) + { + prev = next; + next = order[next]; + } + return prev; +} + + +void order_helper::g_reverse(t_size * order,t_size base,t_size count) +{ + t_size max = count>>1; + t_size n; + t_size base2 = base+count-1; + for(n=0;n>1;n++) swap_t(ptr[n],ptr[p_bytes-n-1]); +} + +void pfc::outputDebugLine(const char * msg) { +#ifdef _WIN32 + OutputDebugString(pfc::stringcvt::string_os_from_utf8(PFC_string_formatter() << msg << "\n") ); +#elif defined(__ANDROID__) + __android_log_write(ANDROID_LOG_INFO, "Debug", msg); +#else + printf("%s\n", msg); +#endif +} + +#if PFC_DEBUG + +#ifdef _WIN32 +void pfc::myassert_win32(const wchar_t * _Message, const wchar_t *_File, unsigned _Line) { + if (IsDebuggerPresent()) pfc::crash(); + _wassert(_Message,_File,_Line); +} +#else + +void pfc::myassert(const char * _Message, const char *_File, unsigned _Line) +{ + PFC_DEBUGLOG << "Assert failure: \"" << _Message << "\" in: " << _File << " line " << _Line; + crash(); +} +#endif + +#endif + + +t_uint64 pfc::pow_int(t_uint64 base, t_uint64 exp) { + t_uint64 mul = base; + t_uint64 val = 1; + t_uint64 mask = 1; + while(exp != 0) { + if (exp & mask) { + val *= mul; + exp ^= mask; + } + mul = mul * mul; + mask <<= 1; + } + return val; +} + +double pfc::exp_int( const double base, const int expS ) { + // return pow(base, (double)v); + + bool neg; + unsigned exp; + if (expS < 0) { + neg = true; + exp = (unsigned) -expS; + } else { + neg = false; + exp = (unsigned) expS; + } + double v = 1.0; + if (true) { + if (exp) { + double mul = base; + for(;;) { + if (exp & 1) v *= mul; + exp >>= 1; + if (exp == 0) break; + mul *= mul; + } + } + } else { + for(unsigned i = 0; i < exp; ++i) { + v *= base; + } + } + if (neg) v = 1.0 / v; + return v; +} + + +t_int32 pfc::rint32(double p_val) { return (t_int32)floor(p_val + 0.5); } +t_int64 pfc::rint64(double p_val) { return (t_int64)floor(p_val + 0.5); } diff --git a/SDK/pfc/other.h b/SDK/pfc/other.h new file mode 100644 index 0000000..52d1bd0 --- /dev/null +++ b/SDK/pfc/other.h @@ -0,0 +1,325 @@ +#ifndef _PFC_OTHER_H_ +#define _PFC_OTHER_H_ + +namespace pfc { + template + class vartoggle_t { + T oldval; T & var; + public: + vartoggle_t(T & p_var,const T & val) : var(p_var) { + oldval = var; + var = val; + } + ~vartoggle_t() {var = oldval;} + }; + + typedef vartoggle_t booltoggle; +}; + +#ifdef _MSC_VER + +class fpu_control +{ + unsigned old_val; + unsigned mask; +public: + inline fpu_control(unsigned p_mask,unsigned p_val) + { + mask = p_mask; + _controlfp_s(&old_val,p_val,mask); + } + inline ~fpu_control() + { + unsigned dummy; + _controlfp_s(&dummy,old_val,mask); + } +}; + +class fpu_control_roundnearest : private fpu_control +{ +public: + fpu_control_roundnearest() : fpu_control(_MCW_RC,_RC_NEAR) {} +}; + +class fpu_control_flushdenormal : private fpu_control +{ +public: + fpu_control_flushdenormal() : fpu_control(_MCW_DN,_DN_FLUSH) {} +}; + +class fpu_control_default : private fpu_control +{ +public: + fpu_control_default() : fpu_control(_MCW_DN|_MCW_RC,_DN_FLUSH|_RC_NEAR) {} +}; + +#ifdef _M_IX86 +class sse_control { +public: + sse_control(unsigned p_mask,unsigned p_val) : m_mask(p_mask) { + __control87_2(p_val,p_mask,NULL,&m_oldval); + } + ~sse_control() { + __control87_2(m_oldval,m_mask,NULL,&m_oldval); + } +private: + unsigned m_mask,m_oldval; +}; +class sse_control_flushdenormal : private sse_control { +public: + sse_control_flushdenormal() : sse_control(_MCW_DN,_DN_FLUSH) {} +}; +#endif + +#endif + +namespace pfc { + + class releaser_delete { + public: + template static void release(T* p_ptr) {delete p_ptr;} + }; + class releaser_delete_array { + public: + template static void release(T* p_ptr) {delete[] p_ptr;} + }; + class releaser_free { + public: + static void release(void * p_ptr) {free(p_ptr);} + }; + + //! Assumes t_freefunc to never throw exceptions. + template + class ptrholder_t { + private: + typedef ptrholder_t t_self; + public: + inline ptrholder_t(T* p_ptr) : m_ptr(p_ptr) {} + inline ptrholder_t() : m_ptr(NULL) {} + inline ~ptrholder_t() {t_releaser::release(m_ptr);} + inline bool is_valid() const {return m_ptr != NULL;} + inline bool is_empty() const {return m_ptr == NULL;} + inline T* operator->() const {return m_ptr;} + inline T* get_ptr() const {return m_ptr;} + inline void release() {t_releaser::release(replace_null_t(m_ptr));;} + inline void attach(T * p_ptr) {release(); m_ptr = p_ptr;} + inline const t_self & operator=(T * p_ptr) {set(p_ptr);return *this;} + inline T* detach() {return pfc::replace_null_t(m_ptr);} + inline T& operator*() const {return *m_ptr;} + + inline t_self & operator<<(t_self & p_source) {attach(p_source.detach());return *this;} + inline t_self & operator>>(t_self & p_dest) {p_dest.attach(detach());return *this;} + + //deprecated + inline void set(T * p_ptr) {attach(p_ptr);} + private: + ptrholder_t(const t_self &) {throw pfc::exception_not_implemented();} + const t_self & operator=(const t_self & ) {throw pfc::exception_not_implemented();} + + T* m_ptr; + }; + + //avoid "void&" breakage + template + class ptrholder_t { + private: + typedef void T; + typedef ptrholder_t t_self; + public: + inline ptrholder_t(T* p_ptr) : m_ptr(p_ptr) {} + inline ptrholder_t() : m_ptr(NULL) {} + inline ~ptrholder_t() {t_releaser::release(m_ptr);} + inline bool is_valid() const {return m_ptr != NULL;} + inline bool is_empty() const {return m_ptr == NULL;} + inline T* operator->() const {return m_ptr;} + inline T* get_ptr() const {return m_ptr;} + inline void release() {t_releaser::release(replace_null_t(m_ptr));;} + inline void attach(T * p_ptr) {release(); m_ptr = p_ptr;} + inline const t_self & operator=(T * p_ptr) {set(p_ptr);return *this;} + inline T* detach() {return pfc::replace_null_t(m_ptr);} + + inline t_self & operator<<(t_self & p_source) {attach(p_source.detach());return *this;} + inline t_self & operator>>(t_self & p_dest) {p_dest.attach(detach());return *this;} + + //deprecated + inline void set(T * p_ptr) {attach(p_ptr);} + private: + ptrholder_t(const t_self &) {throw pfc::exception_not_implemented();} + const t_self & operator=(const t_self & ) {throw pfc::exception_not_implemented();} + + T* m_ptr; + }; + + void crash(); + void outputDebugLine(const char * msg); + + class debugLog : public string_formatter { + public: + ~debugLog() { outputDebugLine(this->get_ptr()); } + }; +#define PFC_DEBUGLOG ::pfc::debugLog()._formatter() + + + template + class int_container_helper { + public: + int_container_helper() : m_val(p_initval) {} + t_type m_val; + }; + + + + //warning: not multi-thread-safe + template + class instanceTracker : public t_base { + private: + typedef instanceTracker t_self; + public: + TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD_WITH_INITIALIZER(instanceTracker,t_base,{g_list += this;}); + + instanceTracker(const t_self & p_other) : t_base( (const t_base &)p_other) {g_list += this;} + ~instanceTracker() {g_list -= this;} + + typedef pfc::avltree_t t_list; + static const t_list & instanceList() {return g_list;} + template static void forEach(t_callback & p_callback) {instanceList().enumerate(p_callback);} + private: + static t_list g_list; + }; + + template + typename instanceTracker::t_list instanceTracker::g_list; + + + //warning: not multi-thread-safe + template + class instanceTrackerV2 { + private: + typedef instanceTrackerV2 t_self; + public: + instanceTrackerV2(const t_self & p_other) {g_list += static_cast(this);} + instanceTrackerV2() {g_list += static_cast(this);} + ~instanceTrackerV2() {g_list -= static_cast(this);} + + typedef pfc::avltree_t t_instanceList; + static const t_instanceList & instanceList() {return g_list;} + template static void forEach(t_callback & p_callback) {instanceList().enumerate(p_callback);} + private: + static t_instanceList g_list; + }; + + template + typename instanceTrackerV2::t_instanceList instanceTrackerV2::g_list; + + + struct objDestructNotifyData { + bool m_flag; + objDestructNotifyData * m_next; + + }; + class objDestructNotify { + public: + objDestructNotify() : m_data() {} + ~objDestructNotify() { + set(); + } + + void set() { + objDestructNotifyData * w = m_data; + while(w) { + w->m_flag = true; w = w->m_next; + } + } + objDestructNotifyData * m_data; + }; + + class objDestructNotifyScope : private objDestructNotifyData { + public: + objDestructNotifyScope(objDestructNotify &obj) : m_obj(&obj) { + m_next = m_obj->m_data; + m_obj->m_data = this; + } + ~objDestructNotifyScope() { + if (!m_flag) m_obj->m_data = m_next; + } + bool get() const {return m_flag;} + PFC_CLASS_NOT_COPYABLE_EX(objDestructNotifyScope) + private: + objDestructNotify * m_obj; + + }; + + + class bigmem { + public: + enum {slice = 1024*1024}; + bigmem() : m_size() {} + ~bigmem() {clear();} + + void resize(size_t newSize) { + clear(); + m_data.set_size( (newSize + slice - 1) / slice ); + m_data.fill_null(); + for(size_t walk = 0; walk < m_data.get_size(); ++walk) { + size_t thisSlice = slice; + if (walk + 1 == m_data.get_size()) { + size_t cut = newSize % slice; + if (cut) thisSlice = cut; + } + void* ptr = malloc(thisSlice); + if (ptr == NULL) {clear(); throw std::bad_alloc();} + m_data[walk] = (uint8_t*)ptr; + } + m_size = newSize; + } + size_t size() const {return m_size;} + void clear() { + for(size_t walk = 0; walk < m_data.get_size(); ++walk) free(m_data[walk]); + m_data.set_size(0); + m_size = 0; + } + void read(void * ptrOut, size_t bytes, size_t offset) { + PFC_ASSERT( offset + bytes <= size() ); + uint8_t * outWalk = (uint8_t*) ptrOut; + while(bytes > 0) { + size_t o1 = offset / slice, o2 = offset % slice; + size_t delta = slice - o2; if (delta > bytes) delta = bytes; + memcpy(outWalk, m_data[o1] + o2, delta); + offset += delta; + bytes -= delta; + outWalk += delta; + } + } + void write(const void * ptrIn, size_t bytes, size_t offset) { + PFC_ASSERT( offset + bytes <= size() ); + const uint8_t * inWalk = (const uint8_t*) ptrIn; + while(bytes > 0) { + size_t o1 = offset / slice, o2 = offset % slice; + size_t delta = slice - o2; if (delta > bytes) delta = bytes; + memcpy(m_data[o1] + o2, inWalk, delta); + offset += delta; + bytes -= delta; + inWalk += delta; + } + } + uint8_t * _slicePtr(size_t which) {return m_data[which];} + size_t _sliceCount() {return m_data.get_size();} + size_t _sliceSize(size_t which) { + if (which + 1 == _sliceCount()) { + size_t s = m_size % slice; + if (s) return s; + } + return slice; + } + private: + array_t m_data; + size_t m_size; + + PFC_CLASS_NOT_COPYABLE_EX(bigmem) + }; + + + double exp_int( double base, int exp ); +} + +#endif \ No newline at end of file diff --git a/SDK/pfc/pathUtils.cpp b/SDK/pfc/pathUtils.cpp new file mode 100644 index 0000000..feb47a6 --- /dev/null +++ b/SDK/pfc/pathUtils.cpp @@ -0,0 +1,187 @@ +#include "pfc.h" + +namespace pfc { namespace io { namespace path { + +#ifdef _WINDOWS +static const string g_pathSeparators ("\\/|"); +#else +static const string g_pathSeparators ("/"); +#endif + +string getFileName(string path) { + t_size split = path.lastIndexOfAnyChar(g_pathSeparators); + if (split == ~0) return path; + else return path.subString(split+1); +} +string getFileNameWithoutExtension(string path) { + string fn = getFileName(path); + t_size split = fn.lastIndexOf('.'); + if (split == ~0) return fn; + else return fn.subString(0,split); +} +string getFileExtension(string path) { + string fn = getFileName(path); + t_size split = fn.lastIndexOf('.'); + if (split == ~0) return ""; + else return fn.subString(split); +} +string getDirectory(string filePath) {return getParent(filePath);} + +string getParent(string filePath) { + t_size split = filePath.lastIndexOfAnyChar(g_pathSeparators); + if (split == ~0) return ""; +#ifdef _WINDOWS + if (split > 0 && getIllegalNameChars().contains(filePath[split-1])) { + if (split + 1 < filePath.length()) return filePath.subString(0,split+1); + else return ""; + } +#endif + return filePath.subString(0,split); +} +string combine(string basePath,string fileName) { + if (basePath.length() > 0) { + if (!isSeparator(basePath.lastChar())) { + basePath += getDefaultSeparator(); + } + return basePath + fileName; + } else { + //todo? + return fileName; + } +} + +bool isSeparator(char c) { + return g_pathSeparators.indexOf(c) != ~0; +} +string getSeparators() { + return g_pathSeparators; +} + +static string replaceIllegalChar(char c) { + switch(c) { + case '*': + return "x"; + case '\"': + return "\'\'"; + case ':': + case '/': + case '\\': + return "-"; + default: + return "_"; + } +} +string replaceIllegalPathChars(string fn) { + string illegal = getIllegalNameChars(); + string separators = getSeparators(); + string_formatter output; + for(t_size walk = 0; walk < fn.length(); ++walk) { + const char c = fn[walk]; + if (separators.contains(c)) { + output.add_byte(getDefaultSeparator()); + } else if (string::isNonTextChar(c) || illegal.contains(c)) { + string replacement = replaceIllegalChar(c); + if (replacement.containsAnyChar(illegal)) /*per-OS weirdness security*/ replacement = "_"; + output << replacement.ptr(); + } else { + output.add_byte(c); + } + } + return output.toString(); +} + +string replaceIllegalNameChars(string fn, bool allowWC) { + const string illegal = getIllegalNameChars(allowWC); + string_formatter output; + for(t_size walk = 0; walk < fn.length(); ++walk) { + const char c = fn[walk]; + if (string::isNonTextChar(c) || illegal.contains(c)) { + string replacement = replaceIllegalChar(c); + if (replacement.containsAnyChar(illegal)) /*per-OS weirdness security*/ replacement = "_"; + output << replacement.ptr(); + } else { + output.add_byte(c); + } + } + return output.toString(); +} + +bool isInsideDirectory(pfc::string directory, pfc::string inside) { + //not very efficient + string walk = inside; + for(;;) { + walk = getParent(walk); + if (walk == "") return false; + if (equals(directory,walk)) return true; + } +} +bool isDirectoryRoot(string path) { + return getParent(path).isEmpty(); +} +//OS-dependant part starts here + + +char getDefaultSeparator() { +#ifdef _WINDOWS + return '\\'; +#else + return '/'; +#endif +} + +static const string g_illegalNameChars(g_pathSeparators +#ifdef _WINDOWS + + ":<>*?\"" +#else + + "*?" +#endif + ); + +static const string g_illegalNameChars_noWC(g_pathSeparators +#ifdef _WINDOWS + + ":<>?\"" +#endif + ); +string getIllegalNameChars(bool allowWC) { + return allowWC ? g_illegalNameChars_noWC : g_illegalNameChars; +} + +#ifdef _WINDOWS +static bool isIllegalTrailingChar(char c) { + return c == ' ' || c == '.'; +} +#endif + +string validateFileName(string name, bool allowWC) { + for(t_size walk = 0; name[walk];) { + if (name[walk] == '?') { + t_size end = walk; + do { ++end; } while(name[end] == '?'); + name = name.subString(0, walk) + name.subString(end); + } else { + ++walk; + } + } +#ifdef _WINDOWS + name = replaceIllegalNameChars(name, allowWC); + if (name.length() > 0) { + t_size end = name.length(); + while(end > 0) { + if (!isIllegalTrailingChar(name[end-1])) break; + --end; + } + t_size begin = 0; + while(begin < end) { + if (!isIllegalTrailingChar(name[begin])) break; + ++begin; + } + if (end < name.length() || begin > 0) name = name.subString(begin,end - begin); + } + if (name.isEmpty()) name = "_"; + return name; +#else + return replaceIllegalNameChars(name); +#endif +} + +}}} diff --git a/SDK/pfc/pathUtils.h b/SDK/pfc/pathUtils.h new file mode 100644 index 0000000..4f084e1 --- /dev/null +++ b/SDK/pfc/pathUtils.h @@ -0,0 +1,32 @@ +namespace pfc { + namespace io { + namespace path { +#ifdef _WINDOWS + typedef string::comparatorCaseInsensitive comparator; +#else + typedef string::comparatorCaseSensitive comparator; // wild assumption +#endif + + + string getFileName(string path); + string getFileNameWithoutExtension(string path); + string getFileExtension(string path); + string getParent(string filePath); + string getDirectory(string filePath);//same as getParent() + string combine(string basePath,string fileName); + char getDefaultSeparator(); + string getSeparators(); + bool isSeparator(char c); + string getIllegalNameChars(bool allowWC = false); + string replaceIllegalNameChars(string fn, bool allowWC = false); + string replaceIllegalPathChars(string fn); + bool isInsideDirectory(pfc::string directory, pfc::string inside); + bool isDirectoryRoot(string path); + string validateFileName(string name, bool allowWC = false);//removes various illegal things from the name, exact effect depends on the OS, includes removal of the invalid characters + + template inline bool equals(const t1 & v1, const t2 & v2) {return comparator::compare(v1,v2) == 0;} + + template inline int compare( t1 const & p1, t2 const & p2 ) {return comparator::compare(p1, p2); } + } + } +} diff --git a/SDK/pfc/pfc-license.txt b/SDK/pfc/pfc-license.txt new file mode 100644 index 0000000..00d2e13 --- /dev/null +++ b/SDK/pfc/pfc-license.txt @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to \ No newline at end of file diff --git a/SDK/pfc/pfc-readme.txt b/SDK/pfc/pfc-readme.txt new file mode 100644 index 0000000..958d16a --- /dev/null +++ b/SDK/pfc/pfc-readme.txt @@ -0,0 +1,5 @@ +PFC : Peter's Foundation Classes + +A library of loosely connected classes used by foobar2000 codebase; freely available and reusable for other projects. + +PFC is not state-of-art code. Many parts of it exist only to keep old bits of foobar2000 codebase ( also third party foobar2000 components ) compiling without modification. For an example, certain classes predating 'pfc' namespace use exist outside the namespace. diff --git a/SDK/pfc/pfc.h b/SDK/pfc/pfc.h new file mode 100644 index 0000000..94f1cb2 --- /dev/null +++ b/SDK/pfc/pfc.h @@ -0,0 +1,220 @@ +#ifndef ___PFC_H___ +#define ___PFC_H___ + +// Global flag - whether it's OK to leak static objects as they'll be released anyway by process death +#ifndef PFC_LEAK_STATIC_OBJECTS +#define PFC_LEAK_STATIC_OBJECTS 1 +#endif + + +#ifdef __clang__ +// Suppress a warning for a common practice in pfc/fb2k code +#pragma clang diagnostic ignored "-Wdelete-non-virtual-dtor" +#endif + +#if !defined(_WINDOWS) && (defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_WIN32_WCE)) +#define _WINDOWS +#endif + + +#define PFC_DLL_EXPORT + +#ifdef _WINDOWS + +#ifndef STRICT +#define STRICT +#endif + +#ifndef _SYS_GUID_OPERATOR_EQ_ +#define _NO_SYS_GUID_OPERATOR_EQ_ //fix retarded warning with operator== on GUID returning int +#endif + +#include + +#if !defined(PFC_WINDOWS_STORE_APP) && !defined(PFC_WINDOWS_DESKTOP_APP) + +#ifdef WINAPI_FAMILY_PARTITION +#if ! WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +#define PFC_WINDOWS_STORE_APP // Windows store or Windows phone app, not a desktop app +#endif // #if ! WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +#endif // #ifdef WINAPI_FAMILY_PARTITION + +#ifndef PFC_WINDOWS_STORE_APP +#define PFC_WINDOWS_DESKTOP_APP +#endif + +#endif // #if !defined(PFC_WINDOWS_STORE_APP) && !defined(PFC_WINDOWS_DESKTOP_APP) + +#ifndef _SYS_GUID_OPERATOR_EQ_ +__inline bool __InlineIsEqualGUID(REFGUID rguid1, REFGUID rguid2) +{ + return ( + ((unsigned long *) &rguid1)[0] == ((unsigned long *) &rguid2)[0] && + ((unsigned long *) &rguid1)[1] == ((unsigned long *) &rguid2)[1] && + ((unsigned long *) &rguid1)[2] == ((unsigned long *) &rguid2)[2] && + ((unsigned long *) &rguid1)[3] == ((unsigned long *) &rguid2)[3]); +} + +inline bool operator==(REFGUID guidOne, REFGUID guidOther) {return __InlineIsEqualGUID(guidOne,guidOther);} +inline bool operator!=(REFGUID guidOne, REFGUID guidOther) {return !__InlineIsEqualGUID(guidOne,guidOther);} +#endif + +#include + +#else + +#include +#include +#include +#include // memcmp + +typedef struct { + uint32_t Data1; + uint16_t Data2; + uint16_t Data3; + uint8_t Data4[ 8 ]; + } GUID; //same as win32 GUID + +inline bool operator==(const GUID & p_item1,const GUID & p_item2) { + return memcmp(&p_item1,&p_item2,sizeof(GUID)) == 0; +} + +inline bool operator!=(const GUID & p_item1,const GUID & p_item2) { + return memcmp(&p_item1,&p_item2,sizeof(GUID)) != 0; +} + +#endif + + + +#define PFC_MEMORY_SPACE_LIMIT ((t_uint64)1<<(sizeof(void*)*8-1)) + +#define PFC_ALLOCA_LIMIT (4096) + +#define INDEX_INVALID ((unsigned)(-1)) + + +#include +#include +#include + +#define _PFC_WIDESTRING(_String) L ## _String +#define PFC_WIDESTRING(_String) _PFC_WIDESTRING(_String) + +#if defined(_DEBUG) || defined(DEBUG) +#define PFC_DEBUG 1 +#else +#define PFC_DEBUG 0 +#endif + +#if ! PFC_DEBUG +#define PFC_ASSERT(_Expression) ((void)0) +#define PFC_ASSERT_SUCCESS(_Expression) (void)( (_Expression), 0) +#define PFC_ASSERT_NO_EXCEPTION(_Expression) { _Expression; } +#else + +#ifdef _WIN32 +namespace pfc { void myassert_win32(const wchar_t * _Message, const wchar_t *_File, unsigned _Line); } +#define PFC_ASSERT(_Expression) (void)( (!!(_Expression)) || (pfc::myassert_win32(PFC_WIDESTRING(#_Expression), PFC_WIDESTRING(__FILE__), __LINE__), 0) ) +#define PFC_ASSERT_SUCCESS(_Expression) PFC_ASSERT(_Expression) +#else +namespace pfc { void myassert (const char * _Message, const char *_File, unsigned _Line); } +#define PFC_ASSERT(_Expression) (void)( (!!(_Expression)) || (pfc::myassert(#_Expression, __FILE__, __LINE__), 0) ) +#define PFC_ASSERT_SUCCESS(_Expression) PFC_ASSERT( _Expression ) +#endif + +#define PFC_ASSERT_NO_EXCEPTION(_Expression) { try { _Expression; } catch(...) { PFC_ASSERT(!"Should not get here - unexpected exception"); } } +#endif + +#ifdef _MSC_VER + +#if PFC_DEBUG +#define NOVTABLE +#else +#define NOVTABLE _declspec(novtable) +#endif + +#if PFC_DEBUG +#define ASSUME(X) PFC_ASSERT(X) +#else +#define ASSUME(X) __assume(X) +#endif + +#define PFC_DEPRECATE(X) // __declspec(deprecated(X)) don't do this since VS2015 defaults to erroring these +#define PFC_NORETURN __declspec(noreturn) +#define PFC_NOINLINE __declspec(noinline) +#else + +#define NOVTABLE +#define ASSUME(X) PFC_ASSERT(X) +#define PFC_DEPRECATE(X) +#define PFC_NORETURN __attribute__ ((noreturn)) +#define PFC_NOINLINE + +#endif + +namespace pfc { + void selftest(); +} + +#include "int_types.h" +#include "traits.h" +#include "bit_array.h" +#include "primitives.h" +#include "alloc.h" +#include "array.h" +#include "bit_array_impl.h" +#include "binary_search.h" +#include "bsearch_inline.h" +#include "bsearch.h" +#include "sort.h" +#include "order_helper.h" +#include "list.h" +#include "ptr_list.h" +#include "string_base.h" +#include "string_list.h" +#include "ref_counter.h" +#include "iterators.h" +#include "avltree.h" +#include "map.h" +#include "bit_array_impl_part2.h" +#include "timers.h" +#include "guid.h" +#include "byte_order_helper.h" +#include "other.h" +#include "chain_list_v2.h" +#include "rcptr.h" +#include "com_ptr_t.h" +#include "string_conv.h" +#include "stringNew.h" +#include "pathUtils.h" +#include "instance_tracker.h" +#include "threads.h" +#include "base64.h" +#include "primitives_part2.h" +#include "cpuid.h" +#include "memalign.h" + +#ifdef _WIN32 +#include "synchro_win.h" +#else +#include "synchro_nix.h" +#endif + +#include "syncd_storage.h" + +#ifdef _WIN32 +#include "win-objects.h" +#else +#include "nix-objects.h" +#endif + +#include "event.h" + +#include "audio_sample.h" +#include "wildcard.h" +#include "filehandle.h" + +#define PFC_INCLUDED 1 + +#endif //___PFC_H___ diff --git a/SDK/pfc/pfc.vcxproj b/SDK/pfc/pfc.vcxproj new file mode 100644 index 0000000..27424c3 --- /dev/null +++ b/SDK/pfc/pfc.vcxproj @@ -0,0 +1,321 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {EBFFFB4E-261D-44D3-B89C-957B31A0BF9C} + pfc + + + + StaticLibrary + false + Unicode + true + v143 + + + StaticLibrary + false + Unicode + v143 + + + StaticLibrary + false + Unicode + true + v143 + + + StaticLibrary + false + Unicode + v143 + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(SolutionDir)$(Configuration)\ + $(Configuration)\ + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + $(SolutionDir)$(Configuration)\ + $(Configuration)\ + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + + + + Disabled + WIN32;_DEBUG;_WINDOWS;PFC_DLL_EXPORTS;%(PreprocessorDefinitions) + EnableFastChecks + Use + pfc.h + Level3 + true + ProgramDatabase + MultiThreadedDebugDLL + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + X64 + + + Disabled + WIN32;_DEBUG;_WINDOWS;PFC_DLL_EXPORTS;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + Use + pfc.h + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + MaxSpeed + WIN32;NDEBUG;_WINDOWS;PFC_DLL_EXPORTS;%(PreprocessorDefinitions) + true + false + Fast + false + Use + pfc.h + Level3 + true + ProgramDatabase + MultiThreadedDLL + NotSet + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + X64 + + + WIN32;NDEBUG;_WINDOWS;PFC_DLL_EXPORTS;%(PreprocessorDefinitions) + true + Fast + false + Use + pfc.h + Level3 + true + MultiThreadedDLL + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Disabled + %(PreprocessorDefinitions) + EnableFastChecks + Disabled + %(PreprocessorDefinitions) + EnableFastChecks + MaxSpeed + %(PreprocessorDefinitions) + MaxSpeed + %(PreprocessorDefinitions) + + + + + Disabled + %(PreprocessorDefinitions) + EnableFastChecks + Disabled + %(PreprocessorDefinitions) + EnableFastChecks + MaxSpeed + %(PreprocessorDefinitions) + MaxSpeed + %(PreprocessorDefinitions) + + + + Disabled + %(PreprocessorDefinitions) + EnableFastChecks + Disabled + %(PreprocessorDefinitions) + EnableFastChecks + MaxSpeed + %(PreprocessorDefinitions) + MaxSpeed + %(PreprocessorDefinitions) + + + + + + Disabled + %(PreprocessorDefinitions) + EnableFastChecks + Disabled + %(PreprocessorDefinitions) + EnableFastChecks + MaxSpeed + %(PreprocessorDefinitions) + MaxSpeed + %(PreprocessorDefinitions) + + + Disabled + %(PreprocessorDefinitions) + EnableFastChecks + Create + Disabled + %(PreprocessorDefinitions) + EnableFastChecks + Create + MaxSpeed + %(PreprocessorDefinitions) + Create + MaxSpeed + %(PreprocessorDefinitions) + Create + + + + + + + + Disabled + %(PreprocessorDefinitions) + EnableFastChecks + Disabled + %(PreprocessorDefinitions) + EnableFastChecks + MaxSpeed + %(PreprocessorDefinitions) + MaxSpeed + %(PreprocessorDefinitions) + + + + + + + + + + + + \ No newline at end of file diff --git a/SDK/pfc/pfc.vcxproj.filters b/SDK/pfc/pfc.vcxproj.filters new file mode 100644 index 0000000..1c05d8d --- /dev/null +++ b/SDK/pfc/pfc.vcxproj.filters @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Doc + + + Doc + + + + + {70b1137d-0c8f-4bb0-8adb-d406ad38bdd0} + + + \ No newline at end of file diff --git a/SDK/pfc/pfc.vcxproj.user b/SDK/pfc/pfc.vcxproj.user new file mode 100644 index 0000000..0f14913 --- /dev/null +++ b/SDK/pfc/pfc.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/SDK/pfc/pp-gettickcount.h b/SDK/pfc/pp-gettickcount.h new file mode 100644 index 0000000..453ba5f --- /dev/null +++ b/SDK/pfc/pp-gettickcount.h @@ -0,0 +1,16 @@ +#if !defined(PP_GETTICKCOUNT_H_INCLUDED) && defined(_WIN32) +#define PP_GETTICKCOUNT_H_INCLUDED + +namespace PP { +#if _WIN32_WINNT >= 0x600 + typedef uint64_t tickcount_t; + inline tickcount_t getTickCount() { return ::GetTickCount64(); } +#else +#define PFC_TICKCOUNT_32BIT + typedef uint32_t tickcount_t; + inline tickcount_t getTickCount() { return ::GetTickCount(); } +#endif + +} + +#endif // #if !defined(PP_GETTICKCOUNT_H_INCLUDED) && defined(_WIN32) \ No newline at end of file diff --git a/SDK/pfc/pp-winapi.h b/SDK/pfc/pp-winapi.h new file mode 100644 index 0000000..225c8b4 --- /dev/null +++ b/SDK/pfc/pp-winapi.h @@ -0,0 +1,61 @@ +#if !defined(PP_WINAPI_H_INCLUDED) && defined(_WIN32) +#define PP_WINAPI_H_INCLUDED + +#ifdef WINAPI_FAMILY_PARTITION + +#if ! WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) + +inline HANDLE CreateEvent(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCTSTR lpName) { + DWORD flags = 0; + if (bManualReset) flags |= CREATE_EVENT_MANUAL_RESET; + if (bInitialState) flags |= CREATE_EVENT_INITIAL_SET; + DWORD rights = SYNCHRONIZE | EVENT_MODIFY_STATE; + return CreateEventEx(lpEventAttributes, lpName, flags, rights); +} + +inline DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds) { + return WaitForSingleObjectEx(hHandle, dwMilliseconds, FALSE); +} + +inline DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE *lpHandles, BOOL bWaitAll, DWORD dwMilliseconds) { + return WaitForMultipleObjectsEx(nCount, lpHandles, bWaitAll, dwMilliseconds, FALSE); +} + +inline void InitializeCriticalSection(LPCRITICAL_SECTION lpCriticalSection) { + InitializeCriticalSectionEx(lpCriticalSection, 0, 0); +} + +inline HANDLE FindFirstFile(LPCTSTR lpFileName, LPWIN32_FIND_DATA lpFindFileData) { + return FindFirstFileEx(lpFileName, FindExInfoStandard, lpFindFileData, FindExSearchNameMatch, NULL, 0); +} + +inline BOOL GetFileSizeEx(HANDLE hFile, PLARGE_INTEGER lpFileSize) { + FILE_STANDARD_INFO info; + if (!GetFileInformationByHandleEx(hFile, FileStandardInfo, &info, sizeof(info))) return FALSE; + *lpFileSize = info.EndOfFile; + return TRUE; +} + +inline HANDLE CreateFileW(LPCTSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) { + CREATEFILE2_EXTENDED_PARAMETERS arg = {}; + arg.dwSize = sizeof(arg); + arg.hTemplateFile = hTemplateFile; + arg.lpSecurityAttributes = lpSecurityAttributes; + arg.dwFileAttributes = dwFlagsAndAttributes & 0x0000FFFF; + arg.dwFileFlags = dwFlagsAndAttributes & 0xFFFF0000; + return CreateFile2(lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, &arg); +} + +inline DWORD GetFileAttributesW(const wchar_t * path) { + WIN32_FILE_ATTRIBUTE_DATA data = {}; + if (!GetFileAttributesEx(path, GetFileExInfoStandard, &data)) return 0xFFFFFFFF; + return data.dwFileAttributes; +} + +#define GetFileAttributes GetFileAttributesW + +#endif // #if ! WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) + +#endif // #ifdef WINAPI_FAMILY_PARTITION + +#endif // !defined(PP_WINAPI_H_INCLUDED) && defined(_WIN32) \ No newline at end of file diff --git a/SDK/pfc/primitives.h b/SDK/pfc/primitives.h new file mode 100644 index 0000000..ac004e5 --- /dev/null +++ b/SDK/pfc/primitives.h @@ -0,0 +1,882 @@ +#define tabsize(x) ((size_t)(sizeof(x)/sizeof(*x))) +#define PFC_TABSIZE(x) ((size_t)(sizeof(x)/sizeof(*x))) + +#define TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD_WITH_INITIALIZER(THISCLASS,MEMBER,INITIALIZER) \ + THISCLASS() : MEMBER() INITIALIZER \ + template THISCLASS(const t_param1 & p_param1) : MEMBER(p_param1) INITIALIZER \ + template THISCLASS(const t_param1 & p_param1,const t_param2 & p_param2) : MEMBER(p_param1,p_param2) INITIALIZER \ + template THISCLASS(const t_param1 & p_param1,const t_param2 & p_param2,const t_param3 & p_param3) : MEMBER(p_param1,p_param2,p_param3) INITIALIZER \ + template THISCLASS(const t_param1 & p_param1,const t_param2 & p_param2,const t_param3 & p_param3,const t_param4 & p_param4) : MEMBER(p_param1,p_param2,p_param3,p_param4) INITIALIZER \ + template THISCLASS(const t_param1 & p_param1,const t_param2 & p_param2,const t_param3 & p_param3,const t_param4 & p_param4,const t_param5 & p_param5) : MEMBER(p_param1,p_param2,p_param3,p_param4,p_param5) INITIALIZER \ + template THISCLASS(const t_param1 & p_param1,const t_param2 & p_param2,const t_param3 & p_param3,const t_param4 & p_param4,const t_param5 & p_param5,const t_param6 & p_param6) : MEMBER(p_param1,p_param2,p_param3,p_param4,p_param5,p_param6) INITIALIZER \ + template THISCLASS(const t_param1 & p_param1,const t_param2 & p_param2,const t_param3 & p_param3,const t_param4 & p_param4,const t_param5 & p_param5,const t_param6 & p_param6,const t_param7 & p_param7) : MEMBER(p_param1,p_param2,p_param3,p_param4,p_param5,p_param6,p_param7) INITIALIZER \ + template THISCLASS(const t_param1 & p_param1,const t_param2 & p_param2,const t_param3 & p_param3,const t_param4 & p_param4,const t_param5 & p_param5,const t_param6 & p_param6,const t_param7 & p_param7, const t_param8 & p_param8) : MEMBER(p_param1,p_param2,p_param3,p_param4,p_param5,p_param6,p_param7, p_param8) INITIALIZER + +#define TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(THISCLASS,MEMBER) TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD_WITH_INITIALIZER(THISCLASS,MEMBER,{}) + + +#ifdef _WIN32 + +#ifndef _MSC_VER +#error MSVC expected +#endif + +// MSVC specific - part of fb2k ABI - cannot ever change on MSVC/Windows + +#define PFC_DECLARE_EXCEPTION(NAME,BASECLASS,DEFAULTMSG) \ +class NAME : public BASECLASS { \ +public: \ + static const char * g_what() {return DEFAULTMSG;} \ + NAME() : BASECLASS(DEFAULTMSG,0) {} \ + NAME(const char * p_msg) : BASECLASS(p_msg) {} \ + NAME(const char * p_msg,int) : BASECLASS(p_msg,0) {} \ + NAME(const NAME & p_source) : BASECLASS(p_source) {} \ +}; + +namespace pfc { + template PFC_NORETURN inline void throw_exception_with_message(const char * p_message) { + throw t_exception(p_message); + } +} + +#else + +#define PFC_DECLARE_EXCEPTION(NAME,BASECLASS,DEFAULTMSG) \ +class NAME : public BASECLASS { \ +public: \ + static const char * g_what() {return DEFAULTMSG;} \ + const char* what() const throw() {return DEFAULTMSG;} \ +}; + +namespace pfc { + template class __exception_with_message_t : public t_base { + private: typedef __exception_with_message_t t_self; + public: + __exception_with_message_t(const char * p_message) : m_message(NULL) { + set_message(p_message); + } + __exception_with_message_t() : m_message(NULL) {} + __exception_with_message_t(const t_self & p_source) : m_message(NULL) {set_message(p_source.m_message);} + + const char* what() const throw() {return m_message != NULL ? m_message : "unnamed exception";} + + const t_self & operator=(const t_self & p_source) {set_message(p_source.m_message);} + + ~__exception_with_message_t() throw() {cleanup();} + + private: + void set_message(const char * p_message) throw() { + cleanup(); + if (p_message != NULL) m_message = strdup(p_message); + } + void cleanup() throw() { + if (m_message != NULL) {free(m_message); m_message = NULL;} + } + char * m_message; + }; + template PFC_NORETURN void throw_exception_with_message(const char * p_message) { + throw __exception_with_message_t(p_message); + } +} +#endif + +namespace pfc { + + template class assert_same_type; + template class assert_same_type {}; + + template + class is_same_type { public: enum {value = false}; }; + template + class is_same_type { public: enum {value = true}; }; + + template class static_assert_t; + template<> class static_assert_t {}; + +#define PFC_STATIC_ASSERT(X) { ::pfc::static_assert_t<(X)>(); } + + template + void assert_raw_type() {static_assert_t< !traits_t::needs_constructor && !traits_t::needs_destructor >();} + + template class assert_byte_type; + template<> class assert_byte_type {}; + template<> class assert_byte_type {}; + template<> class assert_byte_type {}; + + + template void __unsafe__memcpy_t(t_type * p_dst,const t_type * p_src,t_size p_count) { + ::memcpy(reinterpret_cast(p_dst), reinterpret_cast(p_src), p_count * sizeof(t_type)); + } + + template void __unsafe__in_place_destructor_t(t_type & p_item) throw() { + if (traits_t::needs_destructor) try{ p_item.~t_type(); } catch(...) {} + } + + template void __unsafe__in_place_constructor_t(t_type & p_item) { + if (traits_t::needs_constructor) { + t_type * ret = new(&p_item) t_type; + PFC_ASSERT(ret == &p_item); + (void) ret; // suppress warning + } + } + + template void __unsafe__in_place_destructor_array_t(t_type * p_items, t_size p_count) throw() { + if (traits_t::needs_destructor) { + t_type * walk = p_items; + for(t_size n=p_count;n;--n) __unsafe__in_place_destructor_t(*(walk++)); + } + } + + template t_type * __unsafe__in_place_constructor_array_t(t_type * p_items,t_size p_count) { + if (traits_t::needs_constructor) { + t_size walkptr = 0; + try { + for(walkptr=0;walkptr t_type * __unsafe__in_place_resize_array_t(t_type * p_items,t_size p_from,t_size p_to) { + if (p_from < p_to) __unsafe__in_place_constructor_array_t(p_items + p_from, p_to - p_from); + else if (p_from > p_to) __unsafe__in_place_destructor_array_t(p_items + p_to, p_from - p_to); + return p_items; + } + + template void __unsafe__in_place_constructor_copy_t(t_type & p_item,const t_copy & p_copyfrom) { + if (traits_t::needs_constructor) { + t_type * ret = new(&p_item) t_type(p_copyfrom); + PFC_ASSERT(ret == &p_item); + (void) ret; // suppress warning + } else { + p_item = p_copyfrom; + } + } + + template t_type * __unsafe__in_place_constructor_array_copy_t(t_type * p_items,t_size p_count, const t_copy * p_copyfrom) { + t_size walkptr = 0; + try { + for(walkptr=0;walkptr t_type * __unsafe__in_place_constructor_array_copy_partial_t(t_type * p_items,t_size p_count, const t_copy * p_copyfrom,t_size p_copyfrom_count) { + if (p_copyfrom_count > p_count) p_copyfrom_count = p_count; + __unsafe__in_place_constructor_array_copy_t(p_items,p_copyfrom_count,p_copyfrom); + try { + __unsafe__in_place_constructor_array_t(p_items + p_copyfrom_count,p_count - p_copyfrom_count); + } catch(...) { + __unsafe__in_place_destructor_array_t(p_items,p_copyfrom_count); + throw; + } + return p_items; + } + + template t_ret implicit_cast(t_ret val) {return val;} + + template + t_ret * safe_ptr_cast(t_param * p_param) { + if (pfc::is_same_type::value) return p_param; + else { + if (p_param == NULL) return NULL; + else return p_param; + } + } + + typedef std::exception exception; + + PFC_DECLARE_EXCEPTION(exception_overflow,exception,"Overflow"); + PFC_DECLARE_EXCEPTION(exception_bug_check,exception,"Bug check"); + PFC_DECLARE_EXCEPTION(exception_invalid_params,exception_bug_check,"Invalid parameters"); + PFC_DECLARE_EXCEPTION(exception_unexpected_recursion,exception_bug_check,"Unexpected recursion"); + PFC_DECLARE_EXCEPTION(exception_not_implemented,exception_bug_check,"Feature not implemented"); + PFC_DECLARE_EXCEPTION(exception_dynamic_assert,exception_bug_check,"dynamic_assert failure"); + + template + t_ret downcast_guarded(const t_param & p_param) { + t_ret temp = (t_ret) p_param; + if ((t_param) temp != p_param) throw exception_overflow(); + return temp; + } + + template + t_ret downcast_guarded_ex(const t_param & p_param) { + t_ret temp = (t_ret) p_param; + if ((t_param) temp != p_param) throw t_exception(); + return temp; + } + + template + void accumulate_guarded(t_acc & p_acc, const t_add & p_add) { + t_acc delta = downcast_guarded(p_add); + delta += p_acc; + if (delta < p_acc) throw exception_overflow(); + p_acc = delta; + } + + //deprecated + inline void bug_check_assert(bool p_condition, const char * p_msg) { + if (!p_condition) { + PFC_ASSERT(0); + throw_exception_with_message(p_msg); + } + } + //deprecated + inline void bug_check_assert(bool p_condition) { + if (!p_condition) { + PFC_ASSERT(0); + throw exception_bug_check(); + } + } + + inline void dynamic_assert(bool p_condition, const char * p_msg) { + if (!p_condition) { + PFC_ASSERT(0); + throw_exception_with_message(p_msg); + } + } + inline void dynamic_assert(bool p_condition) { + if (!p_condition) { + PFC_ASSERT(0); + throw exception_dynamic_assert(); + } + } + + template + inline void swap_multi_t(T * p_buffer1,T * p_buffer2,t_size p_size) { + T * walk1 = p_buffer1, * walk2 = p_buffer2; + for(t_size n=p_size;n;--n) { + T temp (* walk1); + *walk1 = *walk2; + *walk2 = temp; + walk1++; walk2++; + } + } + + template + inline void swap_multi_t(T * p_buffer1,T * p_buffer2) { + T * walk1 = p_buffer1, * walk2 = p_buffer2; + for(t_size n=p_size;n;--n) { + T temp (* walk1); + *walk1 = *walk2; + *walk2 = temp; + walk1++; walk2++; + } + } + + + template + inline void __unsafe__swap_raw_t(void * p_object1, void * p_object2) { + if (p_size % sizeof(t_size) == 0) { + swap_multi_t(reinterpret_cast(p_object1),reinterpret_cast(p_object2)); + } else { + swap_multi_t(reinterpret_cast(p_object1),reinterpret_cast(p_object2)); + } + } + + template + inline void swap_t(T & p_item1, T & p_item2) { + if (traits_t::realloc_safe) { + __unsafe__swap_raw_t( reinterpret_cast( &p_item1 ), reinterpret_cast( &p_item2 ) ); + } else { + T temp( std::move(p_item2) ); + p_item2 = std::move(p_item1); + p_item1 = std::move(temp); + } + } + + //! This is similar to plain p_item1 = p_item2; assignment, but optimized for the case where p_item2 content is no longer needed later on. This can be overridden for specific classes for optimal performance. \n + //! p_item2 value is undefined after performing a move_t. For an example, in certain cases move_t will fall back to swap_t. + template + inline void move_t(T & p_item1, T & p_item2) { + typedef traits_t t; + if (t::needs_constructor || t::needs_destructor) { + if (t::realloc_safe) swap_t(p_item1, p_item2); + else p_item1 = std::move( p_item2 ); + } else { + p_item1 = std::move( p_item2 ); + } + } + + template + t_size array_size_t(const t_array & p_array) {return p_array.get_size();} + + template + t_size array_size_t(const t_item (&p_array)[p_width]) {return p_width;} + + template static bool array_isLast(const t_array & arr, const t_item & item) { + const t_size size = pfc::array_size_t(arr); + return size > 0 && arr[size-1] == item; + } + template static bool array_isFirst(const t_array & arr, const t_item & item) { + const t_size size = pfc::array_size_t(arr); + return size > 0 && arr[0] == item; + } + + template + inline void fill_t(t_array & p_buffer,const t_size p_count, const t_filler & p_filler) { + for(t_size n=0;n + inline void fill_ptr_t(t_array * p_buffer,const t_size p_count, const t_filler & p_filler) { + for(t_size n=0;n + inline int compare_t(const t_item1 & p_item1, const t_item2 & p_item2) { + if (p_item1 < p_item2) return -1; + else if (p_item1 > p_item2) return 1; + else return 0; + } + + //! For use with avltree/map etc. + class comparator_default { + public: + template + inline static int compare(const t_item1 & p_item1,const t_item2 & p_item2) {return pfc::compare_t(p_item1,p_item2);} + }; + + template class comparator_pointer { public: + template static int compare(const t_item1 & p_item1,const t_item2 & p_item2) {return t_comparator::compare(*p_item1,*p_item2);} + }; + + template class comparator_dual { public: + template static int compare(const t_item1 & p_item1,const t_item2 & p_item2) { + int state = t_primary::compare(p_item1,p_item2); + if (state != 0) return state; + return t_secondary::compare(p_item1,p_item2); + } + }; + + class comparator_memcmp { + public: + template + inline static int compare(const t_item1 & p_item1,const t_item2 & p_item2) { + static_assert_t(); + return memcmp(&p_item1,&p_item2,sizeof(t_item1)); + } + }; + + template + t_size subtract_sorted_lists_calculate_count(const t_source1 & p_source1, const t_source2 & p_source2) { + t_size walk1 = 0, walk2 = 0, walk_out = 0; + const t_size max1 = p_source1.get_size(), max2 = p_source2.get_size(); + for(;;) { + int state; + if (walk1 < max1 && walk2 < max2) { + state = pfc::compare_t(p_source1[walk1],p_source2[walk2]); + } else if (walk1 < max1) { + state = -1; + } else if (walk2 < max2) { + state = 1; + } else { + break; + } + if (state < 0) walk_out++; + if (state <= 0) walk1++; + if (state >= 0) walk2++; + } + return walk_out; + } + + //! Subtracts p_source2 contents from p_source1 and stores result in p_destination. Both source lists must be sorted. + //! Note: duplicates will be carried over (and ignored for p_source2). + template + void subtract_sorted_lists(t_destination & p_destination,const t_source1 & p_source1, const t_source2 & p_source2) { + p_destination.set_size(subtract_sorted_lists_calculate_count(p_source1,p_source2)); + t_size walk1 = 0, walk2 = 0, walk_out = 0; + const t_size max1 = p_source1.get_size(), max2 = p_source2.get_size(); + for(;;) { + int state; + if (walk1 < max1 && walk2 < max2) { + state = pfc::compare_t(p_source1[walk1],p_source2[walk2]); + } else if (walk1 < max1) { + state = -1; + } else if (walk2 < max2) { + state = 1; + } else { + break; + } + + + if (state < 0) p_destination[walk_out++] = p_source1[walk1]; + if (state <= 0) walk1++; + if (state >= 0) walk2++; + } + } + + template + t_size merge_sorted_lists_calculate_count(const t_source1 & p_source1, const t_source2 & p_source2) { + t_size walk1 = 0, walk2 = 0, walk_out = 0; + const t_size max1 = p_source1.get_size(), max2 = p_source2.get_size(); + for(;;) { + int state; + if (walk1 < max1 && walk2 < max2) { + state = pfc::compare_t(p_source1[walk1],p_source2[walk2]); + } else if (walk1 < max1) { + state = -1; + } else if (walk2 < max2) { + state = 1; + } else { + break; + } + if (state <= 0) walk1++; + if (state >= 0) walk2++; + walk_out++; + } + return walk_out; + } + + //! Merges p_source1 and p_source2, storing content in p_destination. Both source lists must be sorted. + //! Note: duplicates will be carried over. + template + void merge_sorted_lists(t_destination & p_destination,const t_source1 & p_source1, const t_source2 & p_source2) { + p_destination.set_size(merge_sorted_lists_calculate_count(p_source1,p_source2)); + t_size walk1 = 0, walk2 = 0, walk_out = 0; + const t_size max1 = p_source1.get_size(), max2 = p_source2.get_size(); + for(;;) { + int state; + if (walk1 < max1 && walk2 < max2) { + state = pfc::compare_t(p_source1[walk1],p_source2[walk2]); + } else if (walk1 < max1) { + state = -1; + } else if (walk2 < max2) { + state = 1; + } else { + break; + } + if (state < 0) { + p_destination[walk_out] = p_source1[walk1++]; + } else if (state > 0) { + p_destination[walk_out] = p_source2[walk2++]; + } else { + p_destination[walk_out] = p_source1[walk1]; + walk1++; walk2++; + } + walk_out++; + } + } + + + + template + inline t_size append_t(t_array & p_array,const T & p_item) + { + t_size old_count = p_array.get_size(); + p_array.set_size(old_count + 1); + p_array[old_count] = p_item; + return old_count; + } + + template + inline t_size append_swap_t(t_array & p_array,T & p_item) + { + t_size old_count = p_array.get_size(); + p_array.set_size(old_count + 1); + swap_t(p_array[old_count],p_item); + return old_count; + } + + template + inline t_size insert_uninitialized_t(t_array & p_array,t_size p_index) { + t_size old_count = p_array.get_size(); + if (p_index > old_count) p_index = old_count; + p_array.set_size(old_count + 1); + for(t_size n=old_count;n>p_index;n--) move_t(p_array[n], p_array[n-1]); + return p_index; + } + + template + inline t_size insert_t(t_array & p_array,const T & p_item,t_size p_index) { + t_size old_count = p_array.get_size(); + if (p_index > old_count) p_index = old_count; + p_array.set_size(old_count + 1); + for(t_size n=old_count;n>p_index;n--) + move_t(p_array[n], p_array[n-1]); + p_array[p_index] = p_item; + return p_index; + } + template + void insert_array_t( array1_t & outArray, size_t insertAt, array2_t const & inArray, size_t inArraySize) { + const size_t oldSize = outArray.get_size(); + if (insertAt > oldSize) insertAt = oldSize; + const size_t newSize = oldSize + inArraySize; + outArray.set_size( newSize ); + for(size_t m = oldSize; m != insertAt; --m) { + move_t( outArray[ m - 1 + inArraySize], outArray[m - 1] ); + } + for(size_t w = 0; w < inArraySize; ++w) { + outArray[ insertAt + w ] = inArray[ w ]; + } + } + + template + inline t_size insert_multi_t(t_array & p_array,const in_array_t & p_items, size_t p_itemCount, t_size p_index) { + const t_size old_count = p_array.get_size(); + const size_t new_count = old_count + p_itemCount; + if (p_index > old_count) p_index = old_count; + p_array.set_size(new_count); + size_t toMove = old_count - p_index; + for(size_t w = 0; w < toMove; ++w) { + move_t( p_array[new_count - 1 - w], p_array[old_count - 1 - w] ); + } + + for(size_t w = 0; w < p_itemCount; ++w) { + p_array[p_index+w] = p_items[w]; + } + + return p_index; + } + template + inline t_size insert_swap_t(t_array & p_array,T & p_item,t_size p_index) { + t_size old_count = p_array.get_size(); + if (p_index > old_count) p_index = old_count; + p_array.set_size(old_count + 1); + for(t_size n=old_count;n>p_index;n--) + swap_t(p_array[n],p_array[n-1]); + swap_t(p_array[p_index],p_item); + return p_index; + } + + + template + inline T max_t(const T & item1, const T & item2) {return item1 > item2 ? item1 : item2;}; + + template + inline T min_t(const T & item1, const T & item2) {return item1 < item2 ? item1 : item2;}; + + template + inline T abs_t(T item) {return item<0 ? -item : item;} + + template + inline T sqr_t(T item) {return item * item;} + + template + inline T clip_t(const T & p_item, const T & p_min, const T & p_max) { + if (p_item < p_min) return p_min; + else if (p_item <= p_max) return p_item; + else return p_max; + } + + + + + + template + inline void delete_t(T* ptr) {delete ptr;} + + template + inline void delete_array_t(T* ptr) {delete[] ptr;} + + template + inline T* clone_t(T* ptr) {return new T(*ptr);} + + + template + inline t_int mul_safe_t(t_int p_val1,t_int p_val2) { + if (p_val1 == 0 || p_val2 == 0) return 0; + t_int temp = (t_int) (p_val1 * p_val2); + if (temp / p_val1 != p_val2) throw t_exception(); + return temp; + } + template + t_int multiply_guarded(t_int v1, t_int v2) { + return mul_safe_t(v1, v2); + } + template t_int add_unsigned_clipped(t_int v1, t_int v2) { + t_int v = v1 + v2; + if (v < v1) return ~0; + return v; + } + template t_int sub_unsigned_clipped(t_int v1, t_int v2) { + t_int v = v1 - v2; + if (v > v1) return 0; + return v; + } + template void acc_unsigned_clipped(t_int & v1, t_int v2) { + v1 = add_unsigned_clipped(v1, v2); + } + + template + void memcpy_t(t_dst* p_dst,const t_src* p_src,t_size p_count) { + for(t_size n=0;n + void copy_array_loop_t(t_dst & p_dst,const t_src & p_src,t_size p_count) { + for(t_size n=0;n + void memcpy_backwards_t(t_dst * p_dst,const t_src * p_src,t_size p_count) { + p_dst += p_count; p_src += p_count; + for(t_size n=0;n + void memset_t(T * p_buffer,const t_val & p_val,t_size p_count) { + for(t_size n=0;n + void memset_t(T &p_buffer,const t_val & p_val) { + const t_size width = pfc::array_size_t(p_buffer); + for(t_size n=0;n + void memset_null_t(T * p_buffer,t_size p_count) { + for(t_size n=0;n + void memset_null_t(T &p_buffer) { + const t_size width = pfc::array_size_t(p_buffer); + for(t_size n=0;n + void memmove_t(T* p_dst,const T* p_src,t_size p_count) { + if (p_dst == p_src) {/*do nothing*/} + else if (p_dst > p_src && p_dst < p_src + p_count) memcpy_backwards_t(p_dst,p_src,p_count); + else memcpy_t(p_dst,p_src,p_count); + } + + template void memxor_t(TVal * out, const TVal * s1, const TVal * s2, t_size count) { + for(t_size walk = 0; walk < count; ++walk) out[walk] = s1[walk] ^ s2[walk]; + } + static void memxor(void * target, const void * source1, const void * source2, t_size size) { + memxor_t( reinterpret_cast(target), reinterpret_cast(source1), reinterpret_cast(source2), size); + } + + template + T* new_ptr_check_t(T* p_ptr) { + if (p_ptr == NULL) throw std::bad_alloc(); + return p_ptr; + } + + template + int sgn_t(const T & p_val) { + if (p_val < 0) return -1; + else if (p_val > 0) return 1; + else return 0; + } + + template const T* empty_string_t(); + + template<> inline const char * empty_string_t() {return "";} + template<> inline const wchar_t * empty_string_t() {return L"";} + + + template + t_type replace_t(t_type & p_var,const t_newval & p_newval) { + t_type oldval = p_var; + p_var = p_newval; + return oldval; + } + template + t_type replace_null_t(t_type & p_var) { + t_type ret = p_var; + p_var = 0; + return ret; + } + + template + inline bool is_ptr_aligned_t(const void * p_ptr) { + static_assert_t< (p_size_pow2 & (p_size_pow2 - 1)) == 0 >(); + return ( ((t_size)p_ptr) & (p_size_pow2-1) ) == 0; + } + + + template + void array_rangecheck_t(const t_array & p_array,t_size p_index) { + if (p_index >= pfc::array_size_t(p_array)) throw pfc::exception_overflow(); + } + + template + void array_rangecheck_t(const t_array & p_array,t_size p_from,t_size p_to) { + if (p_from > p_to) throw pfc::exception_overflow(); + array_rangecheck_t(p_array,p_from); array_rangecheck_t(p_array,p_to); + } + + t_int32 rint32(double p_val); + t_int64 rint64(double p_val); + + + + + template + inline t_size remove_mask_t(t_array & p_array,const bit_array & p_mask)//returns amount of items left + { + t_size n,count = p_array.get_size(), total = 0; + + n = total = p_mask.find(true,0,count); + + if (n + t_size find_duplicates_sorted_t(t_array p_array,t_size p_count,t_compare p_compare,bit_array_var & p_out) { + t_size ret = 0; + t_size n; + if (p_count > 0) + { + p_out.set(0,false); + for(n=1;n + t_size find_duplicates_sorted_permutation_t(t_array p_array,t_size p_count,t_compare p_compare,t_permutation const & p_permutation,bit_array_var & p_out) { + t_size ret = 0; + t_size n; + if (p_count > 0) { + p_out.set(p_permutation[0],false); + for(n=1;n + t_size strlen_t(const t_char * p_string,t_size p_length = ~0) { + for(t_size walk = 0;;walk++) { + if (walk >= p_length || p_string[walk] == 0) return walk; + } + } + + + template + class __list_to_array_enumerator { + public: + __list_to_array_enumerator(t_array & p_array) : m_walk(), m_array(p_array) {} + template + void operator() (const t_item & p_item) { + PFC_ASSERT(m_walk < m_array.get_size()); + m_array[m_walk++] = p_item; + } + void finalize() { + PFC_ASSERT(m_walk == m_array.get_size()); + } + private: + t_size m_walk; + t_array & m_array; + }; + + template + void list_to_array(t_array & p_array,const t_list & p_list) { + p_array.set_size(p_list.get_count()); + __list_to_array_enumerator enumerator(p_array); + p_list.enumerate(enumerator); + enumerator.finalize(); + } + + template + class enumerator_add_item { + public: + enumerator_add_item(t_receiver & p_receiver) : m_receiver(p_receiver) {} + template void operator() (const t_item & p_item) {m_receiver.add_item(p_item);} + private: + t_receiver & m_receiver; + }; + + template + void overwrite_list_enumerated(t_receiver & p_receiver,const t_giver & p_giver) { + enumerator_add_item wrapper(p_receiver); + p_giver.enumerate(wrapper); + } + + template + void copy_list_enumerated(t_receiver & p_receiver,const t_giver & p_giver) { + p_receiver.remove_all(); + overwrite_list_enumerated(p_receiver,p_giver); + } + + inline bool lxor(bool p_val1,bool p_val2) { + return p_val1 == !p_val2; + } + + template + inline void min_acc(t_val & p_acc,const t_val & p_val) { + if (p_val < p_acc) p_acc = p_val; + } + + template + inline void max_acc(t_val & p_acc,const t_val & p_val) { + if (p_val > p_acc) p_acc = p_val; + } + + t_uint64 pow_int(t_uint64 base, t_uint64 exp); + + + template + class incrementScope { + public: + incrementScope(t_val & i) : v(i) {++v;} + ~incrementScope() {--v;} + private: + t_val & v; + }; + + inline unsigned countBits32(uint32_t i) { + const uint32_t mask = 0x11111111; + uint32_t acc = i & mask; + acc += (i >> 1) & mask; + acc += (i >> 2) & mask; + acc += (i >> 3) & mask; + + const uint32_t mask2 = 0x0F0F0F0F; + uint32_t acc2 = acc & mask2; + acc2 += (acc >> 4) & mask2; + + const uint32_t mask3 = 0x00FF00FF; + uint32_t acc3 = acc2 & mask3; + acc3 += (acc2 >> 8) & mask3; + + return (acc3 & 0xFFFF) + ((acc3 >> 16) & 0xFFFF); + } + + // Forward declarations + template + void copy_array_t(t_to & p_to,const t_from & p_from); + + template + void fill_array_t(t_array & p_array,const t_value & p_value); +}; + + +#define PFC_CLASS_NOT_COPYABLE(THISCLASSNAME,THISTYPE) \ + private: \ + THISCLASSNAME(const THISTYPE&); \ + const THISTYPE & operator=(const THISTYPE &); + +#define PFC_CLASS_NOT_COPYABLE_EX(THISTYPE) PFC_CLASS_NOT_COPYABLE(THISTYPE,THISTYPE) \ No newline at end of file diff --git a/SDK/pfc/primitives_part2.h b/SDK/pfc/primitives_part2.h new file mode 100644 index 0000000..c846a3b --- /dev/null +++ b/SDK/pfc/primitives_part2.h @@ -0,0 +1,24 @@ +namespace pfc { + template + static bool guess_reorder_pattern(pfc::array_t & out, const t_list1 & from, const t_list2 & to) { + typedef typename t_list1::t_item t_item; + const t_size count = from.get_size(); + if (count != to.get_size()) return false; + out.set_size(count); + for(t_size walk = 0; walk < count; ++walk) out[walk] = walk; + //required output: to[n] = from[out[n]]; + typedef pfc::chain_list_v2_t t_queue; + pfc::map_t content; + for(t_size walk = 0; walk < count; ++walk) { + content.find_or_add(from[walk]).add_item(walk); + } + for(t_size walk = 0; walk < count; ++walk) { + t_queue * q = content.query_ptr(to[walk]); + if (q == NULL) return false; + if (q->get_count() == 0) return false; + out[walk] = *q->first(); + q->remove(q->first()); + } + return true; + } +} diff --git a/SDK/pfc/printf.cpp b/SDK/pfc/printf.cpp new file mode 100644 index 0000000..e236c40 --- /dev/null +++ b/SDK/pfc/printf.cpp @@ -0,0 +1,121 @@ +#include "pfc.h" + +//implementations of deprecated string_printf methods, with a pragma to disable warnings when they reference other deprecated methods. + +#ifndef _MSC_VER +#define _itoa_s itoa +#define _ultoa_s ultoa +#endif + +#ifdef _MSC_VER +#pragma warning(disable:4996) +#endif + +namespace pfc { + +void string_printf::run(const char * fmt,va_list list) {g_run(*this,fmt,list);} + +string_printf_va::string_printf_va(const char * fmt,va_list list) {string_printf::g_run(*this,fmt,list);} + +void string_printf::g_run(string_base & out,const char * fmt,va_list list) +{ + out.reset(); + while(*fmt) + { + if (*fmt=='%') + { + fmt++; + if (*fmt=='%') + { + out.add_char('%'); + fmt++; + } + else + { + bool force_sign = false; + if (*fmt=='+') + { + force_sign = true; + fmt++; + } + char padchar = (*fmt == '0') ? '0' : ' '; + t_size pad = 0; + while(*fmt>='0' && *fmt<='9') + { + pad = pad * 10 + (*fmt - '0'); + fmt++; + } + + if (*fmt=='s' || *fmt=='S') + { + const char * ptr = va_arg(list,const char*); + t_size len = strlen(ptr); + if (pad>len) out.add_chars(padchar,pad-len); + out.add_string(ptr); + fmt++; + + } + else if (*fmt=='i' || *fmt=='I' || *fmt=='d' || *fmt=='D') + { + int val = va_arg(list,int); + if (force_sign && val>0) out.add_char('+'); + pfc::format_int temp( val ); + t_size len = strlen(temp); + if (pad>len) out.add_chars(padchar,pad-len); + out.add_string(temp); + fmt++; + } + else if (*fmt=='u' || *fmt=='U') + { + int val = va_arg(list,int); + if (force_sign && val>0) out.add_char('+'); + pfc::format_uint temp(val); + t_size len = strlen(temp); + if (pad>len) out.add_chars(padchar,pad-len); + out.add_string(temp); + fmt++; + } + else if (*fmt=='x' || *fmt=='X') + { + int val = va_arg(list,int); + if (force_sign && val>0) out.add_char('+'); + pfc::format_uint temp(val, 0, 16); + if (*fmt=='X') + { + char * t = const_cast< char* > ( temp.get_ptr() ); + while(*t) + { + if (*t>='a' && *t<='z') + *t += 'A' - 'a'; + t++; + } + } + t_size len = strlen(temp); + if (pad>len) out.add_chars(padchar,pad-len); + out.add_string(temp); + fmt++; + } + else if (*fmt=='c' || *fmt=='C') + { + out.add_char(va_arg(list,int)); + fmt++; + } + } + } + else + { + out.add_char(*(fmt++)); + } + } +} + +string_printf::string_printf(const char * fmt,...) +{ + va_list list; + va_start(list,fmt); + run(fmt,list); + va_end(list); +} + + +} diff --git a/SDK/pfc/ptr_list.h b/SDK/pfc/ptr_list.h new file mode 100644 index 0000000..6d1ac4b --- /dev/null +++ b/SDK/pfc/ptr_list.h @@ -0,0 +1,47 @@ +#ifndef __PFC_PTR_LIST_H_ +#define __PFC_PTR_LIST_H_ + +namespace pfc { + + template > + class ptr_list_t : public B + { + public: + ptr_list_t() {} + ptr_list_t(const ptr_list_t & p_source) {*this = p_source;} + + void free_by_idx(t_size n) {free_mask(bit_array_one(n));} + void free_all() {this->remove_all_ex(free);} + void free_mask(const bit_array & p_mask) {this->remove_mask_ex(p_mask,free);} + + void delete_item(T* ptr) {delete_by_idx(find_item(ptr));} + + void delete_by_idx(t_size p_index) { + delete_mask(bit_array_one(p_index)); + } + + void delete_all() { + this->remove_all_ex(pfc::delete_t); + } + + void delete_mask(const bit_array & p_mask) { + this->remove_mask_ex(p_mask,pfc::delete_t); + } + + T * operator[](t_size n) const {return this->get_item(n);} + }; + + template + class ptr_list_hybrid_t : public ptr_list_t > { + public: + ptr_list_hybrid_t() {} + ptr_list_hybrid_t(const ptr_list_hybrid_t & p_source) {*this = p_source;} + }; + + typedef ptr_list_t ptr_list; + + template class traits_t > : public traits_t {}; +} + + +#endif //__PFC_PTR_LIST_H_ diff --git a/SDK/pfc/rcptr.h b/SDK/pfc/rcptr.h new file mode 100644 index 0000000..382809a --- /dev/null +++ b/SDK/pfc/rcptr.h @@ -0,0 +1,269 @@ +namespace pfc { + + struct _rcptr_null; + typedef _rcptr_null* t_rcptr_null; + + static const t_rcptr_null rcptr_null = NULL; + + class rc_container_base { + public: + long add_ref() throw() { + return ++m_counter; + } + long release() throw() { + long ret = --m_counter; + if (ret == 0) PFC_ASSERT_NO_EXCEPTION( delete this ); + return ret; + } + protected: + virtual ~rc_container_base() {} + private: + refcounter m_counter; + }; + + template + class rc_container_t : public rc_container_base { + public: + TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(rc_container_t,m_object) + + t_object m_object; + }; + + template + class rcptr_t { + private: + typedef rcptr_t t_self; + typedef rc_container_base t_container; + typedef rc_container_t t_container_impl; + public: + rcptr_t(t_rcptr_null) throw() {_clear();} + rcptr_t() throw() {_clear();} + rcptr_t(const t_self & p_source) throw() {__init(p_source);} + t_self const & operator=(const t_self & p_source) throw() {__copy(p_source); return *this;} + + template + rcptr_t(const rcptr_t & p_source) throw() {__init(p_source);} + template + const t_self & operator=(const rcptr_t & p_source) throw() {__copy(p_source); return *this;} + + rcptr_t(t_self && p_source) throw() {_move(p_source);} + const t_self & operator=(t_self && p_source) throw() {release(); _move(p_source); return *this;} + + const t_self & operator=(t_rcptr_null) throw() {release(); return *this;} + +/* template + operator rcptr_t() const throw() { + rcptr_t temp; + if (is_valid()) temp.__set_from_cast(this->m_container,this->m_ptr); + return temp; + }*/ + + + template + bool operator==(const rcptr_t & p_other) const throw() { + return m_container == p_other.__container(); + } + + template + bool operator!=(const rcptr_t & p_other) const throw() { + return m_container != p_other.__container(); + } + + void __set_from_cast(t_container * p_container,t_object * p_ptr) throw() { + //addref first because in rare cases this is the same pointer as the one we currently own + if (p_container != NULL) p_container->add_ref(); + release(); + m_container = p_container; + m_ptr = p_ptr; + } + + bool is_valid() const throw() {return m_container != NULL;} + bool is_empty() const throw() {return m_container == NULL;} + + + ~rcptr_t() throw() {release();} + + void release() throw() { + t_container * temp = m_container; + m_ptr = NULL; + m_container = NULL; + if (temp != NULL) temp->release(); + } + + + template + rcptr_t static_cast_t() const throw() { + rcptr_t temp; + if (is_valid()) temp.__set_from_cast(this->m_container,static_cast(this->m_ptr)); + return temp; + } + + void new_t() { + on_new(new t_container_impl()); + } + + template + void new_t(t_param1 const & p_param1) { + on_new(new t_container_impl(p_param1)); + } + + template + void new_t(t_param1 const & p_param1, t_param2 const & p_param2) { + on_new(new t_container_impl(p_param1,p_param2)); + } + + template + void new_t(t_param1 const & p_param1, t_param2 const & p_param2,t_param3 const & p_param3) { + on_new(new t_container_impl(p_param1,p_param2,p_param3)); + } + + template + void new_t(t_param1 const & p_param1, t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4) { + on_new(new t_container_impl(p_param1,p_param2,p_param3,p_param4)); + } + + template + void new_t(t_param1 const & p_param1, t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4,t_param5 const & p_param5) { + on_new(new t_container_impl(p_param1,p_param2,p_param3,p_param4,p_param5)); + } + + template + void new_t(t_param1 const & p_param1, t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4,t_param5 const & p_param5,t_param6 const & p_param6) { + on_new(new t_container_impl(p_param1,p_param2,p_param3,p_param4,p_param5,p_param6)); + } + + static t_self g_new_t() { + t_self temp; + temp.new_t(); + return temp; + } + + template + static t_self g_new_t(t_param1 const & p_param1) { + t_self temp; + temp.new_t(p_param1); + return temp; + } + + template + static t_self g_new_t(t_param1 const & p_param1,t_param2 const & p_param2) { + t_self temp; + temp.new_t(p_param1,p_param2); + return temp; + } + + template + static t_self g_new_t(t_param1 const & p_param1,t_param2 const & p_param2,t_param3 const & p_param3) { + t_self temp; + temp.new_t(p_param1,p_param2,p_param3); + return temp; + } + + template + static t_self g_new_t(t_param1 const & p_param1,t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4) { + t_self temp; + temp.new_t(p_param1,p_param2,p_param3,p_param4); + return temp; + } + + template + static t_self g_new_t(t_param1 const & p_param1,t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4,t_param5 const & p_param5) { + t_self temp; + temp.new_t(p_param1,p_param2,p_param3,p_param4,p_param5); + return temp; + } + + t_object & operator*() const throw() {return *this->m_ptr;} + + t_object * operator->() const throw() {return this->m_ptr;} + + + t_container * __container() const throw() {return m_container;} + + // FOR INTERNAL USE ONLY + void _clear() throw() {m_container = NULL; m_ptr = NULL;} + private: + + template + void __init(const rcptr_t & p_source) throw() { + m_container = p_source.__container(); + m_ptr = &*p_source; + if (m_container != NULL) m_container->add_ref(); + } + template + void _move(rcptr_t & p_source) throw() { + m_container = p_source.__container(); + m_ptr = &*p_source; + p_source._clear(); + } + template + void __copy(const rcptr_t & p_source) throw() { + __set_from_cast(p_source.__container(),&*p_source); + } + void on_new(t_container_impl * p_container) throw() { + this->release(); + p_container->add_ref(); + this->m_ptr = &p_container->m_object; + this->m_container = p_container; + } + + t_container * m_container; + t_object * m_ptr; + }; + + template + rcptr_t rcnew_t() { + rcptr_t temp; + temp.new_t(); + return temp; + } + + template + rcptr_t rcnew_t(t_param1 const & p_param1) { + rcptr_t temp; + temp.new_t(p_param1); + return temp; + } + + template + rcptr_t rcnew_t(t_param1 const & p_param1,t_param2 const & p_param2) { + rcptr_t temp; + temp.new_t(p_param1,p_param2); + return temp; + } + + template + rcptr_t rcnew_t(t_param1 const & p_param1,t_param2 const & p_param2,t_param3 const & p_param3) { + rcptr_t temp; + temp.new_t(p_param1,p_param2,p_param3); + return temp; + } + + template + rcptr_t rcnew_t(t_param1 const & p_param1,t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4) { + rcptr_t temp; + temp.new_t(p_param1,p_param2,p_param3,p_param4); + return temp; + } + + template + rcptr_t rcnew_t(t_param1 const & p_param1,t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4,t_param5 const & p_param5) { + rcptr_t temp; + temp.new_t(p_param1,p_param2,p_param3,p_param4,p_param5); + return temp; + } + + template + rcptr_t rcnew_t(t_param1 const & p_param1,t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4,t_param5 const & p_param5,t_param6 const & p_param6) { + rcptr_t temp; + temp.new_t(p_param1,p_param2,p_param3,p_param4,p_param5,p_param6); + return temp; + } + + class traits_rcptr : public traits_default { + public: + enum { realloc_safe = true, constructor_may_fail = false }; + }; + + template class traits_t > : public traits_rcptr {}; +} \ No newline at end of file diff --git a/SDK/pfc/ref_counter.h b/SDK/pfc/ref_counter.h new file mode 100644 index 0000000..b8069c2 --- /dev/null +++ b/SDK/pfc/ref_counter.h @@ -0,0 +1,136 @@ +#ifdef _MSC_VER +#include +#endif + +namespace pfc { + class counter { + public: + typedef long t_val; + + counter(t_val p_val = 0) : m_val(p_val) {} + long operator++() throw() {return inc();} + long operator--() throw() {return dec();} + long operator++(int) throw() {return inc()-1;} + long operator--(int) throw() {return dec()+1;} + operator t_val() const throw() {return m_val;} + private: + t_val inc() { +#ifdef _MSC_VER + return _InterlockedIncrement(&m_val); +#else + return __sync_add_and_fetch(&m_val, 1); +#endif + } + t_val dec() { +#ifdef _MSC_VER + return _InterlockedDecrement(&m_val); +#else + return __sync_sub_and_fetch(&m_val, 1); +#endif + } + + volatile t_val m_val; + }; + + typedef counter refcounter; + + class NOVTABLE refcounted_object_root + { + public: + void refcount_add_ref() throw() {++m_counter;} + void refcount_release() throw() {if (--m_counter == 0) delete this;} + void _refcount_release_temporary() throw() {--m_counter;}//for internal use only! + protected: + refcounted_object_root() {} + virtual ~refcounted_object_root() {} + private: + refcounter m_counter; + }; + + template + class refcounted_object_ptr_t { + private: + typedef refcounted_object_ptr_t t_self; + public: + inline refcounted_object_ptr_t() throw() : m_ptr(NULL) {} + inline refcounted_object_ptr_t(T* p_ptr) throw() : m_ptr(NULL) {copy(p_ptr);} + inline refcounted_object_ptr_t(const t_self & p_source) throw() : m_ptr(NULL) {copy(p_source);} + inline refcounted_object_ptr_t(t_self && p_source) throw() { m_ptr = p_source.m_ptr; p_source.m_ptr = NULL; } + + template + inline refcounted_object_ptr_t(t_source * p_ptr) throw() : m_ptr(NULL) {copy(p_ptr);} + + template + inline refcounted_object_ptr_t(const refcounted_object_ptr_t & p_source) throw() : m_ptr(NULL) {copy(p_source);} + + inline ~refcounted_object_ptr_t() throw() {if (m_ptr != NULL) m_ptr->refcount_release();} + + template + inline void copy(t_source * p_ptr) throw() { + T* torel = pfc::replace_t(m_ptr,pfc::safe_ptr_cast(p_ptr)); + if (m_ptr != NULL) m_ptr->refcount_add_ref(); + if (torel != NULL) torel->refcount_release(); + + } + + template + inline void copy(const refcounted_object_ptr_t & p_source) throw() {copy(p_source.get_ptr());} + + + inline const t_self & operator=(const t_self & p_source) throw() {copy(p_source); return *this;} + inline const t_self & operator=(t_self && p_source) throw() {attach(p_source.detach()); return *this;} + inline const t_self & operator=(T * p_ptr) throw() {copy(p_ptr); return *this;} + + template inline t_self & operator=(const refcounted_object_ptr_t & p_source) throw() {copy(p_source); return *this;} + template inline t_self & operator=(t_source * p_ptr) throw() {copy(p_ptr); return *this;} + + inline void release() throw() { + T * temp = pfc::replace_t(m_ptr,(T*)NULL); + if (temp != NULL) temp->refcount_release(); + } + + + inline T& operator*() const throw() {return *m_ptr;} + + inline T* operator->() const throw() {PFC_ASSERT(m_ptr != NULL);return m_ptr;} + + inline T* get_ptr() const throw() {return m_ptr;} + + inline bool is_valid() const throw() {return m_ptr != NULL;} + inline bool is_empty() const throw() {return m_ptr == NULL;} + + inline bool operator==(const t_self & p_item) const throw() {return m_ptr == p_item.get_ptr();} + inline bool operator!=(const t_self & p_item) const throw() {return m_ptr != p_item.get_ptr();} + inline bool operator>(const t_self & p_item) const throw() {return m_ptr > p_item.get_ptr();} + inline bool operator<(const t_self & p_item) const throw() {return m_ptr < p_item.get_ptr();} + + + inline T* _duplicate_ptr() const throw()//should not be used ! temporary ! + { + if (m_ptr) m_ptr->refcount_add_ref(); + return m_ptr; + } + + inline T* detach() throw() {//should not be used ! temporary ! + T* ret = m_ptr; + m_ptr = 0; + return ret; + } + + inline void attach(T * p_ptr) throw() {//should not be used ! temporary ! + release(); + m_ptr = p_ptr; + } + inline t_self & operator<<(t_self & p_source) throw() {attach(p_source.detach());return *this;} + inline t_self & operator>>(t_self & p_dest) throw() {p_dest.attach(detach());return *this;} + private: + T* m_ptr; + }; + + template + class traits_t > : public traits_default { + public: + enum { realloc_safe = true, constructor_may_fail = false}; + }; + +}; \ No newline at end of file diff --git a/SDK/pfc/selftest.cpp b/SDK/pfc/selftest.cpp new file mode 100644 index 0000000..7d7c9f5 --- /dev/null +++ b/SDK/pfc/selftest.cpp @@ -0,0 +1,84 @@ +#include "pfc.h" + + +namespace { + class foo {}; +} + +inline pfc::string_base & operator<<(pfc::string_base & p_fmt,foo p_source) {p_fmt.add_string_("FOO"); return p_fmt;} + +namespace { + using namespace pfc; + class thread_selftest : public thread { + public: + void threadProc() { + pfc::event ev; + ev.wait_for(1); + m_event.set_state(true); + ev.wait_for(1); + } + pfc::event m_event; + + void selftest() { + lores_timer timer; timer.start(); + this->start(); + if (!m_event.wait_for(-1)) { + PFC_ASSERT(!"Should not get here"); + return; + } + PFC_ASSERT(fabs(timer.query() - 1.0) < 0.1); + this->waitTillDone(); + PFC_ASSERT(fabs(timer.query() - 2.0) < 0.1); + } + }; +} + +namespace pfc { + + + + // Self test routines that need to be executed to do their payload + void selftest_runtime() { + { + thread_selftest t; t.selftest(); + } + + } + // Self test routines that fail at compile time if there's something seriously wrong + void selftest_static() { + PFC_STATIC_ASSERT(sizeof(t_uint8) == 1); + PFC_STATIC_ASSERT(sizeof(t_uint16) == 2); + PFC_STATIC_ASSERT(sizeof(t_uint32) == 4); + PFC_STATIC_ASSERT(sizeof(t_uint64) == 8); + + PFC_STATIC_ASSERT(sizeof(t_int8) == 1); + PFC_STATIC_ASSERT(sizeof(t_int16) == 2); + PFC_STATIC_ASSERT(sizeof(t_int32) == 4); + PFC_STATIC_ASSERT(sizeof(t_int64) == 8); + + PFC_STATIC_ASSERT(sizeof(t_float32) == 4); + PFC_STATIC_ASSERT(sizeof(t_float64) == 8); + + PFC_STATIC_ASSERT(sizeof(t_size) == sizeof(void*)); + PFC_STATIC_ASSERT(sizeof(t_ssize) == sizeof(void*)); + + PFC_STATIC_ASSERT(sizeof(wchar_t) == 2 || sizeof(wchar_t) == 4); + + PFC_STATIC_ASSERT(sizeof(GUID) == 16); + + typedef pfc::avltree_t t_asdf; + t_asdf asdf; asdf.add_item(1); + t_asdf::iterator iter = asdf._first_var(); + t_asdf::const_iterator iter2 = asdf._first_var(); + + PFC_string_formatter() << "foo" << 1337 << foo(); + + pfc::list_t l; l.add_item(3); + } + + void selftest() { + selftest_static(); selftest_runtime(); + + debugLog out; out << "PFC selftest OK"; + } +} diff --git a/SDK/pfc/sort.cpp b/SDK/pfc/sort.cpp new file mode 100644 index 0000000..912bc92 --- /dev/null +++ b/SDK/pfc/sort.cpp @@ -0,0 +1,268 @@ +#include "pfc.h" + +#if defined(_M_IX86) || defined(_M_IX64) +#include +#define PFC_HAVE_RDTSC +#endif + +namespace pfc { + +void swap_void(void * item1,void * item2,t_size width) +{ + unsigned char * ptr1 = (unsigned char*)item1, * ptr2 = (unsigned char*)item2; + t_size n; + unsigned char temp; + for(n=0;n done; + done.set_size(done_size); + pfc::memset_t(done,(unsigned char)0); + t_size n; + for(n=0;nn); + PFC_ASSERT(n done; + done.set_size(done_size); + pfc::memset_t(done,(unsigned char)0); + t_size n; + for(n=0;nn); + PFC_ASSERT(n 0) pfc::swap_t(p_elem1,p_elem2); +} + + +#ifdef PFC_HAVE_RDTSC +static inline t_uint64 uniqueVal() {return __rdtsc();} +#else +static counter uniqueValCounter; +static counter::t_val uniqueVal() { + return ++uniqueValCounter; +} +#endif + +static t_size myrand(t_size count) { + const uint64_t rm = (uint64_t)RAND_MAX + 1; + uint64_t m = 1; + uint64_t v = 0; + for(;;) { + v += rand() * m; + m *= rm; + if (m >= count) break; + } + v ^= uniqueVal(); + return (t_size)(v % count); +} + +inline static t_size __pivot_helper(pfc::sort_callback & p_callback,t_size const p_base,t_size const p_count) { + PFC_ASSERT(p_count > 2); + + //t_size val1 = p_base, val2 = p_base + (p_count / 2), val3 = p_base + (p_count - 1); + + t_size val1 = myrand(p_count), val2 = myrand(p_count-1), val3 = myrand(p_count-2); + if (val2 >= val1) val2++; + if (val3 >= val1) val3++; + if (val3 >= val2) val3++; + + val1 += p_base; val2 += p_base; val3 += p_base; + + __sort_2elem_helper(p_callback,val1,val2); + __sort_2elem_helper(p_callback,val1,val3); + __sort_2elem_helper(p_callback,val2,val3); + + return val2; +} + +static void newsort(pfc::sort_callback & p_callback,t_size const p_base,t_size const p_count) { + if (p_count <= 4) { + squaresort(p_callback,p_base,p_count); + return; + } + + t_size pivot = __pivot_helper(p_callback,p_base,p_count); + + { + const t_size target = p_base + p_count - 1; + if (pivot != target) { + p_callback.swap(pivot,target); pivot = target; + } + } + + + t_size partition = p_base; + { + bool asdf = false; + for(t_size walk = p_base; walk < pivot; ++walk) { + const int comp = p_callback.compare(walk,pivot); + bool trigger = false; + if (comp == 0) { + trigger = asdf; + asdf = !asdf; + } else if (comp < 0) { + trigger = true; + } + if (trigger) { + if (partition != walk) p_callback.swap(partition,walk); + partition++; + } + } + } + if (pivot != partition) { + p_callback.swap(pivot,partition); pivot = partition; + } + + newsort(p_callback,p_base,pivot-p_base); + newsort(p_callback,pivot+1,p_count-(pivot+1-p_base)); +} + +void sort(pfc::sort_callback & p_callback,t_size p_num) { + srand((unsigned int)(uniqueVal() ^ p_num)); + newsort(p_callback,0,p_num); +} + + +void sort_void(void * base,t_size num,t_size width,int (*comp)(const void *, const void *) ) +{ + sort_void_ex(base,num,width,comp,swap_void); +} + + + + +sort_callback_stabilizer::sort_callback_stabilizer(sort_callback & p_chain,t_size p_count) +: m_chain(p_chain) +{ + m_order.set_size(p_count); + t_size n; + for(n=0;n + class reorder_callback_impl_t : public reorder_callback + { + public: + reorder_callback_impl_t(t_container & p_data) : m_data(p_data) {} + void swap(t_size p_index1,t_size p_index2) + { + pfc::swap_t(m_data[p_index1],m_data[p_index2]); + } + private: + t_container & m_data; + }; + + class reorder_callback_impl_delta : public reorder_callback + { + public: + reorder_callback_impl_delta(reorder_callback & p_data,t_size p_delta) : m_data(p_data), m_delta(p_delta) {} + void swap(t_size p_index1,t_size p_index2) + { + m_data.swap(p_index1+m_delta,p_index2+m_delta); + } + private: + reorder_callback & m_data; + t_size m_delta; + }; + + template + void reorder_t(t_container & p_data,const t_size * p_order,t_size p_count) + { + reorder_callback_impl_t cb(p_data); + reorder(cb,p_order,p_count); + } + + template + void reorder_partial_t(t_container & p_data,t_size p_base,const t_size * p_order,t_size p_count) + { + reorder_callback_impl_t cb1(p_data); + reorder_callback_impl_delta cb2( cb1, p_base ); + reorder(cb2,p_order,p_count); +// reorder(reorder_callback_impl_delta(reorder_callback_impl_t(p_data),p_base),p_order,p_count); + } + + template + class reorder_callback_impl_ptr_t : public reorder_callback + { + public: + reorder_callback_impl_ptr_t(T * p_data) : m_data(p_data) {} + void swap(t_size p_index1,t_size p_index2) + { + pfc::swap_t(m_data[p_index1],m_data[p_index2]); + } + private: + T* m_data; + }; + + + template + void reorder_ptr_t(T* p_data,const t_size * p_order,t_size p_count) + { + reorder(reorder_callback_impl_ptr_t(p_data),p_order,p_count); + } + + + + class NOVTABLE sort_callback + { + public: + virtual int compare(t_size p_index1, t_size p_index2) const = 0; + virtual void swap(t_size p_index1, t_size p_index2) = 0; + void swap_check(t_size p_index1, t_size p_index2) {if (compare(p_index1,p_index2) > 0) swap(p_index1,p_index2);} + }; + + class sort_callback_stabilizer : public sort_callback + { + public: + sort_callback_stabilizer(sort_callback & p_chain,t_size p_count); + virtual int compare(t_size p_index1, t_size p_index2) const; + virtual void swap(t_size p_index1, t_size p_index2); + private: + sort_callback & m_chain; + array_t m_order; + }; + + void sort(sort_callback & p_callback,t_size p_count); + void sort_stable(sort_callback & p_callback,t_size p_count); + + void sort_void_ex(void *base,t_size num,t_size width, int (*comp)(const void *, const void *),void (*swap)(void *, void *, t_size) ); + void sort_void(void * base,t_size num,t_size width,int (*comp)(const void *, const void *) ); + + template + class sort_callback_impl_simple_wrap_t : public sort_callback + { + public: + sort_callback_impl_simple_wrap_t(t_container & p_data, t_compare p_compare) : m_data(p_data), m_compare(p_compare) {} + int compare(t_size p_index1, t_size p_index2) const + { + return m_compare(m_data[p_index1],m_data[p_index2]); + } + + void swap(t_size p_index1, t_size p_index2) + { + swap_t(m_data[p_index1],m_data[p_index2]); + } + private: + t_container & m_data; + t_compare m_compare; + }; + + template + class sort_callback_impl_auto_wrap_t : public sort_callback + { + public: + sort_callback_impl_auto_wrap_t(t_container & p_data) : m_data(p_data) {} + int compare(t_size p_index1, t_size p_index2) const + { + return compare_t(m_data[p_index1],m_data[p_index2]); + } + + void swap(t_size p_index1, t_size p_index2) + { + swap_t(m_data[p_index1],m_data[p_index2]); + } + private: + t_container & m_data; + }; + + template + class sort_callback_impl_permutation_wrap_t : public sort_callback + { + public: + sort_callback_impl_permutation_wrap_t(const t_container & p_data, t_compare p_compare,t_permutation const & p_permutation) : m_data(p_data), m_compare(p_compare), m_permutation(p_permutation) {} + int compare(t_size p_index1, t_size p_index2) const + { + return m_compare(m_data[m_permutation[p_index1]],m_data[m_permutation[p_index2]]); + } + + void swap(t_size p_index1, t_size p_index2) + { + swap_t(m_permutation[p_index1],m_permutation[p_index2]); + } + private: + const t_container & m_data; + t_compare m_compare; + t_permutation const & m_permutation; + }; + + template + static void sort_t(t_container & p_data,t_compare p_compare,t_size p_count) + { + sort_callback_impl_simple_wrap_t cb(p_data,p_compare); + sort(cb,p_count); + } + + template + static void sort_stable_t(t_container & p_data,t_compare p_compare,t_size p_count) + { + sort_callback_impl_simple_wrap_t cb(p_data,p_compare); + sort_stable(cb,p_count); + } + + template + static void sort_get_permutation_t(const t_container & p_data,t_compare p_compare,t_size p_count,t_permutation const & p_permutation) + { + sort_callback_impl_permutation_wrap_t cb(p_data,p_compare,p_permutation); + sort(cb,p_count); + } + + template + static void sort_stable_get_permutation_t(const t_container & p_data,t_compare p_compare,t_size p_count,t_permutation const & p_permutation) + { + sort_callback_impl_permutation_wrap_t cb(p_data,p_compare,p_permutation); + sort_stable(cb,p_count); + } + +} diff --git a/SDK/pfc/stdafx.cpp b/SDK/pfc/stdafx.cpp new file mode 100644 index 0000000..f2d9441 --- /dev/null +++ b/SDK/pfc/stdafx.cpp @@ -0,0 +1,2 @@ +//cpp used to generate precompiled header +#include "pfc.h" \ No newline at end of file diff --git a/SDK/pfc/string8_impl.h b/SDK/pfc/string8_impl.h new file mode 100644 index 0000000..9c8578e --- /dev/null +++ b/SDK/pfc/string8_impl.h @@ -0,0 +1,117 @@ +namespace pfc { + +template class t_alloc> +void string8_t::add_string(const char * ptr,t_size len) +{ + if (m_data.is_owned(ptr)) { + add_string(string8(ptr,len)); + } else { + len = strlen_max(ptr,len); + add_string_nc(ptr, len); + } +} + +template class t_alloc> +void string8_t::set_string(const char * ptr,t_size len) { + if (m_data.is_owned(ptr)) { + set_string_(string8(ptr,len)); + } else { + len = strlen_max(ptr,len); + set_string_nc(ptr, len); + } +} + +template class t_alloc> +void string8_t::set_char(unsigned offset,char c) +{ + if (!c) truncate(offset); + else if (offset class t_alloc> +void string8_t::fix_filename_chars(char def,char leave)//replace "bad" characters, leave parameter can be used to keep eg. path separators +{ + t_size n; + for(n=0;n class t_alloc> +void string8_t::remove_chars(t_size first,t_size count) +{ + if (first>used) first = used; + if (first+count>used) count = used-first; + if (count>0) + { + t_size n; + for(n=first+count;n<=used;n++) + m_data[n-count]=m_data[n]; + used -= count; + makespace(used+1); + } +} + +template class t_alloc> +void string8_t::insert_chars(t_size first,const char * src, t_size count) +{ + if (first > used) first = used; + + makespace(used+count+1); + t_size n; + for(n=used;(int)n>=(int)first;n--) + m_data[n+count] = m_data[n]; + for(n=0;n class t_alloc> +void string8_t::insert_chars(t_size first,const char * src) {insert_chars(first,src,strlen(src));} + + +template class t_alloc> +t_size string8_t::replace_nontext_chars(char p_replace) +{ + t_size ret = 0; + for(t_size n=0;n class t_alloc> +t_size string8_t::replace_byte(char c1,char c2,t_size start) +{ + PFC_ASSERT(c1 != 0); PFC_ASSERT(c2 != 0); + t_size n, ret = 0; + for(n=start;n class t_alloc> +t_size string8_t::replace_char(unsigned c1,unsigned c2,t_size start) +{ + if (c1 < 128 && c2 < 128) return replace_byte((char)c1,(char)c2,start); + + string8 temp(get_ptr()+start); + truncate(start); + const char * ptr = temp; + t_size rv = 0; + while(*ptr) + { + unsigned test; + t_size delta = utf8_decode_char(ptr,test); + if (delta==0 || test==0) break; + if (test == c1) {test = c2;rv++;} + add_char(test); + ptr += delta; + } + return rv; +} + +} diff --git a/SDK/pfc/stringNew.cpp b/SDK/pfc/stringNew.cpp new file mode 100644 index 0000000..d84141a --- /dev/null +++ b/SDK/pfc/stringNew.cpp @@ -0,0 +1,82 @@ +#include "pfc.h" + +namespace pfc { + +t_size string::indexOf(char c,t_size base) const { + return pfc::string_find_first(ptr(),c,base); +} +t_size string::lastIndexOf(char c,t_size base) const { + return pfc::string_find_last(ptr(),c,base); +} +t_size string::indexOf(stringp s,t_size base) const { + return pfc::string_find_first(ptr(),s.ptr(),base); +} +t_size string::lastIndexOf(stringp s,t_size base) const { + return pfc::string_find_last(ptr(),s.ptr(),base); +} +t_size string::indexOfAnyChar(stringp _s,t_size base) const { + string s ( _s ); + const t_size len = length(); + const char* content = ptr(); + for(t_size walk = 0; walk < len; ++walk) { + if (s.contains(content[walk])) return walk; + } + return ~0; +} +t_size string::lastIndexOfAnyChar(stringp _s,t_size base) const { + string s ( _s ); + const char* content = ptr(); + for(t_size _walk = length(); _walk > 0; --_walk) { + const t_size walk = _walk-1; + if (s.contains(content[walk])) return walk; + } + return ~0; +} +bool string::startsWith(char c) const { + return (*this)[0] == c; +} +bool string::startsWith(string s) const { + const char * walk = ptr(); + const char * subWalk = s.ptr(); + for(;;) { + if (*subWalk == 0) return true; + if (*walk != *subWalk) return false; + walk++; subWalk++; + } +} +bool string::endsWith(char c) const { + const t_size len = length(); + if (len == 0) return false; + return ptr()[len-1] == c; +} +bool string::endsWith(string s) const { + const t_size len = length(), subLen = s.length(); + if (subLen > len) return false; + return subString(len - subLen) == s; +} + +char string::firstChar() const { + return (*this)[0]; +} +char string::lastChar() const { + const t_size len = length(); + return len > 0 ? (*this)[len-1] : (char)0; +} + +string string::replace(stringp strOld, stringp strNew) const { + t_size walk = 0; + string ret; + for(;;) { + t_size next = indexOf(strOld, walk); + if (next == ~0) { + ret += subString(walk); break; + } + ret += subString(walk,next-walk) + strNew; + walk = next + strOld.length(); + } + return ret; +} +bool string::contains(char c) const {return indexOf(c) != ~0;} +bool string::contains(stringp s) const {return indexOf(s) != ~0;} +bool string::containsAnyChar(stringp s) const {return indexOfAnyChar(s) != ~0;} +} diff --git a/SDK/pfc/stringNew.h b/SDK/pfc/stringNew.h new file mode 100644 index 0000000..0ee0055 --- /dev/null +++ b/SDK/pfc/stringNew.h @@ -0,0 +1,260 @@ +namespace pfc { + //helper, const methods only + class __stringEmpty : public string_base { + public: + const char * get_ptr() const {return "";} + void add_string(const char * p_string,t_size p_length = ~0) {throw exception_not_implemented();} + void set_string(const char * p_string,t_size p_length = ~0) {throw exception_not_implemented();} + void truncate(t_size len) {throw exception_not_implemented();} + t_size get_length() const {return 0;} + char * lock_buffer(t_size p_requested_length) {throw exception_not_implemented();} + void unlock_buffer() {throw exception_not_implemented();} + }; + + class stringp; + + //! New EXPERIMENTAL string class, allowing efficient copies and returning from functions. \n + //! Does not implement the string_base interface so you still need string8 in many cases. \n + //! Safe to pass between DLLs, but since a reference is used, objects possibly created by other DLLs must be released before owning DLLs are unloaded. + class string { + public: + typedef rcptr_t t_data; + typedef rcptr_t t_dataImpl; + + string() : m_content(rcnew_t<__stringEmpty>()) {} + string(const char * p_source) : m_content(rcnew_t(p_source)) {} + string(const char * p_source, t_size p_sourceLen) : m_content(rcnew_t(p_source,p_sourceLen)) {} + string(char * p_source) : m_content(rcnew_t(p_source)) {} + string(char * p_source, t_size p_sourceLen) : m_content(rcnew_t(p_source,p_sourceLen)) {} + string(t_data const & p_source) : m_content(p_source) {} + string(string_part_ref source) : m_content(rcnew_t(source)) {} + template string(const TSource & p_source); + + string(const string& other) : m_content(other.m_content) {} + string(string&& other) : m_content(std::move(other.m_content)) {} + + const string& operator=(const string& other) {m_content = other.m_content; return *this;} + const string& operator=(string&& other) {m_content = std::move(other.m_content); return *this;} + + + string const & toString() const {return *this;} + + //warning, not length-checked anymore! + static string g_concatenateRaw(const char * item1, t_size len1, const char * item2, t_size len2) { + t_dataImpl impl; impl.new_t(); + char * buffer = impl->lock_buffer(len1+len2); + memcpy_t(buffer,item1,len1); + memcpy_t(buffer+len1,item2,len2); + impl->unlock_buffer(); + return string(t_data(impl)); + } + + string operator+(const string& p_item2) const { + return g_concatenateRaw(ptr(),length(),p_item2.ptr(),p_item2.length()); + } + string operator+(const char * p_item2) const { + return g_concatenateRaw(ptr(),length(),p_item2,strlen(p_item2)); + } + + template string operator+(const TSource & p_item2) const; + + template + const string & operator+=(const TSource & p_item) { + *this = *this + p_item; + return *this; + } + + string subString(t_size base) const { + if (base > length()) throw exception_overflow(); + return string(ptr() + base); + } + string subString(t_size base, t_size count) const { + return string(ptr() + base,count); + } + + string toLower() const { + string8_fastalloc temp; temp.prealloc(128); + stringToLowerAppend(temp,ptr(),~0); + return string(temp.get_ptr()); + } + string toUpper() const { + string8_fastalloc temp; temp.prealloc(128); + stringToUpperAppend(temp,ptr(),~0); + return string(temp.get_ptr()); + } + + string clone() const {return string(ptr());} + + //! @returns ~0 if not found. + t_size indexOf(char c,t_size base = 0) const; + //! @returns ~0 if not found. + t_size lastIndexOf(char c,t_size base = ~0) const; + //! @returns ~0 if not found. + t_size indexOf(stringp s,t_size base = 0) const; + //! @returns ~0 if not found. + t_size lastIndexOf(stringp s,t_size base = ~0) const; + //! @returns ~0 if not found. + t_size indexOfAnyChar(stringp s,t_size base = 0) const; + //! @returns ~0 if not found. + t_size lastIndexOfAnyChar(stringp s,t_size base = ~0) const; + + bool contains(char c) const; + bool contains(stringp s) const; + + bool containsAnyChar(stringp s) const; + + bool startsWith(char c) const; + bool startsWith(string s) const; + bool endsWith(char c) const; + bool endsWith(string s) const; + + char firstChar() const; + char lastChar() const; + + string replace(stringp strOld, stringp strNew) const; + + static int g_compare(const string & p_item1, const string & p_item2) {return strcmp(p_item1.ptr(),p_item2.ptr());} + bool operator==(const string& p_other) const {return g_compare(*this,p_other) == 0;} + bool operator!=(const string& p_other) const {return g_compare(*this,p_other) != 0;} + bool operator<(const string& p_other) const {return g_compare(*this,p_other) < 0;} + bool operator>(const string& p_other) const {return g_compare(*this,p_other) > 0;} + bool operator<=(const string& p_other) const {return g_compare(*this,p_other) <= 0;} + bool operator>=(const string& p_other) const {return g_compare(*this,p_other) >= 0;} + + const char * ptr() const {return m_content->get_ptr();} + const char * get_ptr() const {return m_content->get_ptr();} + const char * c_str() const { return get_ptr(); } + t_size length() const {return m_content->get_length();} + t_size get_length() const {return m_content->get_length();} + + void set_string(const char * ptr, t_size len = ~0) { + *this = string(ptr, len); + } + + static bool isNonTextChar(char c) {return c >= 0 && c < 32;} + + char operator[](t_size p_index) const { + PFC_ASSERT(p_index <= length()); + return ptr()[p_index]; + } + bool isEmpty() const {return length() == 0;} + + class _comparatorCommon { + protected: + template static const char * myStringToPtr(const T& val) {return stringToPtr(val);} + static const char * myStringToPtr(string_part_ref) { + PFC_ASSERT(!"Should never get here"); throw exception_invalid_params(); + } + }; + + class comparatorCaseSensitive : private _comparatorCommon { + public: + template + static int compare(T1 const& v1, T2 const& v2) { + if (is_same_type::value || is_same_type::value) { + return compare_ex(stringToRef(v1), stringToRef(v2)); + } else { + return strcmp(myStringToPtr(v1),myStringToPtr(v2)); + } + } + static int compare_ex(string_part_ref v1, string_part_ref v2) { + return strcmp_ex(v1.m_ptr, v1.m_len, v2.m_ptr, v2.m_len); + } + static int compare_ex(const char * v1, t_size l1, const char * v2, t_size l2) { + return strcmp_ex(v1, l1, v2, l2); + } + }; + class comparatorCaseInsensitive : private _comparatorCommon { + public: + template + static int compare(T1 const& v1, T2 const& v2) { + if (is_same_type::value || is_same_type::value) { + return stringCompareCaseInsensitiveEx(stringToRef(v1), stringToRef(v2)); + } else { + return stringCompareCaseInsensitive(myStringToPtr(v1),myStringToPtr(v2)); + } + } + }; + class comparatorCaseInsensitiveASCII : private _comparatorCommon { + public: + template + static int compare(T1 const& v1, T2 const& v2) { + if (is_same_type::value || is_same_type::value) { + return compare_ex(stringToRef(v1), stringToRef(v2)); + } else { + return stricmp_ascii(myStringToPtr(v1),myStringToPtr(v2)); + } + } + static int compare_ex(string_part_ref v1, string_part_ref v2) { + return stricmp_ascii_ex(v1.m_ptr, v1.m_len, v2.m_ptr, v2.m_len); + } + static int compare_ex(const char * v1, t_size l1, const char * v2, t_size l2) { + return stricmp_ascii_ex(v1, l1, v2, l2); + } + }; + + static bool g_equals(const string & p_item1, const string & p_item2) {return p_item1 == p_item2;} + static bool g_equalsCaseInsensitive(const string & p_item1, const string & p_item2) {return comparatorCaseInsensitive::compare(p_item1,p_item2) == 0;} + + t_data _content() const {return m_content;} + private: + t_data m_content; + }; + + template inline string toString(T const& val) {return val.toString();} + template<> inline string toString(t_int64 const& val) {return format_int(val).get_ptr();} + template<> inline string toString(t_int32 const& val) {return format_int(val).get_ptr();} + template<> inline string toString(t_int16 const& val) {return format_int(val).get_ptr();} + template<> inline string toString(t_uint64 const& val) {return format_uint(val).get_ptr();} + template<> inline string toString(t_uint32 const& val) {return format_uint(val).get_ptr();} + template<> inline string toString(t_uint16 const& val) {return format_uint(val).get_ptr();} + template<> inline string toString(float const& val) {return format_float(val).get_ptr();} + template<> inline string toString(double const& val) {return format_float(val).get_ptr();} + template<> inline string toString(char const& val) {return string(&val,1);} + inline const char * toString(std::exception const& val) {return val.what();} + + template string::string(const TSource & p_source) { + *this = pfc::toString(p_source); + } + template string string::operator+(const TSource & p_item2) const { + return *this + pfc::toString(p_item2); + } + + //! "String parameter" helper class, to use in function parameters, allowing functions to take any type of string as a parameter (const char*, string_base, string). + class stringp { + public: + stringp(const char * ptr) : m_ptr(ptr) {} + stringp(string const &s) : m_ptr(s.ptr()), m_s(s._content()) {} + stringp(string_base const &s) : m_ptr(s.get_ptr()) {} + template stringp(const TWhat& in) : m_ptr(in.toString()) {} + + operator const char*() const {return m_ptr;} + const char * ptr() const {return m_ptr;} + const char * get_ptr() const {return m_ptr;} + string str() const {return m_s.is_valid() ? string(m_s) : string(m_ptr);} + operator string() const {return str();} + string toString() const {return str();} + t_size length() const {return m_s.is_valid() ? m_s->length() : strlen(m_ptr);} + const char * c_str() const { return ptr(); } + private: + const char * const m_ptr; + string::t_data m_s; + }; + + template + string stringCombineList(const TList & list, stringp separator) { + typename TList::const_iterator iter = list.first(); + string acc; + if (iter.is_valid()) { + acc = *iter; + for(++iter; iter.is_valid(); ++iter) { + acc = acc + separator + *iter; + } + } + return acc; + } + + class string; + template<> class traits_t : public traits_default {}; + +} diff --git a/SDK/pfc/string_base.cpp b/SDK/pfc/string_base.cpp new file mode 100644 index 0000000..38dda67 --- /dev/null +++ b/SDK/pfc/string_base.cpp @@ -0,0 +1,1219 @@ +#include "pfc.h" + +namespace pfc { + +void string_receiver::add_char(t_uint32 p_char) +{ + char temp[8]; + t_size len = utf8_encode_char(p_char,temp); + if (len>0) add_string(temp,len); +} + +void string_base::skip_trailing_char(unsigned skip) +{ + const char * str = get_ptr(); + t_size ptr,trunc = 0; + bool need_trunc = false; + for(ptr=0;str[ptr];) + { + unsigned c; + t_size delta = utf8_decode_char(str+ptr,c); + if (delta==0) break; + if (c==skip) + { + need_trunc = true; + trunc = ptr; + } + else + { + need_trunc = false; + } + ptr += delta; + } + if (need_trunc) truncate(trunc); +} + +format_time::format_time(t_uint64 p_seconds) { + t_uint64 length = p_seconds; + unsigned weeks,days,hours,minutes,seconds; + + weeks = (unsigned)( ( length / (60*60*24*7) ) ); + days = (unsigned)( ( length / (60*60*24) ) % 7 ); + hours = (unsigned) ( ( length / (60 * 60) ) % 24); + minutes = (unsigned) ( ( length / (60 ) ) % 60 ); + seconds = (unsigned) ( ( length ) % 60 ); + + if (weeks) { + m_buffer << weeks << "wk "; + } + if (days || weeks) { + m_buffer << days << "d "; + } + if (hours || days || weeks) { + m_buffer << hours << ":" << format_uint(minutes,2) << ":" << format_uint(seconds,2); + } else { + m_buffer << minutes << ":" << format_uint(seconds,2); + } +} + +bool is_path_separator(unsigned c) +{ + return c=='\\' || c=='/' || c=='|' || c==':'; +} + +bool is_path_bad_char(unsigned c) +{ +#ifdef _WINDOWS + return c=='\\' || c=='/' || c=='|' || c==':' || c=='*' || c=='?' || c=='\"' || c=='>' || c=='<'; +#else + return c=='/' || c=='*' || c=='?'; +#endif +} + + + +char * strdup_n(const char * src,t_size len) +{ + len = strlen_max(src,len); + char * ret = (char*)malloc(len+1); + if (ret) + { + memcpy(ret,src,len); + ret[len]=0; + } + return ret; +} + +string_filename::string_filename(const char * fn) +{ + fn += pfc::scan_filename(fn); + const char * ptr=fn,*dot=0; + while(*ptr && *ptr!='?') + { + if (*ptr=='.') dot=ptr; + ptr++; + } + + if (dot && dot>fn) set_string(fn,dot-fn); + else set_string(fn); +} + +string_filename_ext::string_filename_ext(const char * fn) +{ + fn += pfc::scan_filename(fn); + const char * ptr = fn; + while(*ptr && *ptr!='?') ptr++; + set_string(fn,ptr-fn); +} + +string_extension::string_extension(const char * src) +{ + buffer[0]=0; + const char * start = src + pfc::scan_filename(src); + const char * end = start + strlen(start); + const char * ptr = end-1; + while(ptr>start && *ptr!='.') + { + if (*ptr=='?') end=ptr; + ptr--; + } + + if (ptr>=start && *ptr=='.') + { + ptr++; + t_size len = end-ptr; + if (len temp; + t_size outptr; + + if (out_max == 0) return; + out_max--;//for null terminator + + outptr = 0; + + if (outptr == out_max) {out[outptr]=0;return;} + + if (val<0) {out[outptr++] = '-'; val = -val;} + else if (b_sign) {out[outptr++] = '+';} + + if (outptr == out_max) {out[outptr]=0;return;} + + + { + double powval = pow((double)10.0,(double)precision); + temp << (t_int64)floor(val * powval + 0.5); + //_i64toa(blargh,temp,10); + } + + const t_size temp_len = temp.length(); + if (temp_len <= precision) + { + out[outptr++] = '0'; + if (outptr == out_max) {out[outptr]=0;return;} + out[outptr++] = '.'; + if (outptr == out_max) {out[outptr]=0;return;} + t_size d; + for(d=precision-temp_len;d;d--) + { + out[outptr++] = '0'; + if (outptr == out_max) {out[outptr]=0;return;} + } + for(d=0;d='0' && *src<='9') + { + int d = *src - '0'; + val = val * 10 + d; + if (got_dot) div--; + src++; + } + else if (*src=='.' || *src==',') + { + if (got_dot) break; + got_dot = true; + src++; + } + else if (*src=='E' || *src=='e') + { + src++; + div += atoi(src); + break; + } + else break; + } + if (neg) val = -val; + return (double) val * exp_int(10, div); +} + +double string_to_float(const char * src,t_size max) { + //old function wants an oldstyle nullterminated string, and i don't currently care enough to rewrite it as it works appropriately otherwise + char blargh[128]; + if (max > 127) max = 127; + t_size walk; + for(walk = 0; walk < max && src[walk]; walk++) blargh[walk] = src[walk]; + blargh[walk] = 0; + return pfc_string_to_float_internal(blargh); +} + + + +void string_base::convert_to_lower_ascii(const char * src,char replace) +{ + reset(); + PFC_ASSERT(replace>0); + while(*src) + { + unsigned c; + t_size delta = utf8_decode_char(src,c); + if (delta==0) {c = replace; delta = 1;} + else if (c>=0x80) c = replace; + add_byte((char)c); + src += delta; + } +} + +void convert_to_lower_ascii(const char * src,t_size max,char * out,char replace) +{ + t_size ptr = 0; + PFC_ASSERT(replace>0); + while(ptr=0x80) c = replace; + *(out++) = (char)c; + ptr += delta; + } + *out = 0; +} + +t_size strstr_ex(const char * p_string,t_size p_string_len,const char * p_substring,t_size p_substring_len) throw() +{ + p_string_len = strlen_max(p_string,p_string_len); + p_substring_len = strlen_max(p_substring,p_substring_len); + t_size index = 0; + while(index + p_substring_len <= p_string_len) + { + if (memcmp(p_string+index,p_substring,p_substring_len) == 0) return index; + t_size delta = utf8_char_len(p_string+index,p_string_len - index); + if (delta == 0) break; + index += delta; + } + return ~0; +} + +unsigned atoui_ex(const char * p_string,t_size p_string_len) +{ + unsigned ret = 0; t_size ptr = 0; + while(ptr= '0' && c <= '9' ) ) break; + ret = ret * 10 + (unsigned)( c - '0' ); + ptr++; + } + return ret; +} + +int strcmp_nc(const char* p1, size_t n1, const char * p2, size_t n2) throw() { + t_size idx = 0; + for(;;) + { + if (idx == n1 && idx == n2) return 0; + else if (idx == n1) return -1;//end of param1 + else if (idx == n2) return 1;//end of param2 + + char c1 = p1[idx], c2 = p2[idx]; + if (c1c2) return 1; + + idx++; + } +} + +int strcmp_ex(const char* p1,t_size n1,const char* p2,t_size n2) throw() +{ + n1 = strlen_max(p1,n1); n2 = strlen_max(p2,n2); + return strcmp_nc(p1, n1, p2, n2); +} + +t_uint64 atoui64_ex(const char * src,t_size len) { + len = strlen_max(src,len); + t_uint64 ret = 0, mul = 1; + t_size ptr = len; + t_size start = 0; +// start += skip_spacing(src+start,len-start); + + while(ptr>start) + { + char c = src[--ptr]; + if (c>='0' && c<='9') + { + ret += (c-'0') * mul; + mul *= 10; + } + else + { + ret = 0; + mul = 1; + } + } + return ret; +} + + +t_int64 atoi64_ex(const char * src,t_size len) +{ + len = strlen_max(src,len); + t_int64 ret = 0, mul = 1; + t_size ptr = len; + t_size start = 0; + bool neg = false; +// start += skip_spacing(src+start,len-start); + if (start < len && src[start] == '-') {neg = true; start++;} +// start += skip_spacing(src+start,len-start); + + while(ptr>start) + { + char c = src[--ptr]; + if (c>='0' && c<='9') + { + ret += (c-'0') * mul; + mul *= 10; + } + else + { + ret = 0; + mul = 1; + } + } + return neg ? -ret : ret; +} + +int stricmp_ascii_partial( const char * str, const char * substr) throw() { + size_t walk = 0; + for(;;) { + char c1 = str[walk]; + char c2 = substr[walk]; + c1 = ascii_tolower(c1); c2 = ascii_tolower(c2); + if (c2 == 0) return 0; // substr terminated = ret0 regardless of str content + if (c1c2) return 1; // ret 1 early + // else c1 == c2 and c2 != 0 so c1 != 0 either + ++walk; // go on + } +} + +int stricmp_ascii_ex(const char * const s1,t_size const len1,const char * const s2,t_size const len2) throw() { + t_size walk1 = 0, walk2 = 0; + for(;;) { + char c1 = (walk1 < len1) ? s1[walk1] : 0; + char c2 = (walk2 < len2) ? s2[walk2] : 0; + c1 = ascii_tolower(c1); c2 = ascii_tolower(c2); + if (c1c2) return 1; + else if (c1 == 0) return 0; + walk1++; + walk2++; + } + +} +int stricmp_ascii(const char * s1,const char * s2) throw() { + for(;;) { + char c1 = *s1, c2 = *s2; + + if (c1 > 0 && c2 > 0) { + c1 = ascii_tolower_lookup(c1); + c2 = ascii_tolower_lookup(c2); + } else { + if (c1 == 0 && c2 == 0) return 0; + } + if (c1c2) return 1; + else if (c1 == 0) return 0; + + s1++; + s2++; + } +} + +static int naturalSortCompareInternal( const char * s1, const char * s2, bool insensitive) throw() { + for( ;; ) { + unsigned c1, c2; + size_t d1 = utf8_decode_char( s1, c1 ); + size_t d2 = utf8_decode_char( s2, c2 ); + if (d1 == 0 && d2 == 0) { + return 0; + } + if (char_is_numeric( c1 ) && char_is_numeric( c2 ) ) { + // Numeric block in both strings, do natural sort magic here + size_t l1 = 1, l2 = 1; + while( char_is_numeric( s1[l1] ) ) ++l1; + while( char_is_numeric( s2[l2] ) ) ++l2; + + size_t l = max_t(l1, l2); + for(size_t w = 0; w < l; ++w) { + char digit1, digit2; + + t_ssize off; + + off = w + l1 - l; + if (off >= 0) { + digit1 = s1[w - l + l1]; + } else { + digit1 = 0; + } + off = w + l2 - l; + if (off >= 0) { + digit2 = s2[w - l + l2]; + } else { + digit2 = 0; + } + if (digit1 < digit2) return -1; + if (digit1 > digit2) return 1; + } + + s1 += l1; s2 += l2; + continue; + } + + + if (insensitive) { + c1 = charLower( c1 ); + c2 = charLower( c2 ); + } + if (c1 < c2) return -1; + if (c1 > c2) return 1; + + s1 += d1; s2 += d2; + } +} +int naturalSortCompare( const char * s1, const char * s2) throw() { + int v = naturalSortCompareInternal( s1, s2, true ); + if (v) return v; + v = naturalSortCompareInternal( s1, s2, false ); + if (v) return v; + return strcmp(s1, s2); +} + +int naturalSortCompareI( const char * s1, const char * s2) throw() { + return naturalSortCompareInternal( s1, s2, true ); +} + + +format_float::format_float(double p_val,unsigned p_width,unsigned p_prec) +{ + char temp[64]; + float_to_string(temp,64,p_val,p_prec,false); + temp[63] = 0; + t_size len = strlen(temp); + if (len < p_width) + m_buffer.add_chars(' ',p_width-len); + m_buffer += temp; +} + +char format_hex_char(unsigned p_val) +{ + PFC_ASSERT(p_val < 16); + return (p_val < 10) ? p_val + '0' : p_val - 10 + 'A'; +} + +format_hex::format_hex(t_uint64 p_val,unsigned p_width) +{ + if (p_width > 16) p_width = 16; + else if (p_width == 0) p_width = 1; + char temp[16]; + unsigned n; + for(n=0;n<16;n++) + { + temp[15-n] = format_hex_char((unsigned)(p_val & 0xF)); + p_val >>= 4; + } + + for(n=0;n<16 && temp[n] == '0';n++) {} + + if (n > 16 - p_width) n = 16 - p_width; + + char * out = m_buffer; + for(;n<16;n++) + *(out++) = temp[n]; + *out = 0; +} + +char format_hex_char_lowercase(unsigned p_val) +{ + PFC_ASSERT(p_val < 16); + return (p_val < 10) ? p_val + '0' : p_val - 10 + 'a'; +} + +format_hex_lowercase::format_hex_lowercase(t_uint64 p_val,unsigned p_width) +{ + if (p_width > 16) p_width = 16; + else if (p_width == 0) p_width = 1; + char temp[16]; + unsigned n; + for(n=0;n<16;n++) + { + temp[15-n] = format_hex_char_lowercase((unsigned)(p_val & 0xF)); + p_val >>= 4; + } + + for(n=0;n<16 && temp[n] == '0';n++) {} + + if (n > 16 - p_width) n = 16 - p_width; + + char * out = m_buffer; + for(;n<16;n++) + *(out++) = temp[n]; + *out = 0; +} + +format_uint::format_uint(t_uint64 val,unsigned p_width,unsigned p_base) +{ + + enum {max_width = PFC_TABSIZE(m_buffer) - 1}; + + if (p_width > max_width) p_width = max_width; + else if (p_width == 0) p_width = 1; + + char temp[max_width]; + + unsigned n; + for(n=0;n max_width - p_width) n = max_width - p_width; + + char * out = m_buffer; + + for(;n max_width) p_width = max_width; + else if (p_width == 0) p_width = 1; + + if (neg && p_width > 1) p_width --; + + char temp[max_width]; + + unsigned n; + for(n=0;n max_width - p_width) n = max_width - p_width; + + char * out = m_buffer; + + if (neg) *(out++) = '-'; + + for(;n 0 && p_spacing != 0) m_formatter << p_spacing; + m_formatter << format_hex_lowercase(buffer[n],2); + } +} + +format_hexdump::format_hexdump(const void * p_buffer,t_size p_bytes,const char * p_spacing) +{ + t_size n; + const t_uint8 * buffer = (const t_uint8*)p_buffer; + for(n=0;n 0 && p_spacing != 0) m_formatter << p_spacing; + m_formatter << format_hex(buffer[n],2); + } +} + + + +string_replace_extension::string_replace_extension(const char * p_path,const char * p_ext) +{ + m_data = p_path; + t_size dot = m_data.find_last('.'); + if (dot < m_data.scan_filename()) + {//argh + m_data += "."; + m_data += p_ext; + } + else + { + m_data.truncate(dot+1); + m_data += p_ext; + } +} + +string_directory::string_directory(const char * p_path) +{ + t_size ptr = scan_filename(p_path); + if (ptr > 1) { + if (is_path_separator(p_path[ptr-1]) && !is_path_separator(p_path[ptr-2])) --ptr; + } + m_data.set_string(p_path,ptr); +} + +t_size scan_filename(const char * ptr) +{ + t_size n; + t_size _used = strlen(ptr); + for(n=_used-1;n!=~0;n--) + { + if (is_path_separator(ptr[n])) return n+1; + } + return 0; +} + + + +t_size string_find_first(const char * p_string,char p_tofind,t_size p_start) { + for(t_size walk = p_start; p_string[walk]; ++walk) { + if (p_string[walk] == p_tofind) return walk; + } + return ~0; +} +t_size string_find_last(const char * p_string,char p_tofind,t_size p_start) { + return string_find_last_ex(p_string,~0,&p_tofind,1,p_start); +} +t_size string_find_first(const char * p_string,const char * p_tofind,t_size p_start) { + return string_find_first_ex(p_string,~0,p_tofind,~0,p_start); +} +t_size string_find_last(const char * p_string,const char * p_tofind,t_size p_start) { + return string_find_last_ex(p_string,~0,p_tofind,~0,p_start); +} + +t_size string_find_first_ex(const char * p_string,t_size p_string_length,char p_tofind,t_size p_start) { + for(t_size walk = p_start; walk < p_string_length && p_string[walk]; ++walk) { + if (p_string[walk] == p_tofind) return walk; + } + return ~0; +} +t_size string_find_last_ex(const char * p_string,t_size p_string_length,char p_tofind,t_size p_start) { + return string_find_last_ex(p_string,p_string_length,&p_tofind,1,p_start); +} +t_size string_find_first_ex(const char * p_string,t_size p_string_length,const char * p_tofind,t_size p_tofind_length,t_size p_start) { + p_string_length = strlen_max(p_string,p_string_length); p_tofind_length = strlen_max(p_tofind,p_tofind_length); + if (p_string_length >= p_tofind_length) { + t_size max = p_string_length - p_tofind_length; + for(t_size walk = p_start; walk <= max; walk++) { + if (_strcmp_partial_ex(p_string+walk,p_string_length-walk,p_tofind,p_tofind_length) == 0) return walk; + } + } + return ~0; +} +t_size string_find_last_ex(const char * p_string,t_size p_string_length,const char * p_tofind,t_size p_tofind_length,t_size p_start) { + p_string_length = strlen_max(p_string,p_string_length); p_tofind_length = strlen_max(p_tofind,p_tofind_length); + if (p_string_length >= p_tofind_length) { + t_size max = min_t(p_string_length - p_tofind_length,p_start); + for(t_size walk = max; walk != (t_size)(-1); walk--) { + if (_strcmp_partial_ex(p_string+walk,p_string_length-walk,p_tofind,p_tofind_length) == 0) return walk; + } + } + return ~0; +} + +t_size string_find_first_nc(const char * p_string,t_size p_string_length,char c,t_size p_start) { + for(t_size walk = p_start; walk < p_string_length; walk++) { + if (p_string[walk] == c) return walk; + } + return ~0; +} + +t_size string_find_first_nc(const char * p_string,t_size p_string_length,const char * p_tofind,t_size p_tofind_length,t_size p_start) { + if (p_string_length >= p_tofind_length) { + t_size max = p_string_length - p_tofind_length; + for(t_size walk = p_start; walk <= max; walk++) { + if (memcmp(p_string+walk, p_tofind, p_tofind_length) == 0) return walk; + } + } + return ~0; +} + + +bool string_is_numeric(const char * p_string,t_size p_length) throw() { + bool retval = false; + for(t_size walk = 0; walk < p_length && p_string[walk] != 0; walk++) { + if (!char_is_numeric(p_string[walk])) {retval = false; break;} + retval = true; + } + return retval; +} + + +void string_base::end_with(char p_char) { + if (!ends_with(p_char)) add_byte(p_char); +} +bool string_base::ends_with(char c) const { + t_size length = get_length(); + return length > 0 && get_ptr()[length-1] == c; +} + +void string_base::end_with_slash() { + end_with( io::path::getDefaultSeparator() ); +} + +char string_base::last_char() const { + size_t l = this->length(); + if (l == 0) return 0; + return this->get_ptr()[l-1]; +} +void string_base::truncate_last_char() { + size_t l = this->length(); + if (l > 0) this->truncate( l - 1 ); +} + +void string_base::truncate_number_suffix() { + size_t l = this->length(); + const char * const p = this->get_ptr(); + while( l > 0 && char_is_numeric( p[l-1] ) ) --l; + truncate( l ); +} + +bool is_multiline(const char * p_string,t_size p_len) { + for(t_size n = 0; n < p_len && p_string[n]; n++) { + switch(p_string[n]) { + case '\r': + case '\n': + return true; + } + } + return false; +} + +static t_uint64 pow10_helper(unsigned p_extra) { + t_uint64 ret = 1; + for(unsigned n = 0; n < p_extra; n++ ) ret *= 10; + return ret; +} + +static uint64_t safeMulAdd(uint64_t prev, unsigned scale, uint64_t add) { + if (add >= scale || scale == 0) throw pfc::exception_invalid_params(); + uint64_t v = prev * scale + add; + if (v / scale != prev) throw pfc::exception_invalid_params(); + return v; +} + +static size_t parseNumber(const char * in, uint64_t & outNumber) { + size_t walk = 0; + uint64_t total = 0; + for (;;) { + char c = in[walk]; + if (!pfc::char_is_numeric(c)) break; + unsigned v = (unsigned)(c - '0'); + uint64_t newVal = total * 10 + v; + if (newVal / 10 != total) throw pfc::exception_overflow(); + total = newVal; + ++walk; + } + outNumber = total; + return walk; +} + +double parse_timecode(const char * in) { + char separator = 0; + uint64_t seconds = 0; + unsigned colons = 0; + for (;;) { + uint64_t number = 0; + size_t digits = parseNumber(in, number); + if (digits == 0) throw pfc::exception_invalid_params(); + in += digits; + char nextSeparator = *in; + switch (separator) { // *previous* separator + case '.': + if (nextSeparator != 0) throw pfc::exception_bug_check(); + return (double)seconds + (double)pfc::exp_int(10, -(int)digits) * number; + case 0: // is first number in the string + seconds = number; + break; + case ':': + if (colons == 2) throw pfc::exception_invalid_params(); + ++colons; + seconds = safeMulAdd(seconds, 60, number); + break; + } + + if (nextSeparator == 0) { + // end of string + return (double)seconds; + } + + ++in; + separator = nextSeparator; + } +} + +format_time_ex::format_time_ex(double p_seconds,unsigned p_extra) { + t_uint64 pow10 = pow10_helper(p_extra); + t_uint64 ticks = pfc::rint64(pow10 * p_seconds); + + m_buffer << pfc::format_time(ticks / pow10); + if (p_extra>0) { + m_buffer << "." << pfc::format_uint(ticks % pow10, p_extra); + } +} + +void stringToUpperAppend(string_base & out, const char * src, t_size len) { + while(len && *src) { + unsigned c; t_size d; + d = utf8_decode_char(src,c,len); + if (d==0 || d>len) break; + out.add_char(charUpper(c)); + src+=d; + len-=d; + } +} +void stringToLowerAppend(string_base & out, const char * src, t_size len) { + while(len && *src) { + unsigned c; t_size d; + d = utf8_decode_char(src,c,len); + if (d==0 || d>len) break; + out.add_char(charLower(c)); + src+=d; + len-=d; + } +} +int stringCompareCaseInsensitiveEx(string_part_ref s1, string_part_ref s2) { + t_size w1 = 0, w2 = 0; + for(;;) { + unsigned c1, c2; t_size d1, d2; + d1 = utf8_decode_char(s1.m_ptr + w1, c1, s1.m_len - w1); + d2 = utf8_decode_char(s2.m_ptr + w2, c2, s2.m_len - w2); + if (d1 == 0 && d2 == 0) return 0; + else if (d1 == 0) return -1; + else if (d2 == 0) return 1; + else { + c1 = charLower(c1); c2 = charLower(c2); + if (c1 < c2) return -1; + else if (c1 > c2) return 1; + } + w1 += d1; w2 += d2; + } +} +int stringCompareCaseInsensitive(const char * s1, const char * s2) { + for(;;) { + unsigned c1, c2; t_size d1, d2; + d1 = utf8_decode_char(s1,c1); + d2 = utf8_decode_char(s2,c2); + if (d1 == 0 && d2 == 0) return 0; + else if (d1 == 0) return -1; + else if (d2 == 0) return 1; + else { + c1 = charLower(c1); c2 = charLower(c2); + if (c1 < c2) return -1; + else if (c1 > c2) return 1; + } + s1 += d1; s2 += d2; + } +} + +format_file_size_short::format_file_size_short(t_uint64 size) { + t_uint64 scale = 1; + const char * unit = "B"; + const char * const unitTable[] = {"B","KB","MB","GB","TB"}; + for(t_size walk = 1; walk < PFC_TABSIZE(unitTable); ++walk) { + t_uint64 next = scale * 1024; + if (size < next) break; + scale = next; unit = unitTable[walk]; + } + *this << ( size / scale ); + + if (scale > 1 && length() < 3) { + t_size digits = 3 - length(); + const t_uint64 mask = pow_int(10,digits); + t_uint64 remaining = ( (size * mask / scale) % mask ); + while(digits > 0 && (remaining % 10) == 0) { + remaining /= 10; --digits; + } + if (digits > 0) { + *this << "." << format_uint(remaining, (t_uint32)digits); + } + } + *this << " " << unit; + m_scale = scale; +} + +bool string_base::truncate_eol(t_size start) +{ + const char * ptr = get_ptr() + start; + for(t_size n=start;*ptr;n++) + { + if (*ptr==10 || *ptr==13) + { + truncate(n); + return true; + } + ptr++; + } + return false; +} + +bool string_base::fix_eol(const char * append,t_size start) +{ + const bool rv = truncate_eol(start); + if (rv) add_string(append); + return rv; +} + +bool string_base::limit_length(t_size length_in_chars,const char * append) +{ + bool rv = false; + const char * base = get_ptr(), * ptr = base; + while(length_in_chars && utf8_advance(ptr)) length_in_chars--; + if (length_in_chars==0) + { + truncate(ptr-base); + add_string(append); + rv = true; + } + return rv; +} + +void string_base::truncate_to_parent_path() { + size_t at = scan_filename(); +#ifdef _WIN32 + while(at > 0 && (*this)[at-1] == '\\') --at; + if (at > 0 && (*this)[at-1] == ':' && (*this)[at] == '\\') ++at; +#else + // Strip trailing / + while(at > 0 && (*this)[at-1] == '/') --at; + + // Hit empty? Bring root / back to life + if (at == 0 && (*this)[0] == '/') ++at; + + // Deal with proto:// + if (at > 0 && (*this)[at-1] == ':') { + while((*this)[at] == '/') ++at; + } +#endif + this->truncate( at ); +} + +t_size string_base::replace_string ( const char * replace, const char * replaceWith, t_size start) { + string_formatter temp; + size_t srcDone = 0, walk = start; + size_t occurances = 0; + const char * const source = this->get_ptr(); + + const size_t replaceLen = strlen( replace ); + for(;;) { + const char * ptr = strstr( source + walk, replace ); + if (ptr == NULL) { + // end + if (srcDone == 0) { + return 0; // string not altered + } + temp.add_string( source + srcDone ); + break; + } + ++occurances; + walk = ptr - source; + temp.add_string( source + srcDone, walk - srcDone ); + temp.add_string( replaceWith ); + walk += replaceLen; + srcDone = walk; + } + this->set_string( temp ); + return occurances; + +} +void urlEncodeAppendRaw(pfc::string_base & out, const char * in, t_size inSize) { + for(t_size walk = 0; walk < inSize; ++walk) { + const char c = in[walk]; + if (c == ' ') out.add_byte('+'); + else if (pfc::char_is_ascii_alphanumeric(c) || c == '_') out.add_byte(c); + else out << "%" << pfc::format_hex((t_uint8)c, 2); + } +} +void urlEncodeAppend(pfc::string_base & out, const char * in) { + for(;;) { + const char c = *(in++); + if (c == 0) break; + else if (c == ' ') out.add_byte('+'); + else if (pfc::char_is_ascii_alphanumeric(c) || c == '_') out.add_byte(c); + else out << "%" << pfc::format_hex((t_uint8)c, 2); + } +} +void urlEncode(pfc::string_base & out, const char * in) { + out.reset(); urlEncodeAppend(out, in); +} + +unsigned char_to_dec(char c) { + if (c >= '0' && c <= '9') return (unsigned)(c - '0'); + else throw exception_invalid_params(); +} + +unsigned char_to_hex(char c) { + if (c >= '0' && c <= '9') return (unsigned)(c - '0'); + else if (c >= 'a' && c <= 'f') return (unsigned)(c - 'a' + 10); + else if (c >= 'A' && c <= 'F') return (unsigned)(c - 'A' + 10); + else throw exception_invalid_params(); +} + + +static const t_uint8 ascii_tolower_table[128] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F,0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F,0x40,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x5B,0x5C,0x5D,0x5E,0x5F,0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F}; + +uint32_t charLower(uint32_t param) +{ + if (param<128) { + return ascii_tolower_table[param]; + } +#ifdef PFC_WINDOWS_DESKTOP_APP + else if (param<0x10000) { + return (unsigned)CharLowerW((WCHAR*)param); + } +#endif + else return param; +} + +uint32_t charUpper(uint32_t param) +{ + if (param<128) { + if (param>='a' && param<='z') param += 'A' - 'a'; + return param; + } +#ifdef PFC_WINDOWS_DESKTOP_APP + else if (param<0x10000) { + return (unsigned)CharUpperW((WCHAR*)param); + } +#endif + else return param; +} + + +bool stringEqualsI_ascii(const char * p1,const char * p2) throw() { + for(;;) + { + char c1 = *p1; + char c2 = *p2; + if (c1 > 0 && c2 > 0) { + if (ascii_tolower_table[ (unsigned) c1 ] != ascii_tolower_table[ (unsigned) c2 ]) return false; + } else { + if (c1 == 0 && c2 == 0) return true; + if (c1 == 0 || c2 == 0) return false; + if (c1 != c2) return false; + } + ++p1; ++p2; + } +} + +bool stringEqualsI_utf8(const char * p1,const char * p2) throw() +{ + for(;;) + { + char c1 = *p1; + char c2 = *p2; + if (c1 > 0 && c2 > 0) { + if (ascii_tolower_table[ (unsigned) c1 ] != ascii_tolower_table[ (unsigned) c2 ]) return false; + ++p1; ++p2; + } else { + if (c1 == 0 && c2 == 0) return true; + if (c1 == 0 || c2 == 0) return false; + unsigned w1,w2; t_size d1,d2; + d1 = utf8_decode_char(p1,w1); + d2 = utf8_decode_char(p2,w2); + if (d1 == 0 || d2 == 0) return false; // bad UTF-8, bail + if (w1 != w2) { + if (charLower(w1) != charLower(w2)) return false; + } + p1 += d1; + p2 += d2; + } + } +} + +char ascii_tolower_lookup(char c) { + PFC_ASSERT( c >= 0); + return (char)ascii_tolower_table[ (unsigned) c ]; +} + +void string_base::fix_dir_separator(char c) { +#ifdef _WIN32 + end_with(c); +#else + end_with_slash(); +#endif +} + + + bool string_has_prefix( const char * string, const char * prefix ) { + for(size_t w = 0; ; ++w ) { + char c = prefix[w]; + if (c == 0) return true; + if (string[w] != c) return false; + } + } + bool string_has_prefix_i( const char * string, const char * prefix ) { + const char * p1 = string; const char * p2 = prefix; + for(;;) { + unsigned w1, w2; size_t d1, d2; + d1 = utf8_decode_char(p1, w1); + d2 = utf8_decode_char(p2, w2); + if (d2 == 0) return true; + if (d1 == 0) return false; + if (w1 != w2) { + if (charLower(w1) != charLower(w2)) return false; + } + p1 += d1; p2 += d2; + } + } + bool string_has_suffix( const char * string, const char * suffix ) { + size_t len = strlen( string ); + size_t suffixLen = strlen( suffix ); + if (suffixLen > len) return false; + size_t base = len - suffixLen; + return memcmp( string + base, suffix, suffixLen * sizeof(char)) == 0; + } + bool string_has_suffix_i( const char * string, const char * suffix ) { + for(;;) { + if (*string == 0) return false; + if (stringEqualsI_utf8( string, suffix )) return true; + if (!utf8_advance(string)) return false; + } + } + + char * strDup(const char * src) { +#ifdef _MSC_VER + return _strdup(src); +#else + return strdup(src); +#endif + } +} //namespace pfc diff --git a/SDK/pfc/string_base.h b/SDK/pfc/string_base.h new file mode 100644 index 0000000..490273d --- /dev/null +++ b/SDK/pfc/string_base.h @@ -0,0 +1,1101 @@ +#ifndef _PFC_STRING_H_ +#define _PFC_STRING_H_ + +#include + +namespace pfc { + inline t_size _strParamLen(const char * str) { + return strlen(str); + } + + + struct string_part_ref { + const char * m_ptr; + t_size m_len; + + + static string_part_ref make(const char * ptr, t_size len) { + string_part_ref val = {ptr, len}; return val; + } + + string_part_ref substring(t_size base) const { + PFC_ASSERT( base <= m_len ); + return make(m_ptr + base, m_len - base); + } + string_part_ref substring(t_size base, t_size len) const { + PFC_ASSERT( base <= m_len && base + len <= m_len ); + return make(m_ptr + base, len); + } + }; + + inline string_part_ref string_part(const char * ptr, t_size len) { + string_part_ref val = {ptr, len}; return val; + } + + + class NOVTABLE string_receiver { + public: + virtual void add_string(const char * p_string,t_size p_string_size = ~0) = 0; + inline void add_string_(const char * str) {add_string(str, _strParamLen(str));} + + void add_char(t_uint32 c);//adds unicode char to the string + void add_byte(char c) {add_string(&c,1);} + void add_chars(t_uint32 p_char,t_size p_count) {for(;p_count;p_count--) add_char(p_char);} + protected: + string_receiver() {} + ~string_receiver() {} + }; + + t_size scan_filename(const char * ptr); + + bool is_path_separator(unsigned c); + bool is_path_bad_char(unsigned c); + bool is_valid_utf8(const char * param,t_size max = ~0); + bool is_lower_ascii(const char * param); + bool is_multiline(const char * p_string,t_size p_len = ~0); + bool has_path_bad_chars(const char * param); + void recover_invalid_utf8(const char * src,char * out,unsigned replace);//out must be enough to hold strlen(char) + 1, or appropiately bigger if replace needs multiple chars + void convert_to_lower_ascii(const char * src,t_size max,char * out,char replace = '?');//out should be at least strlen(src)+1 long + + template inline char_t ascii_tolower(char_t c) {if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; return c;} + template inline char_t ascii_toupper(char_t c) {if (c >= 'a' && c <= 'z') c += 'A' - 'a'; return c;} + + t_size string_find_first(const char * p_string,char p_tofind,t_size p_start = 0); //returns infinite if not found + t_size string_find_last(const char * p_string,char p_tofind,t_size p_start = ~0); //returns infinite if not found + t_size string_find_first(const char * p_string,const char * p_tofind,t_size p_start = 0); //returns infinite if not found + t_size string_find_last(const char * p_string,const char * p_tofind,t_size p_start = ~0); //returns infinite if not found + + t_size string_find_first_ex(const char * p_string,t_size p_string_length,char p_tofind,t_size p_start = 0); //returns infinite if not found + t_size string_find_last_ex(const char * p_string,t_size p_string_length,char p_tofind,t_size p_start = ~0); //returns infinite if not found + t_size string_find_first_ex(const char * p_string,t_size p_string_length,const char * p_tofind,t_size p_tofind_length,t_size p_start = 0); //returns infinite if not found + t_size string_find_last_ex(const char * p_string,t_size p_string_length,const char * p_tofind,t_size p_tofind_length,t_size p_start = ~0); //returns infinite if not found + + + t_size string_find_first_nc(const char * p_string,t_size p_string_length,char c,t_size p_start = 0); // lengths MUST be valid, no checks are performed (faster than the other flavour) + t_size string_find_first_nc(const char * p_string,t_size p_string_length,const char * p_tofind,t_size p_tofind_length,t_size p_start = 0); // lengths MUST be valid, no checks are performed (faster than the other falvour); + + + bool string_has_prefix( const char * string, const char * prefix ); + bool string_has_prefix_i( const char * string, const char * prefix ); + bool string_has_suffix( const char * string, const char * suffix ); + bool string_has_suffix_i( const char * string, const char * suffix ); + + template + t_size strlen_max_t(const t_char * ptr,t_size max) { + PFC_ASSERT( ptr != NULL || max == 0 ); + t_size n = 0; + while(n inline bool char_is_numeric(char_t p_char) throw() {return p_char >= '0' && p_char <= '9';} + inline bool char_is_hexnumeric(char p_char) throw() {return char_is_numeric(p_char) || (p_char >= 'a' && p_char <= 'f') || (p_char >= 'A' && p_char <= 'F');} + inline bool char_is_ascii_alpha_upper(char p_char) throw() {return p_char >= 'A' && p_char <= 'Z';} + inline bool char_is_ascii_alpha_lower(char p_char) throw() {return p_char >= 'a' && p_char <= 'z';} + inline bool char_is_ascii_alpha(char p_char) throw() {return char_is_ascii_alpha_lower(p_char) || char_is_ascii_alpha_upper(p_char);} + inline bool char_is_ascii_alphanumeric(char p_char) throw() {return char_is_ascii_alpha(p_char) || char_is_numeric(p_char);} + + unsigned atoui_ex(const char * ptr,t_size max); + t_int64 atoi64_ex(const char * ptr,t_size max); + t_uint64 atoui64_ex(const char * ptr,t_size max); + + //Throws exception_invalid_params on failure. + unsigned char_to_hex(char c); + unsigned char_to_dec(char c); + + //Throws exception_invalid_params or exception_overflow on failure. + template t_uint atohex(const char * in, t_size inLen) { + t_uint ret = 0; + const t_uint guard = (t_uint)0xF << (sizeof(t_uint) * 8 - 4); + for(t_size walk = 0; walk < inLen; ++walk) { + if (ret & guard) throw exception_overflow(); + ret = (ret << 4) | char_to_hex(in[walk]); + } + return ret; + } + template t_uint atodec(const char * in, t_size inLen) { + t_uint ret = 0; + for(t_size walk = 0; walk < inLen; ++walk) { + const t_uint prev = ret; + ret = (ret * 10) + char_to_dec(in[walk]); + if ((ret / 10) != prev) throw exception_overflow(); + } + return ret; + } + + t_size strlen_utf8(const char * s,t_size num = ~0) throw();//returns number of characters in utf8 string; num - no. of bytes (optional) + t_size utf8_char_len(const char * s,t_size max = ~0) throw();//returns size of utf8 character pointed by s, in bytes, 0 on error + t_size utf8_char_len_from_header(char c) throw(); + t_size utf8_chars_to_bytes(const char * string,t_size count) throw(); + + t_size strcpy_utf8_truncate(const char * src,char * out,t_size maxbytes); + + template void strcpy_t( char_t * out, const char_t * in ) { + for(;;) { char_t c = *in++; *out++ = c; if (c == 0) break; } + } + + t_size utf8_decode_char(const char * src,unsigned & out,t_size src_bytes) throw();//returns length in bytes + t_size utf8_decode_char(const char * src,unsigned & out) throw();//returns length in bytes + + t_size utf8_encode_char(unsigned c,char * out) throw();//returns used length in bytes, max 6 + + + t_size utf16_decode_char(const char16_t * p_source,unsigned * p_out,t_size p_source_length = ~0) throw(); + t_size utf16_encode_char(unsigned c,char16_t * out) throw(); + +#ifdef _MSC_VER + t_size utf16_decode_char(const wchar_t * p_source,unsigned * p_out,t_size p_source_length = ~0) throw(); + t_size utf16_encode_char(unsigned c,wchar_t * out) throw(); +#endif + + t_size wide_decode_char(const wchar_t * p_source,unsigned * p_out,t_size p_source_length = ~0) throw(); + t_size wide_encode_char(unsigned c,wchar_t * out) throw(); + + + t_size strstr_ex(const char * p_string,t_size p_string_len,const char * p_substring,t_size p_substring_len) throw(); + + + t_size skip_utf8_chars(const char * ptr,t_size count) throw(); + char * strdup_n(const char * src,t_size len); + int stricmp_ascii(const char * s1,const char * s2) throw(); + int stricmp_ascii_ex(const char * s1,t_size len1,const char * s2,t_size len2) throw(); + int naturalSortCompare( const char * s1, const char * s2) throw(); + int naturalSortCompareI( const char * s1, const char * s2) throw(); + + int strcmp_ex(const char* p1,t_size n1,const char* p2,t_size n2) throw(); + int strcmp_nc(const char* p1, size_t n1, const char * p2, size_t n2) throw(); + + unsigned utf8_get_char(const char * src); + + inline bool utf8_advance(const char * & var) throw() { + t_size delta = utf8_char_len(var); + var += delta; + return delta>0; + } + + inline bool utf8_advance(char * & var) throw() { + t_size delta = utf8_char_len(var); + var += delta; + return delta>0; + } + + inline const char * utf8_char_next(const char * src) throw() {return src + utf8_char_len(src);} + inline char * utf8_char_next(char * src) throw() {return src + utf8_char_len(src);} + + class NOVTABLE string_base : public pfc::string_receiver { + public: + virtual const char * get_ptr() const = 0; + const char * c_str() const { return get_ptr(); } + virtual void add_string(const char * p_string,t_size p_length = ~0) = 0;//same as string_receiver method + virtual void set_string(const char * p_string,t_size p_length = ~0) {reset();add_string(p_string,p_length);} + virtual void truncate(t_size len)=0; + virtual t_size get_length() const {return strlen(get_ptr());} + virtual char * lock_buffer(t_size p_requested_length) = 0; + virtual void unlock_buffer() = 0; + + void set_string_(const char * str) {set_string(str, _strParamLen(str));} + + inline const char * toString() const {return get_ptr();} + + //! For compatibility with old conventions. + inline t_size length() const {return get_length();} + + inline void reset() {truncate(0);} + + inline bool is_empty() const {return *get_ptr()==0;} + + void skip_trailing_char(unsigned c = ' '); + + bool is_valid_utf8() const {return pfc::is_valid_utf8(get_ptr());} + + void convert_to_lower_ascii(const char * src,char replace = '?'); + + inline const string_base & operator= (const char * src) {set_string_(src);return *this;} + inline const string_base & operator+= (const char * src) {add_string_(src);return *this;} + inline const string_base & operator= (const string_base & src) {set_string(src);return *this;} + inline const string_base & operator+= (const string_base & src) {add_string(src);return *this;} + + bool operator==(const string_base & p_other) const {return strcmp(*this,p_other) == 0;} + bool operator!=(const string_base & p_other) const {return strcmp(*this,p_other) != 0;} + bool operator>(const string_base & p_other) const {return strcmp(*this,p_other) > 0;} + bool operator<(const string_base & p_other) const {return strcmp(*this,p_other) < 0;} + bool operator>=(const string_base & p_other) const {return strcmp(*this,p_other) >= 0;} + bool operator<=(const string_base & p_other) const {return strcmp(*this,p_other) <= 0;} + + inline operator const char * () const {return get_ptr();} + + t_size scan_filename() const {return pfc::scan_filename(get_ptr());} + + t_size find_first(char p_char,t_size p_start = 0) const {return pfc::string_find_first(get_ptr(),p_char,p_start);} + t_size find_last(char p_char,t_size p_start = ~0) const {return pfc::string_find_last(get_ptr(),p_char,p_start);} + t_size find_first(const char * p_string,t_size p_start = 0) const {return pfc::string_find_first(get_ptr(),p_string,p_start);} + t_size find_last(const char * p_string,t_size p_start = ~0) const {return pfc::string_find_last(get_ptr(),p_string,p_start);} + + void fix_dir_separator(char c = '\\'); // Backwards compat function, "do what I mean" applied on non Windows + void end_with(char c); + void end_with_slash(); + bool ends_with(char c) const; + void delimit(const char* c) {if (length()>0) add_string(c);} + char last_char() const; + void truncate_last_char(); + void truncate_number_suffix(); + + bool truncate_eol(t_size start = 0); + bool fix_eol(const char * append = " (...)",t_size start = 0); + bool limit_length(t_size length_in_chars,const char * append = " (...)"); + + void truncate_filename() {truncate(scan_filename());} + void truncate_to_parent_path(); + void add_filename( const char * fn ) {end_with_slash(); *this += fn; } + + t_size replace_string ( const char * replace, const char * replaceWith, t_size start = 0); + + string_base & _formatter() const {return const_cast(*this);} + + bool has_prefix( const char * prefix) const { return string_has_prefix( get_ptr(), prefix ); } + bool has_prefix_i( const char * prefix ) const { return string_has_prefix_i( get_ptr(), prefix); } + bool has_suffix( const char * suffix ) const { return string_has_suffix( get_ptr(), suffix); } + bool has_suffix_i( const char * suffix ) const { return string_has_suffix_i( get_ptr(), suffix); } + protected: + string_base() {} + ~string_base() {} + }; + + template + class string_fixed_t : public pfc::string_base { + public: + inline string_fixed_t() {init();} + inline string_fixed_t(const string_fixed_t & p_source) {init(); *this = p_source;} + inline string_fixed_t(const char * p_source) {init(); set_string(p_source);} + + inline const string_fixed_t & operator=(const string_fixed_t & p_source) {set_string(p_source);return *this;} + inline const string_fixed_t & operator=(const char * p_source) {set_string(p_source);return *this;} + + char * lock_buffer(t_size p_requested_length) { + if (p_requested_length >= max_length) return NULL; + memset(m_data,0,sizeof(m_data)); + return m_data; + } + void unlock_buffer() { + m_length = strlen(m_data); + } + + inline operator const char * () const {return m_data;} + + const char * get_ptr() const {return m_data;} + + void add_string(const char * ptr,t_size len) { + len = strlen_max(ptr,len); + if (m_length + len < m_length || m_length + len > max_length) throw pfc::exception_overflow(); + for(t_size n=0;n max_length) len = max_length; + if (m_length > len) { + m_length = len; + m_data[len] = 0; + } + } + t_size get_length() const {return m_length;} + private: + inline void init() { + PFC_STATIC_ASSERT(max_length>1); + m_length = 0; m_data[0] = 0; + } + t_size m_length; + char m_data[max_length+1]; + }; + + template class t_alloc> + class string8_t : public pfc::string_base { + private: + typedef string8_t t_self; + protected: + pfc::array_t m_data; + t_size used; + + inline void makespace(t_size s) { + if (t_alloc::alloc_prioritizes_speed) { + m_data.set_size(s); + } else { + const t_size old_size = m_data.get_size(); + if (old_size < s) + m_data.set_size(s + 16); + else if (old_size > s + 32) + m_data.set_size(s); + } + } + + inline const char * _get_ptr() const throw() {return used > 0 ? m_data.get_ptr() : "";} + + public: + inline void set_string_(const char * str) {set_string_nc(str, strlen(str));} + inline void add_string_(const char * str) {add_string_nc(str, strlen(str));} + void set_string_nc(const char * ptr, t_size len) { + PFC_ASSERT(! m_data.is_owned(ptr) ); + PFC_ASSERT( strlen_max(ptr, len) == len ); + makespace(len+1); + pfc::memcpy_t(m_data.get_ptr(),ptr,len); + used=len; + m_data[used]=0; + } + void add_string_nc(const char * ptr, t_size len) { + PFC_ASSERT(! m_data.is_owned(ptr) ); + PFC_ASSERT( strlen_max(ptr, len) == len ); + makespace(used+len+1); + pfc::memcpy_t(m_data.get_ptr() + used,ptr,len); + used+=len; + m_data[used]=0; + } + inline const t_self & operator= (const char * src) {set_string_(src);return *this;} + inline const t_self & operator+= (const char * src) {add_string_(src);return *this;} + inline const t_self & operator= (const string_base & src) {set_string(src);return *this;} + inline const t_self & operator+= (const string_base & src) {add_string(src);return *this;} + inline const t_self & operator= (const t_self & src) {set_string(src);return *this;} + inline const t_self & operator+= (const t_self & src) {add_string(src);return *this;} + + inline const t_self & operator= (string_part_ref src) {set_string(src);return *this;} + inline const t_self & operator+= (string_part_ref src) {add_string(src);return *this;} + + inline operator const char * () const throw() {return _get_ptr();} + + string8_t() : used(0) {} + string8_t(const char * p_string) : used(0) {set_string_(p_string);} + string8_t(const char * p_string,t_size p_length) : used(0) {set_string(p_string,p_length);} + string8_t(const t_self & p_string) : used(0) {set_string(p_string);} + string8_t(const string_base & p_string) : used(0) {set_string(p_string);} + string8_t(string_part_ref ref) : used(0) {set_string(ref);} + + void prealloc(t_size p_size) {m_data.prealloc(p_size+1);} + + const char * get_ptr() const throw() {return _get_ptr();} + + void add_string(const char * p_string,t_size p_length = ~0); + void set_string(const char * p_string,t_size p_length = ~0); + + void set_string(string_part_ref ref) {set_string_nc(ref.m_ptr, ref.m_len);} + void add_string(string_part_ref ref) {add_string_nc(ref.m_ptr, ref.m_len);} + + void truncate(t_size len) + { + if (used>len) {used=len;m_data[len]=0;makespace(used+1);} + } + + t_size get_length() const throw() {return used;} + + + void set_char(unsigned offset,char c); + + t_size replace_nontext_chars(char p_replace = '_'); + t_size replace_char(unsigned c1,unsigned c2,t_size start = 0); + t_size replace_byte(char c1,char c2,t_size start = 0); + void fix_filename_chars(char def = '_',char leave=0);//replace "bad" characters, leave parameter can be used to keep eg. path separators + void remove_chars(t_size first,t_size count); //slow + void insert_chars(t_size first,const char * src, t_size count);//slow + void insert_chars(t_size first,const char * src); + + //for string_buffer class + char * lock_buffer(t_size n) + { + if (n + 1 == 0) throw exception_overflow(); + makespace(n+1); + pfc::memset_t(m_data,(char)0); + return m_data.get_ptr();; + } + + void unlock_buffer() { + if (m_data.get_size() > 0) { + used=strlen(m_data.get_ptr()); + makespace(used+1); + } + } + + void force_reset() {used=0;m_data.force_reset();} + + inline static void g_swap(t_self & p_item1,t_self & p_item2) { + pfc::swap_t(p_item1.m_data,p_item2.m_data); + pfc::swap_t(p_item1.used,p_item2.used); + } + }; + + typedef string8_t string8; + typedef string8_t string8_fast; + typedef string8_t string8_fast_aggressive; + //for backwards compatibility + typedef string8_t string8_fastalloc; + + + template class t_alloc> class traits_t > : public pfc::combine_traits > > { + public: + enum { + needs_constructor = true, + }; + }; +} + + + +#include "string8_impl.h" + +#define PFC_DEPRECATE_PRINTF PFC_DEPRECATE("Use string8/string_fixed_t with operator<< overloads instead.") + +namespace pfc { + + class string_buffer { + private: + string_base & m_owner; + char * m_buffer; + public: + explicit string_buffer(string_base & p_string,t_size p_requested_length) : m_owner(p_string) {m_buffer = m_owner.lock_buffer(p_requested_length);} + ~string_buffer() {m_owner.unlock_buffer();} + char * get_ptr() {return m_buffer;} + operator char* () {return m_buffer;} + }; + + class PFC_DEPRECATE_PRINTF string_printf : public string8_fastalloc { + public: + static void g_run(string_base & out,const char * fmt,va_list list); + void run(const char * fmt,va_list list); + + explicit string_printf(const char * fmt,...); + }; + + class PFC_DEPRECATE_PRINTF string_printf_va : public string8_fastalloc { + public: + string_printf_va(const char * fmt,va_list list); + }; + + class format_time { + public: + format_time(t_uint64 p_seconds); + const char * get_ptr() const {return m_buffer;} + operator const char * () const {return m_buffer;} + protected: + string_fixed_t<127> m_buffer; + }; + + + class format_time_ex { + public: + format_time_ex(double p_seconds,unsigned p_extra = 3); + const char * get_ptr() const {return m_buffer;} + operator const char * () const {return m_buffer;} + private: + string_fixed_t<127> m_buffer; + }; + + + double parse_timecode( const char * tc ); + + class string_filename : public string8 { + public: + explicit string_filename(const char * fn); + }; + + class string_filename_ext : public string8 { + public: + explicit string_filename_ext(const char * fn); + }; + + class string_extension + { + char buffer[32]; + public: + inline const char * get_ptr() const {return buffer;} + inline t_size length() const {return strlen(buffer);} + inline operator const char * () const {return buffer;} + inline const char * toString() const {return buffer;} + explicit string_extension(const char * src); + }; + + + class string_replace_extension + { + public: + string_replace_extension(const char * p_path,const char * p_ext); + inline operator const char*() const {return m_data;} + private: + string8 m_data; + }; + + class string_directory + { + public: + string_directory(const char * p_path); + inline operator const char*() const {return m_data;} + private: + string8 m_data; + }; + + void float_to_string(char * out,t_size out_max,double val,unsigned precision,bool force_sign = false);//doesnt add E+X etc, has internal range limits, useful for storing float numbers as strings without having to bother with international coma/dot settings BS + double string_to_float(const char * src,t_size len = ~0); + + template<> + inline void swap_t(string8 & p_item1,string8 & p_item2) + { + string8::g_swap(p_item1,p_item2); + } + + class format_float + { + public: + format_float(double p_val,unsigned p_width = 0,unsigned p_prec = 7); + format_float(const format_float & p_source) {*this = p_source;} + + inline const char * get_ptr() const {return m_buffer.get_ptr();} + inline const char * toString() const {return m_buffer.get_ptr();} + inline operator const char*() const {return m_buffer.get_ptr();} + private: + string8 m_buffer; + }; + + class format_int + { + public: + format_int(t_int64 p_val,unsigned p_width = 0,unsigned p_base = 10); + format_int(const format_int & p_source) {*this = p_source;} + inline const char * get_ptr() const {return m_buffer;} + inline const char * toString() const {return m_buffer;} + inline operator const char*() const {return m_buffer;} + private: + char m_buffer[64]; + }; + + + class format_uint { + public: + format_uint(t_uint64 p_val,unsigned p_width = 0,unsigned p_base = 10); + format_uint(const format_uint & p_source) {*this = p_source;} + inline const char * get_ptr() const {return m_buffer;} + inline const char * toString() const {return m_buffer;} + inline operator const char*() const {return m_buffer;} + private: + char m_buffer[64]; + }; + + class format_hex + { + public: + format_hex(t_uint64 p_val,unsigned p_width = 0); + format_hex(const format_hex & p_source) {*this = p_source;} + inline const char * get_ptr() const {return m_buffer;} + inline const char * toString() const {return m_buffer;} + inline operator const char*() const {return m_buffer;} + private: + char m_buffer[17]; + }; + + class format_hex_lowercase + { + public: + format_hex_lowercase(t_uint64 p_val,unsigned p_width = 0); + format_hex_lowercase(const format_hex_lowercase & p_source) {*this = p_source;} + inline const char * get_ptr() const {return m_buffer;} + inline operator const char*() const {return m_buffer;} + inline const char * toString() const {return m_buffer;} + private: + char m_buffer[17]; + }; + + char format_hex_char_lowercase(unsigned p_val); + char format_hex_char(unsigned p_val); + + + typedef string8_fastalloc string_formatter; +#define PFC_string_formatter() ::pfc::string_formatter()._formatter() + + class format_hexdump + { + public: + format_hexdump(const void * p_buffer,t_size p_bytes,const char * p_spacing = " "); + + inline const char * get_ptr() const {return m_formatter;} + inline operator const char * () const {return m_formatter;} + inline const char * toString() const {return m_formatter;} + private: + string_formatter m_formatter; + }; + + class format_hexdump_lowercase + { + public: + format_hexdump_lowercase(const void * p_buffer,t_size p_bytes,const char * p_spacing = " "); + + inline const char * get_ptr() const {return m_formatter;} + inline operator const char * () const {return m_formatter;} + inline const char * toString() const {return m_formatter;} + + private: + string_formatter m_formatter; + }; + + class format_fixedpoint + { + public: + format_fixedpoint(t_int64 p_val,unsigned p_point); + inline const char * get_ptr() const {return m_buffer;} + inline operator const char*() const {return m_buffer;} + inline const char * toString() const {return m_buffer;} + private: + string_formatter m_buffer; + }; + + class format_char { + public: + format_char(char p_char) {m_buffer[0] = p_char; m_buffer[1] = 0;} + inline const char * get_ptr() const {return m_buffer;} + inline operator const char*() const {return m_buffer;} + inline const char * toString() const {return m_buffer;} + private: + char m_buffer[2]; + }; + + template + class format_pad_left { + public: + format_pad_left(t_size p_chars,t_uint32 p_padding /* = ' ' */,const char * p_string,t_size p_string_length = ~0) { + t_size source_len = 0, source_walk = 0; + + while(source_walk < p_string_length && source_len < p_chars) { + unsigned dummy; + t_size delta = pfc::utf8_decode_char(p_string + source_walk, dummy, p_string_length - source_walk); + if (delta == 0) break; + source_len++; + source_walk += delta; + } + + m_buffer.add_string(p_string,source_walk); + m_buffer.add_chars(p_padding,p_chars - source_len); + } + inline const char * get_ptr() const {return m_buffer;} + inline operator const char*() const {return m_buffer;} + inline const char * toString() const {return m_buffer;} + private: + t_stringbuffer m_buffer; + }; + + template + class format_pad_right { + public: + format_pad_right(t_size p_chars,t_uint32 p_padding /* = ' ' */,const char * p_string,t_size p_string_length = ~0) { + t_size source_len = 0, source_walk = 0; + + while(source_walk < p_string_length && source_len < p_chars) { + unsigned dummy; + t_size delta = pfc::utf8_decode_char(p_string + source_walk, dummy, p_string_length - source_walk); + if (delta == 0) break; + source_len++; + source_walk += delta; + } + + m_buffer.add_chars(p_padding,p_chars - source_len); + m_buffer.add_string(p_string,source_walk); + } + inline const char * get_ptr() const {return m_buffer;} + inline operator const char*() const {return m_buffer;} + inline const char * toString() const {return m_buffer;} + private: + t_stringbuffer m_buffer; + }; + + + + class format_file_size_short : public string_formatter { + public: + format_file_size_short(t_uint64 size); + t_uint64 get_used_scale() const {return m_scale;} + private: + t_uint64 m_scale; + }; + +} + +inline pfc::string_base & operator<<(pfc::string_base & p_fmt,const char * p_source) {p_fmt.add_string_(p_source); return p_fmt;} +inline pfc::string_base & operator<<(pfc::string_base & p_fmt,pfc::string_part_ref source) {p_fmt.add_string(source.m_ptr, source.m_len); return p_fmt;} +inline pfc::string_base & operator<<(pfc::string_base & p_fmt,short p_val) {p_fmt.add_string(pfc::format_int(p_val)); return p_fmt;} +inline pfc::string_base & operator<<(pfc::string_base & p_fmt,unsigned short p_val) {p_fmt.add_string(pfc::format_uint(p_val)); return p_fmt;} +inline pfc::string_base & operator<<(pfc::string_base & p_fmt,int p_val) {p_fmt.add_string(pfc::format_int(p_val)); return p_fmt;} +inline pfc::string_base & operator<<(pfc::string_base & p_fmt,unsigned p_val) {p_fmt.add_string(pfc::format_uint(p_val)); return p_fmt;} +inline pfc::string_base & operator<<(pfc::string_base & p_fmt,long p_val) {p_fmt.add_string(pfc::format_int(p_val)); return p_fmt;} +inline pfc::string_base & operator<<(pfc::string_base & p_fmt,unsigned long p_val) {p_fmt.add_string(pfc::format_uint(p_val)); return p_fmt;} +inline pfc::string_base & operator<<(pfc::string_base & p_fmt,long long p_val) {p_fmt.add_string(pfc::format_int(p_val)); return p_fmt;} +inline pfc::string_base & operator<<(pfc::string_base & p_fmt,unsigned long long p_val) {p_fmt.add_string(pfc::format_uint(p_val)); return p_fmt;} +inline pfc::string_base & operator<<(pfc::string_base & p_fmt,double p_val) {p_fmt.add_string(pfc::format_float(p_val)); return p_fmt;} +inline pfc::string_base & operator<<(pfc::string_base & p_fmt,std::exception const & p_exception) {p_fmt.add_string(p_exception.what()); return p_fmt;} + +template class t_alloc> inline pfc::string8_t & operator<< (pfc::string8_t & str, const char * src) {str.add_string_(src); return str;} +template class t_alloc> inline pfc::string8_t & operator<< (pfc::string8_t & str, pfc::string_base const & src) {str.add_string(src); return str;} +template class t_alloc> inline pfc::string8_t & operator<< (pfc::string8_t & str, pfc::string_part_ref src) {str.add_string(src); return str;} + + +namespace pfc { + + class format_array : public string_formatter { + public: + template format_array(t_source const & source, const char * separator = ", ") { + const t_size count = array_size_t(source); + if (count > 0) { + *this << source[0]; + for(t_size walk = 1; walk < count; ++walk) *this << separator << source[walk]; + } + } + }; + + + class format_hexdump_ex { + public: + template format_hexdump_ex(const TWord * buffer, t_size bufLen, const char * spacing = " ") { + for(t_size n = 0; n < bufLen; n++) { + if (n > 0 && spacing != NULL) m_formatter << spacing; + m_formatter << format_hex(buffer[n],sizeof(TWord) * 2); + } + } + inline const char * get_ptr() const {return m_formatter;} + inline operator const char * () const {return m_formatter;} + inline const char * toString() const {return m_formatter;} + private: + string_formatter m_formatter; + }; + + + + + + template + class string_simple_t { + private: + typedef string_simple_t t_self; + public: + t_size length() const { + t_size s = m_buffer.get_size(); + if (s == 0) return 0; else return s-1; + } + bool is_empty() const {return m_buffer.get_size() == 0;} + + void set_string_nc(const t_char * p_source, t_size p_length) { + if (p_length == 0) { + m_buffer.set_size(0); + } else { + m_buffer.set_size(p_length + 1); + pfc::memcpy_t(m_buffer.get_ptr(),p_source,p_length); + m_buffer[p_length] = 0; + } + } + void set_string(const t_char * p_source) { + set_string_nc(p_source, pfc::strlen_t(p_source)); + } + void set_string(const t_char * p_source, t_size p_length) { + set_string_nc(p_source, strlen_max_t(p_source, p_length)); + } + void add_string(const t_char * p_source, t_size p_length) { + add_string_nc(p_source, strlen_max_t(p_source, p_length)); + } + void add_string(const t_char * p_source) { + add_string_nc(p_source, strlen_t(p_source)); + } + void add_string_nc(const t_char * p_source, t_size p_length) { + if (p_length > 0) { + t_size base = length(); + m_buffer.set_size( base + p_length + 1 ); + memcpy_t(m_buffer.get_ptr() + base, p_source, p_length); + m_buffer[base + p_length] = 0; + } + } + string_simple_t() {} + string_simple_t(const t_char * p_source) {set_string(p_source);} + string_simple_t(const t_char * p_source, t_size p_length) {set_string(p_source, p_length);} + const t_self & operator=(const t_char * p_source) {set_string(p_source);return *this;} + operator const t_char* () const {return get_ptr();} + const t_char * get_ptr() const {return m_buffer.get_size() > 0 ? m_buffer.get_ptr() : pfc::empty_string_t();} + const t_char * c_str() const { return get_ptr(); } + private: + pfc::array_t m_buffer; + }; + + typedef string_simple_t string_simple; + + template class traits_t > : public traits_t > {}; +} + + +namespace pfc { + class comparator_strcmp { + public: + inline static int compare(const char * p_item1,const char * p_item2) {return strcmp(p_item1,p_item2);} + inline static int compare(const wchar_t * item1, const wchar_t * item2) {return wcscmp(item1, item2);} + + static int compare(const char * p_item1, string_part_ref p_item2) { + return strcmp_ex(p_item1, ~0, p_item2.m_ptr, p_item2.m_len); + } + static int compare(string_part_ref p_item1, string_part_ref p_item2) { + return strcmp_ex(p_item1.m_ptr, p_item1.m_len, p_item2.m_ptr, p_item2.m_len); + } + static int compare(string_part_ref p_item1, const char * p_item2) { + return strcmp_ex(p_item1.m_ptr, p_item1.m_len, p_item2, ~0); + } + }; + + class comparator_stricmp_ascii { + public: + inline static int compare(const char * p_item1,const char * p_item2) {return stricmp_ascii(p_item1,p_item2);} + }; + + + class comparator_naturalSort { + public: + inline static int compare( const char * i1, const char * i2 ) throw() {return naturalSortCompare(i1, i2); } + }; + + template static void stringCombine(pfc::string_base & out, t_source const & in, const char * separator, const char * separatorLast) { + out.reset(); + for(typename t_source::const_iterator walk = in.first(); walk.is_valid(); ++walk) { + if (!out.is_empty()) { + if (walk == in.last()) out << separatorLast; + else out << separator; + } + out << stringToPtr(*walk); + } + } + + template + void splitStringEx(t_output & p_output, const t_splitCheck & p_check, const char * p_string, t_size p_stringLen = ~0) { + t_size walk = 0, splitBase = 0; + const t_size max = strlen_max(p_string,p_stringLen); + for(;walk < max;) { + t_size delta = p_check(p_string + walk,max - walk); + if (delta > 0) { + if (walk > splitBase) p_output(p_string + splitBase, walk - splitBase); + splitBase = walk + delta; + } else { + delta = utf8_char_len(p_string + walk, max - walk); + if (delta == 0) break; + } + walk += delta; + } + if (walk > splitBase) p_output(p_string + splitBase, walk - splitBase); + } + + class __splitStringSimple_calculateSubstringCount { + public: + __splitStringSimple_calculateSubstringCount() : m_count() {} + void operator() (const char *, t_size) {++m_count;} + t_size get() const {return m_count;} + private: + t_size m_count; + }; + + template class _splitStringSimple_check; + + template<> class _splitStringSimple_check { + public: + _splitStringSimple_check(const char * p_chars) { + m_chars.set_size(strlen_utf8(p_chars)); + for(t_size walk = 0, ptr = 0; walk < m_chars.get_size(); ++walk) { + ptr += utf8_decode_char(p_chars + ptr,m_chars[walk]); + } + } + t_size operator()(const char * p_string, t_size p_stringLen) const { + t_uint32 c; + t_size delta = utf8_decode_char(p_string, c, p_stringLen); + if (delta > 0) { + for(t_size walk = 0; walk < m_chars.get_size(); ++walk) { + if (m_chars[walk] == c) return delta; + } + } + return 0; + } + private: + array_t m_chars; + }; + template<> class _splitStringSimple_check { + public: + _splitStringSimple_check(char c) : m_char(c) {} + t_size operator()(const char * str, t_size len) const { + PFC_ASSERT( len > 0 ); + if (*str == m_char) return 1; + else return 0; + } + private: + const char m_char; + }; + template + class __splitStringSimple_arrayWrapper { + public: + __splitStringSimple_arrayWrapper(t_array & p_array) : m_walk(), m_array(p_array) {} + void operator()(const char * p_string, t_size p_stringLen) { + m_array[m_walk++] = string_part(p_string,p_stringLen); + } + private: + t_size m_walk; + t_array & m_array; + }; + template + class __splitStringSimple_listWrapper { + public: + __splitStringSimple_listWrapper(t_list & p_list) : m_list(p_list) {} + void operator()(const char * p_string, t_size p_stringLen) { + m_list += string_part(p_string, p_stringLen); + } + private: + t_list & m_list; + }; + + template + void splitStringSimple_toArray(t_array & p_output, t_split p_split, const char * p_string, t_size p_stringLen = ~0) { + _splitStringSimple_check strCheck(p_split); + + { + __splitStringSimple_calculateSubstringCount wrapper; + splitStringEx(wrapper,strCheck,p_string,p_stringLen); + p_output.set_size(wrapper.get()); + } + + { + __splitStringSimple_arrayWrapper wrapper(p_output); + splitStringEx(wrapper,strCheck,p_string,p_stringLen); + } + } + template + void splitStringSimple_toList(t_list & p_output, t_split p_split, const char * p_string, t_size p_stringLen = ~0) { + _splitStringSimple_check strCheck(p_split); + + __splitStringSimple_listWrapper wrapper(p_output); + splitStringEx(wrapper,strCheck,p_string,p_stringLen); + } + + template void splitStringByLines(t_out & out, const char * str) { + for(;;) { + const char * next = strchr(str, '\n'); + if (next == NULL) { + out += string_part(str, strlen(str)); break; + } + const char * walk = next; + while(walk > str && walk[-1] == '\r') --walk; + out += string_part(str, walk - str); + str = next + 1; + } + } + template void splitStringByChar(t_out & out, const char * str, char c) { + for(;;) { + const char * next = strchr(str, c); + if (next == NULL) { + out += string_part(str, strlen(str)); break; + } + out += string_part(str, next - str); + str = next + 1; + } + } + template void splitStringBySubstring(t_out & out, const char * str, const char * split) { + for(;;) { + const char * next = strstr(str, split); + if (next == NULL) { + out += string_part(str, strlen(str)); break; + } + out += string_part(str, next - str); + str = next + strlen(split); + } + } + + void stringToUpperAppend(string_base & p_out, const char * p_source, t_size p_sourceLen); + void stringToLowerAppend(string_base & p_out, const char * p_source, t_size p_sourceLen); + int stringCompareCaseInsensitive(const char * s1, const char * s2); + int stringCompareCaseInsensitiveEx(string_part_ref s1, string_part_ref s2); + t_uint32 charLower(t_uint32 param); + t_uint32 charUpper(t_uint32 param); + bool stringEqualsI_utf8(const char * p1,const char * p2) throw(); + bool stringEqualsI_ascii(const char * p1,const char * p2) throw(); + char ascii_tolower_lookup(char c); + + template inline const char * stringToPtr(T const& val) {return val.c_str();} + inline const char * stringToPtr(const char* val) {return val;} + + template static string_part_ref stringToRef(T const & val) {return string_part(stringToPtr(val), val.length());} + inline string_part_ref stringToRef(string_part_ref val) {return val;} + inline string_part_ref stringToRef(const char * val) {return string_part(val, strlen(val));} + + + + + class string_base_ref : public string_base { + public: + string_base_ref(const char * ptr) : m_ptr(ptr), m_len(strlen(ptr)) {} + const char * get_ptr() const {return m_ptr;} + t_size get_length() const {return m_len;} + private: + void add_string(const char * p_string,t_size p_length = ~0) {throw pfc::exception_not_implemented();} + void set_string(const char * p_string,t_size p_length = ~0) {throw pfc::exception_not_implemented();} + void truncate(t_size len) {throw pfc::exception_not_implemented();} + char * lock_buffer(t_size p_requested_length) {throw pfc::exception_not_implemented();} + void unlock_buffer() {throw pfc::exception_not_implemented();} + private: + const char * const m_ptr; + t_size const m_len; + }; + + //! Writes a string to a fixed-size buffer. Truncates the string if necessary. Always writes a null terminator. + template + void stringToBuffer(TChar (&buffer)[len], const TSource & source) { + PFC_STATIC_ASSERT(len>0); + t_size walk; + for(walk = 0; walk < len - 1 && source[walk] != 0; ++walk) { + buffer[walk] = source[walk]; + } + buffer[walk] = 0; + } + + //! Same as stringToBuffer() but throws exception_overflow() if the string could not be fully written, including null terminator. + template + void stringToBufferGuarded(TChar (&buffer)[len], const TSource & source) { + t_size walk; + for(walk = 0; source[walk] != 0; ++walk) { + if (walk >= len) throw exception_overflow(); + buffer[walk] = source[walk]; + } + if (walk >= len) throw exception_overflow(); + buffer[walk] = 0; + } + + + template int _strcmp_partial_ex(const t_char * p_string,t_size p_string_length,const t_char * p_substring,t_size p_substring_length) throw() { + for(t_size walk=0;walk=p_string_length ? 0 : p_string[walk]); + t_char substringchar = p_substring[walk]; + int result = compare_t(stringchar,substringchar); + if (result != 0) return result; + } + return 0; + } + + template int strcmp_partial_ex_t(const t_char * p_string,t_size p_string_length,const t_char * p_substring,t_size p_substring_length) throw() { + p_string_length = strlen_max_t(p_string,p_string_length); p_substring_length = strlen_max_t(p_substring,p_substring_length); + return _strcmp_partial_ex(p_string,p_string_length,p_substring,p_substring_length); + } + + template + int strcmp_partial_t(const t_char * p_string,const t_char * p_substring) throw() {return strcmp_partial_ex_t(p_string,~0,p_substring,~0);} + + inline int strcmp_partial_ex(const char * str, t_size strLen, const char * substr, t_size substrLen) throw() {return strcmp_partial_ex(str, strLen, substr, substrLen); } + inline int strcmp_partial(const char * str, const char * substr) throw() {return strcmp_partial_t(str, substr); } + + int stricmp_ascii_partial( const char * str, const char * substr) throw(); + + void urlEncodeAppendRaw(pfc::string_base & out, const char * in, t_size inSize); + void urlEncodeAppend(pfc::string_base & out, const char * in); + void urlEncode(pfc::string_base & out, const char * in); + + + char * strDup(const char * src); // POSIX strdup() clone, prevent MSVC complaining +} + +#endif //_PFC_STRING_H_ diff --git a/SDK/pfc/string_conv.cpp b/SDK/pfc/string_conv.cpp new file mode 100644 index 0000000..996534d --- /dev/null +++ b/SDK/pfc/string_conv.cpp @@ -0,0 +1,454 @@ +#include "pfc.h" + + + +namespace { + template + class string_writer_t { + public: + string_writer_t(t_char * p_buffer,t_size p_size) : m_buffer(p_buffer), m_size(p_size), m_writeptr(0) {} + + void write(t_char p_char) { + if (isChecked) { + if (m_writeptr < m_size) { + m_buffer[m_writeptr++] = p_char; + } + } else { + m_buffer[m_writeptr++] = p_char; + } + } + void write_multi(const t_char * p_buffer,t_size p_count) { + if (isChecked) { + const t_size delta = pfc::min_t(p_count,m_size-m_writeptr); + for(t_size n=0;n(m_writeptr,m_size-1); + m_buffer[terminator] = 0; + return terminator; + } else { + m_buffer[m_writeptr] = 0; + return m_writeptr; + } + } + bool is_overrun() const { + return m_writeptr >= m_size; + } + private: + t_char * m_buffer; + t_size m_size; + t_size m_writeptr; + }; + + + + + static const uint16_t mappings1252[] = { + /*0x80*/ 0x20AC, // #EURO SIGN + /*0x81*/ 0, // #UNDEFINED + /*0x82*/ 0x201A, // #SINGLE LOW-9 QUOTATION MARK + /*0x83*/ 0x0192, // #LATIN SMALL LETTER F WITH HOOK + /*0x84*/ 0x201E, // #DOUBLE LOW-9 QUOTATION MARK + /*0x85*/ 0x2026, // #HORIZONTAL ELLIPSIS + /*0x86*/ 0x2020, // #DAGGER + /*0x87*/ 0x2021, // #DOUBLE DAGGER + /*0x88*/ 0x02C6, // #MODIFIER LETTER CIRCUMFLEX ACCENT + /*0x89*/ 0x2030, // #PER MILLE SIGN + /*0x8A*/ 0x0160, // #LATIN CAPITAL LETTER S WITH CARON + /*0x8B*/ 0x2039, // #SINGLE LEFT-POINTING ANGLE QUOTATION MARK + /*0x8C*/ 0x0152, // #LATIN CAPITAL LIGATURE OE + /*0x8D*/ 0, // #UNDEFINED + /*0x8E*/ 0x017D, // #LATIN CAPITAL LETTER Z WITH CARON + /*0x8F*/ 0, // #UNDEFINED + /*0x90*/ 0, // #UNDEFINED + /*0x91*/ 0x2018, // #LEFT SINGLE QUOTATION MARK + /*0x92*/ 0x2019, // #RIGHT SINGLE QUOTATION MARK + /*0x93*/ 0x201C, // #LEFT DOUBLE QUOTATION MARK + /*0x94*/ 0x201D, // #RIGHT DOUBLE QUOTATION MARK + /*0x95*/ 0x2022, // #BULLET + /*0x96*/ 0x2013, // #EN DASH + /*0x97*/ 0x2014, // #EM DASH + /*0x98*/ 0x02DC, // #SMALL TILDE + /*0x99*/ 0x2122, // #TRADE MARK SIGN + /*0x9A*/ 0x0161, // #LATIN SMALL LETTER S WITH CARON + /*0x9B*/ 0x203A, // #SINGLE RIGHT-POINTING ANGLE QUOTATION MARK + /*0x9C*/ 0x0153, // #LATIN SMALL LIGATURE OE + /*0x9D*/ 0, // #UNDEFINED + /*0x9E*/ 0x017E, // #LATIN SMALL LETTER Z WITH CARON + /*0x9F*/ 0x0178, // #LATIN CAPITAL LETTER Y WITH DIAERESIS + }; + + static bool charImport1252(uint32_t & unichar, char c) { + uint8_t uc = (uint8_t) c; + if (uc == 0) return false; + else if (uc < 0x80) {unichar = uc; return true;} + else if (uc < 0xA0) { + uint32_t t = mappings1252[uc-0x80]; + if (t == 0) return false; + unichar = t; return true; + } else { + unichar = uc; return true; + } + } + + static bool charExport1252(char & c, uint32_t unichar) { + if (unichar == 0) return false; + else if (unichar < 0x80 || (unichar >= 0xa0 && unichar <= 0xFF)) {c = (char)(uint8_t)unichar; return true;} + for(size_t walk = 0; walk < PFC_TABSIZE(mappings1252); ++walk) { + if (unichar == mappings1252[walk]) { + c = (char)(uint8_t)(walk + 0x80); + return true; + } + } + return false; + } + struct asciiMap_t {uint16_t from; uint8_t to;}; + static const asciiMap_t g_asciiMap[] = { + {160,32},{161,33},{162,99},{164,36},{165,89},{166,124},{169,67},{170,97},{171,60},{173,45},{174,82},{178,50},{179,51},{183,46},{184,44},{185,49},{186,111},{187,62},{192,65},{193,65},{194,65},{195,65},{196,65},{197,65},{198,65},{199,67},{200,69},{201,69},{202,69},{203,69},{204,73},{205,73},{206,73},{207,73},{208,68},{209,78},{210,79},{211,79},{212,79},{213,79},{214,79},{216,79},{217,85},{218,85},{219,85},{220,85},{221,89},{224,97},{225,97},{226,97},{227,97},{228,97},{229,97},{230,97},{231,99},{232,101},{233,101},{234,101},{235,101},{236,105},{237,105},{238,105},{239,105},{241,110},{242,111},{243,111},{244,111},{245,111},{246,111},{248,111},{249,117},{250,117},{251,117},{252,117},{253,121},{255,121},{256,65},{257,97},{258,65},{259,97},{260,65},{261,97},{262,67},{263,99},{264,67},{265,99},{266,67},{267,99},{268,67},{269,99},{270,68},{271,100},{272,68},{273,100},{274,69},{275,101},{276,69},{277,101},{278,69},{279,101},{280,69},{281,101},{282,69},{283,101},{284,71},{285,103},{286,71},{287,103},{288,71},{289,103},{290,71},{291,103},{292,72},{293,104},{294,72},{295,104},{296,73},{297,105},{298,73},{299,105},{300,73},{301,105},{302,73},{303,105},{304,73},{305,105},{308,74},{309,106},{310,75},{311,107},{313,76},{314,108},{315,76},{316,108},{317,76},{318,108},{321,76},{322,108},{323,78},{324,110},{325,78},{326,110},{327,78},{328,110},{332,79},{333,111},{334,79},{335,111},{336,79},{337,111},{338,79},{339,111},{340,82},{341,114},{342,82},{343,114},{344,82},{345,114},{346,83},{347,115},{348,83},{349,115},{350,83},{351,115},{352,83},{353,115},{354,84},{355,116},{356,84},{357,116},{358,84},{359,116},{360,85},{361,117},{362,85},{363,117},{364,85},{365,117},{366,85},{367,117},{368,85},{369,117},{370,85},{371,117},{372,87},{373,119},{374,89},{375,121},{376,89},{377,90},{378,122},{379,90},{380,122},{381,90},{382,122},{384,98},{393,68},{401,70},{402,102},{407,73},{410,108},{415,79},{416,79},{417,111},{427,116},{430,84},{431,85},{432,117},{438,122},{461,65},{462,97},{463,73},{464,105},{465,79},{466,111},{467,85},{468,117},{469,85},{470,117},{471,85},{472,117},{473,85},{474,117},{475,85},{476,117},{478,65},{479,97},{484,71},{485,103},{486,71},{487,103},{488,75},{489,107},{490,79},{491,111},{492,79},{493,111},{496,106},{609,103},{697,39},{698,34},{700,39},{708,94},{710,94},{712,39},{715,96},{717,95},{732,126},{768,96},{770,94},{771,126},{782,34},{817,95},{818,95},{8192,32},{8193,32},{8194,32},{8195,32},{8196,32},{8197,32},{8198,32},{8208,45},{8209,45},{8211,45},{8212,45},{8216,39},{8217,39},{8218,44},{8220,34},{8221,34},{8222,34},{8226,46},{8230,46},{8242,39},{8245,96},{8249,60},{8250,62},{8482,84},{65281,33},{65282,34},{65283,35},{65284,36},{65285,37},{65286,38},{65287,39},{65288,40},{65289,41},{65290,42},{65291,43},{65292,44},{65293,45},{65294,46},{65295,47},{65296,48},{65297,49},{65298,50},{65299,51},{65300,52},{65301,53},{65302,54},{65303,55},{65304,56},{65305,57},{65306,58},{65307,59},{65308,60},{65309,61},{65310,62},{65312,64},{65313,65},{65314,66},{65315,67},{65316,68},{65317,69},{65318,70},{65319,71},{65320,72},{65321,73},{65322,74},{65323,75},{65324,76},{65325,77},{65326,78},{65327,79},{65328,80},{65329,81},{65330,82},{65331,83},{65332,84},{65333,85},{65334,86},{65335,87},{65336,88},{65337,89},{65338,90},{65339,91},{65340,92},{65341,93},{65342,94},{65343,95},{65344,96},{65345,97},{65346,98},{65347,99},{65348,100},{65349,101},{65350,102},{65351,103},{65352,104},{65353,105},{65354,106},{65355,107},{65356,108},{65357,109},{65358,110},{65359,111},{65360,112},{65361,113},{65362,114},{65363,115},{65364,116},{65365,117},{65366,118},{65367,119},{65368,120},{65369,121},{65370,122},{65371,123},{65372,124},{65373,125},{65374,126}}; + +} + +namespace pfc { + namespace stringcvt { + + char charToASCII( unsigned c ) { + if (c < 128) return (char)c; + unsigned lo = 0, hi = PFC_TABSIZE(g_asciiMap); + while( lo < hi ) { + const unsigned mid = (lo + hi) / 2; + const asciiMap_t entry = g_asciiMap[mid]; + if ( c > entry.from ) { + lo = mid + 1; + } else if (c < entry.from) { + hi = mid; + } else { + return (char)entry.to; + } + } + return '?'; + } + + t_size convert_utf8_to_wide(wchar_t * p_out,t_size p_out_size,const char * p_in,t_size p_in_size) { + const t_size insize = p_in_size; + t_size inptr = 0; + string_writer_t writer(p_out,p_out_size); + + while(inptr < insize && !writer.is_overrun()) { + unsigned newchar = 0; + t_size delta = utf8_decode_char(p_in + inptr,newchar,insize - inptr); + if (delta == 0 || newchar == 0) break; + PFC_ASSERT(inptr + delta <= insize); + inptr += delta; + writer.write_as_wide(newchar); + } + + return writer.finalize(); + } + + t_size convert_utf8_to_wide_unchecked(wchar_t * p_out,const char * p_in) { + t_size inptr = 0; + string_writer_t writer(p_out,~0); + + while(!writer.is_overrun()) { + unsigned newchar = 0; + t_size delta = utf8_decode_char(p_in + inptr,newchar); + if (delta == 0 || newchar == 0) break; + inptr += delta; + writer.write_as_wide(newchar); + } + + return writer.finalize(); + } + + t_size convert_wide_to_utf8(char * p_out,t_size p_out_size,const wchar_t * p_in,t_size p_in_size) { + const t_size insize = p_in_size; + t_size inptr = 0; + string_writer_t writer(p_out,p_out_size); + + while(inptr < insize && !writer.is_overrun()) { + unsigned newchar = 0; + t_size delta = wide_decode_char(p_in + inptr,&newchar,insize - inptr); + if (delta == 0 || newchar == 0) break; + PFC_ASSERT(inptr + delta <= insize); + inptr += delta; + writer.write_as_utf8(newchar); + } + + return writer.finalize(); + } + + t_size estimate_utf8_to_wide(const char * p_in) { + t_size inptr = 0; + t_size retval = 1;//1 for null terminator + for(;;) { + unsigned newchar = 0; + t_size delta = utf8_decode_char(p_in + inptr,newchar); + if (delta == 0 || newchar == 0) break; + inptr += delta; + + { + wchar_t temp[2]; + retval += wide_encode_char(newchar,temp); + } + } + return retval; + } + + t_size estimate_utf8_to_wide(const char * p_in,t_size p_in_size) { + const t_size insize = p_in_size; + t_size inptr = 0; + t_size retval = 1;//1 for null terminator + while(inptr < insize) { + unsigned newchar = 0; + t_size delta = utf8_decode_char(p_in + inptr,newchar,insize - inptr); + if (delta == 0 || newchar == 0) break; + PFC_ASSERT(inptr + delta <= insize); + inptr += delta; + + { + wchar_t temp[2]; + retval += wide_encode_char(newchar,temp); + } + } + return retval; + } + + t_size estimate_wide_to_utf8(const wchar_t * p_in,t_size p_in_size) { + const t_size insize = p_in_size; + t_size inptr = 0; + t_size retval = 1;//1 for null terminator + while(inptr < insize) { + unsigned newchar = 0; + t_size delta = wide_decode_char(p_in + inptr,&newchar,insize - inptr); + if (delta == 0 || newchar == 0) break; + PFC_ASSERT(inptr + delta <= insize); + inptr += delta; + + { + char temp[6]; + delta = utf8_encode_char(newchar,temp); + if (delta == 0) break; + retval += delta; + } + } + return retval; + } + + t_size estimate_wide_to_win1252( const wchar_t * p_in, t_size p_in_size ) { + const t_size insize = p_in_size; + t_size inptr = 0; + t_size retval = 1;//1 for null terminator + while(inptr < insize) { + unsigned newchar = 0; + t_size delta = wide_decode_char(p_in + inptr,&newchar,insize - inptr); + if (delta == 0 || newchar == 0) break; + PFC_ASSERT(inptr + delta <= insize); + inptr += delta; + + ++retval; + } + return retval; + + } + + t_size convert_wide_to_win1252( char * p_out, t_size p_out_size, const wchar_t * p_in, t_size p_in_size ) { + const t_size insize = p_in_size; + t_size inptr = 0; + string_writer_t writer(p_out,p_out_size); + + while(inptr < insize && !writer.is_overrun()) { + unsigned newchar = 0; + t_size delta = wide_decode_char(p_in + inptr,&newchar,insize - inptr); + if (delta == 0 || newchar == 0) break; + PFC_ASSERT(inptr + delta <= insize); + inptr += delta; + + char temp; + if (!charExport1252( temp, newchar )) temp = '?'; + writer.write( temp ); + } + + return writer.finalize(); + + } + + t_size estimate_win1252_to_wide( const char * p_source, t_size p_source_size ) { + return strlen_max_t( p_source, p_source_size ) + 1; + } + + t_size convert_win1252_to_wide( wchar_t * p_out, t_size p_out_size, const char * p_in, t_size p_in_size ) { + const t_size insize = p_in_size; + t_size inptr = 0; + string_writer_t writer(p_out,p_out_size); + + while(inptr < insize && !writer.is_overrun()) { + char inChar = p_in[inptr]; + if (inChar == 0) break; + ++inptr; + + unsigned out; + if (!charImport1252( out , inChar )) out = '?'; + writer.write_as_wide( out ); + } + + return writer.finalize(); + } + + t_size estimate_utf8_to_win1252( const char * p_in, t_size p_in_size ) { + const t_size insize = p_in_size; + t_size inptr = 0; + t_size retval = 1;//1 for null terminator + while(inptr < insize) { + unsigned newchar = 0; + t_size delta = utf8_decode_char(p_in + inptr,newchar,insize - inptr); + if (delta == 0 || newchar == 0) break; + PFC_ASSERT(inptr + delta <= insize); + inptr += delta; + + ++retval; + } + return retval; + } + t_size convert_utf8_to_win1252( char * p_out, t_size p_out_size, const char * p_in, t_size p_in_size ) { + const t_size insize = p_in_size; + t_size inptr = 0; + string_writer_t writer(p_out,p_out_size); + + while(inptr < insize && !writer.is_overrun()) { + unsigned newchar = 0; + t_size delta = utf8_decode_char(p_in + inptr,newchar,insize - inptr); + if (delta == 0 || newchar == 0) break; + PFC_ASSERT(inptr + delta <= insize); + inptr += delta; + + char temp; + if (!charExport1252( temp, newchar )) temp = '?'; + writer.write( temp ); + } + + return writer.finalize(); + } + + t_size estimate_win1252_to_utf8( const char * p_in, t_size p_in_size ) { + const size_t insize = p_in_size; + t_size inptr = 0; + t_size retval = 1; // 1 for null terminator + while(inptr < insize) { + unsigned newchar; + char c = p_in[inptr]; + if (c == 0) break; + ++inptr; + if (!charImport1252( newchar, c)) newchar = '?'; + + char temp[6]; + retval += pfc::utf8_encode_char( newchar, temp ); + } + return retval; + } + + t_size convert_win1252_to_utf8( char * p_out, t_size p_out_size, const char * p_in, t_size p_in_size ) { + const t_size insize = p_in_size; + t_size inptr = 0; + string_writer_t writer(p_out,p_out_size); + + while(inptr < insize && !writer.is_overrun()) { + char inChar = p_in[inptr]; + if (inChar == 0) break; + ++inptr; + + unsigned out; + if (!charImport1252( out , inChar )) out = '?'; + writer.write_as_utf8( out ); + } + + return writer.finalize(); + } + + t_size estimate_utf8_to_ascii( const char * p_source, t_size p_source_size ) { + return estimate_utf8_to_win1252( p_source, p_source_size ); + } + t_size convert_utf8_to_ascii( char * p_out, t_size p_out_size, const char * p_in, t_size p_in_size ) { + const t_size insize = p_in_size; + t_size inptr = 0; + string_writer_t writer(p_out,p_out_size); + + while(inptr < insize && !writer.is_overrun()) { + unsigned newchar = 0; + t_size delta = utf8_decode_char(p_in + inptr,newchar,insize - inptr); + if (delta == 0 || newchar == 0) break; + PFC_ASSERT(inptr + delta <= insize); + inptr += delta; + + writer.write( charToASCII(newchar) ); + } + + return writer.finalize(); + } + + } +} + +#ifdef _WINDOWS + + +namespace pfc { + namespace stringcvt { + + + t_size convert_codepage_to_wide(unsigned p_codepage,wchar_t * p_out,t_size p_out_size,const char * p_source,t_size p_source_size) { + if (p_out_size == 0) return 0; + memset(p_out,0,p_out_size * sizeof(*p_out)); + MultiByteToWideChar(p_codepage,0,p_source,p_source_size,p_out,p_out_size); + p_out[p_out_size-1] = 0; + return wcslen(p_out); + } + + t_size convert_wide_to_codepage(unsigned p_codepage,char * p_out,t_size p_out_size,const wchar_t * p_source,t_size p_source_size) { + if (p_out_size == 0) return 0; + memset(p_out,0,p_out_size * sizeof(*p_out)); + WideCharToMultiByte(p_codepage,0,p_source,p_source_size,p_out,p_out_size,0,FALSE); + p_out[p_out_size-1] = 0; + return strlen(p_out); + } + + t_size estimate_codepage_to_wide(unsigned p_codepage,const char * p_source,t_size p_source_size) { + return MultiByteToWideChar(p_codepage,0,p_source,strlen_max(p_source,p_source_size),0,0) + 1; + } + t_size estimate_wide_to_codepage(unsigned p_codepage,const wchar_t * p_source,t_size p_source_size) { + return WideCharToMultiByte(p_codepage,0,p_source,wcslen_max(p_source,p_source_size),0,0,0,FALSE) + 1; + } + } + +} + +#endif //_WINDOWS diff --git a/SDK/pfc/string_conv.h b/SDK/pfc/string_conv.h new file mode 100644 index 0000000..518a73e --- /dev/null +++ b/SDK/pfc/string_conv.h @@ -0,0 +1,558 @@ +namespace pfc { + + namespace stringcvt { + //! Converts UTF-8 characters to wide character. + //! @param p_out Output buffer, receives converted string, with null terminator. + //! @param p_out_size Size of output buffer, in characters. If converted string is too long, it will be truncated. Null terminator is always written, unless p_out_size is zero. + //! @param p_source String to convert. + //! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier. + //! @returns Number of characters written, not counting null terminator. + t_size convert_utf8_to_wide(wchar_t * p_out,t_size p_out_size,const char * p_source,t_size p_source_size); + + + //! Estimates buffer size required to convert specified UTF-8 string to widechar. + //! @param p_source String to be converted. + //! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier. + //! @returns Number of characters to allocate, including space for null terminator. + t_size estimate_utf8_to_wide(const char * p_source,t_size p_source_size); + + t_size estimate_utf8_to_wide(const char * p_source); + + //! Converts wide character string to UTF-8. + //! @param p_out Output buffer, receives converted string, with null terminator. + //! @param p_out_size Size of output buffer, in characters. If converted string is too long, it will be truncated. Null terminator is always written, unless p_out_size is zero. + //! @param p_source String to convert. + //! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier. + //! @returns Number of characters written, not counting null terminator. + t_size convert_wide_to_utf8(char * p_out,t_size p_out_size,const wchar_t * p_source,t_size p_source_size); + + //! Estimates buffer size required to convert specified wide character string to UTF-8. + //! @param p_source String to be converted. + //! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier. + //! @returns Number of characters to allocate, including space for null terminator. + t_size estimate_wide_to_utf8(const wchar_t * p_source,t_size p_source_size); + + t_size estimate_utf8_to_ascii( const char * p_source, t_size p_source_size ); + t_size convert_utf8_to_ascii( char * p_out, t_size p_out_size, const char * p_source, t_size p_source_size ); + + t_size estimate_wide_to_win1252( const wchar_t * p_source, t_size p_source_size ); + t_size convert_wide_to_win1252( char * p_out, t_size p_out_size, const wchar_t * p_source, t_size p_source_size ); + t_size estimate_win1252_to_wide( const char * p_source, t_size p_source_size ); + t_size convert_win1252_to_wide( wchar_t * p_out, t_size p_out_size, const char * p_source, t_size p_source_size ); + + t_size estimate_utf8_to_win1252( const char * p_source, t_size p_source_size ); + t_size convert_utf8_to_win1252( char * p_out, t_size p_out_size, const char * p_source, t_size p_source_size ); + t_size estimate_win1252_to_utf8( const char * p_source, t_size p_source_size ); + t_size convert_win1252_to_utf8( char * p_out, t_size p_out_size, const char * p_source, t_size p_source_size ); + + + + //! estimate_utf8_to_wide_quick() functions use simple math to determine buffer size required for the conversion. The result is not accurate length of output string - it's just a safe estimate of required buffer size, possibly bigger than what's really needed. \n + //! These functions are meant for scenarios when speed is more important than memory usage. + inline t_size estimate_utf8_to_wide_quick(t_size sourceLen) { + return sourceLen + 1; + } + inline t_size estimate_utf8_to_wide_quick(const char * source) { + return estimate_utf8_to_wide_quick(strlen(source)); + } + inline t_size estimate_utf8_to_wide_quick(const char * source, t_size sourceLen) { + return estimate_utf8_to_wide_quick(strlen_max(source, sourceLen)); + } + t_size convert_utf8_to_wide_unchecked(wchar_t * p_out,const char * p_source); + + template const t_char * null_string_t(); + template<> inline const char * null_string_t() {return "";} + template<> inline const wchar_t * null_string_t() {return L"";} + + template t_size strlen_t(const t_char * p_string,t_size p_string_size = ~0) { + for(t_size n=0;n bool string_is_empty_t(const t_char * p_string,t_size p_string_size = ~0) { + if (p_string_size == 0) return true; + return p_string[0] == 0; + } + + template class t_alloc = pfc::alloc_standard> class char_buffer_t { + public: + char_buffer_t() {} + char_buffer_t(const char_buffer_t & p_source) : m_buffer(p_source.m_buffer) {} + void set_size(t_size p_count) {m_buffer.set_size(p_count);} + t_char * get_ptr_var() {return m_buffer.get_ptr();} + const t_char * get_ptr() const { + return m_buffer.get_size() > 0 ? m_buffer.get_ptr() : null_string_t(); + } + private: + pfc::array_t m_buffer; + }; + + template class t_alloc = pfc::alloc_standard> + class string_utf8_from_wide_t { + public: + string_utf8_from_wide_t() {} + string_utf8_from_wide_t(const wchar_t * p_source,t_size p_source_size = ~0) {convert(p_source,p_source_size);} + + void convert(const wchar_t * p_source,t_size p_source_size = ~0) { + t_size size = estimate_wide_to_utf8(p_source,p_source_size); + m_buffer.set_size(size); + convert_wide_to_utf8( m_buffer.get_ptr_var(),size,p_source,p_source_size); + } + + operator const char * () const {return get_ptr();} + const char * get_ptr() const {return m_buffer.get_ptr();} + const char * toString() const {return get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + + private: + char_buffer_t m_buffer; + }; + typedef string_utf8_from_wide_t<> string_utf8_from_wide; + + template class t_alloc = pfc::alloc_standard> + class string_wide_from_utf8_t { + public: + string_wide_from_utf8_t() {} + string_wide_from_utf8_t(const char* p_source) {convert(p_source);} + string_wide_from_utf8_t(const char* p_source,t_size p_source_size) {convert(p_source,p_source_size);} + + void convert(const char* p_source,t_size p_source_size) { + const t_size size = estimate_size(p_source, p_source_size); + m_buffer.set_size(size); + convert_utf8_to_wide( m_buffer.get_ptr_var(),size,p_source,p_source_size ); + } + void convert(const char * p_source) { + m_buffer.set_size( estimate_size(p_source) ); + convert_utf8_to_wide_unchecked(m_buffer.get_ptr_var(), p_source); + } + + operator const wchar_t * () const {return get_ptr();} + const wchar_t * get_ptr() const {return m_buffer.get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + + void append(const char* p_source,t_size p_source_size) { + const t_size base = length(); + const t_size size = estimate_size(p_source, p_source_size); + m_buffer.set_size(base + size); + convert_utf8_to_wide( m_buffer.get_ptr_var() + base, size, p_source, p_source_size ); + } + void append(const char * p_source) { + const t_size base = length(); + m_buffer.set_size( base + estimate_size(p_source) ); + convert_utf8_to_wide_unchecked(m_buffer.get_ptr_var() + base, p_source); + } + + enum { alloc_prioritizes_speed = t_alloc::alloc_prioritizes_speed }; + private: + + inline t_size estimate_size(const char * source, t_size sourceLen) { + return alloc_prioritizes_speed ? estimate_utf8_to_wide_quick(source, sourceLen) : estimate_utf8_to_wide(source,sourceLen); + } + inline t_size estimate_size(const char * source) { + return alloc_prioritizes_speed ? estimate_utf8_to_wide_quick(source) : estimate_utf8_to_wide(source,~0); + } + char_buffer_t m_buffer; + }; + typedef string_wide_from_utf8_t<> string_wide_from_utf8; + typedef string_wide_from_utf8_t string_wide_from_utf8_fast; + + + template class t_alloc = pfc::alloc_standard> + class string_wide_from_win1252_t { + public: + string_wide_from_win1252_t() {} + string_wide_from_win1252_t(const char * p_source,t_size p_source_size = ~0) {convert(p_source,p_source_size);} + + void convert(const char * p_source,t_size p_source_size = ~0) { + t_size size = estimate_win1252_to_wide(p_source,p_source_size); + m_buffer.set_size(size); + convert_win1252_to_wide(m_buffer.get_ptr_var(),size,p_source,p_source_size); + } + + operator const wchar_t * () const {return get_ptr();} + const wchar_t * get_ptr() const {return m_buffer.get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + + private: + char_buffer_t m_buffer; + }; + typedef string_wide_from_win1252_t<> string_wide_from_win1252; + + + template class t_alloc = pfc::alloc_standard> + class string_win1252_from_wide_t { + public: + string_win1252_from_wide_t() {} + string_win1252_from_wide_t(const wchar_t * p_source,t_size p_source_size = ~0) {convert(p_source,p_source_size);} + + void convert(const wchar_t * p_source,t_size p_source_size = ~0) { + t_size size = estimate_wide_to_win1252(p_source,p_source_size); + m_buffer.set_size(size); + convert_wide_to_win1252(m_buffer.get_ptr_var(),size,p_source,p_source_size); + } + + operator const char * () const {return get_ptr();} + const char * get_ptr() const {return m_buffer.get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + + private: + char_buffer_t m_buffer; + }; + typedef string_win1252_from_wide_t<> string_win1252_from_wide; + + + template class t_alloc = pfc::alloc_standard> + class string_utf8_from_win1252_t { + public: + string_utf8_from_win1252_t() {} + string_utf8_from_win1252_t(const char * p_source,t_size p_source_size = ~0) {convert(p_source,p_source_size);} + + void convert(const char * p_source,t_size p_source_size = ~0) { + t_size size = estimate_win1252_to_utf8(p_source,p_source_size); + m_buffer.set_size(size); + convert_win1252_to_utf8(m_buffer.get_ptr_var(),size,p_source,p_source_size); + } + + operator const char * () const {return get_ptr();} + const char * get_ptr() const {return m_buffer.get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + + private: + char_buffer_t m_buffer; + }; + typedef string_utf8_from_win1252_t<> string_utf8_from_win1252; + + + template class t_alloc = pfc::alloc_standard> + class string_win1252_from_utf8_t { + public: + string_win1252_from_utf8_t() {} + string_win1252_from_utf8_t(const char * p_source,t_size p_source_size = ~0) {convert(p_source,p_source_size);} + + void convert(const char * p_source,t_size p_source_size = ~0) { + t_size size = estimate_utf8_to_win1252(p_source,p_source_size); + m_buffer.set_size(size); + convert_utf8_to_win1252(m_buffer.get_ptr_var(),size,p_source,p_source_size); + } + + operator const char * () const {return get_ptr();} + const char * get_ptr() const {return m_buffer.get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + + private: + char_buffer_t m_buffer; + }; + typedef string_win1252_from_utf8_t<> string_win1252_from_utf8; + + class string_ascii_from_utf8 { + public: + string_ascii_from_utf8() {} + string_ascii_from_utf8( const char * p_source, t_size p_source_size = ~0) { convert(p_source, p_source_size); } + + void convert( const char * p_source, t_size p_source_size = ~0) { + t_size size = estimate_utf8_to_ascii(p_source, p_source_size); + m_buffer.set_size(size); + convert_utf8_to_ascii(m_buffer.get_ptr_var(), size, p_source, p_source_size); + } + + operator const char * () const {return get_ptr();} + const char * get_ptr() const {return m_buffer.get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + + private: + char_buffer_t m_buffer; + }; + + } +#ifdef _WINDOWS + namespace stringcvt { + + enum { + codepage_system = CP_ACP, + codepage_ascii = 20127, + codepage_iso_8859_1 = 28591, + }; + + + + //! Converts string from specified codepage to wide character. + //! @param p_out Output buffer, receives converted string, with null terminator. + //! @param p_codepage Codepage ID of source string. + //! @param p_source String to convert. + //! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier. + //! @param p_out_size Size of output buffer, in characters. If converted string is too long, it will be truncated. Null terminator is always written, unless p_out_size is zero. + //! @returns Number of characters written, not counting null terminator. + t_size convert_codepage_to_wide(unsigned p_codepage,wchar_t * p_out,t_size p_out_size,const char * p_source,t_size p_source_size); + + //! Estimates buffer size required to convert specified string from specified codepage to wide character. + //! @param p_codepage Codepage ID of source string. + //! @param p_source String to be converted. + //! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier. + //! @returns Number of characters to allocate, including space for null terminator. + t_size estimate_codepage_to_wide(unsigned p_codepage,const char * p_source,t_size p_source_size); + + //! Converts string from wide character to specified codepage. + //! @param p_codepage Codepage ID of source string. + //! @param p_out Output buffer, receives converted string, with null terminator. + //! @param p_out_size Size of output buffer, in characters. If converted string is too long, it will be truncated. Null terminator is always written, unless p_out_size is zero. + //! @param p_source String to convert. + //! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier. + //! @returns Number of characters written, not counting null terminator. + t_size convert_wide_to_codepage(unsigned p_codepage,char * p_out,t_size p_out_size,const wchar_t * p_source,t_size p_source_size); + + //! Estimates buffer size required to convert specified wide character string to specified codepage. + //! @param p_codepage Codepage ID of source string. + //! @param p_source String to be converted. + //! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier. + //! @returns Number of characters to allocate, including space for null terminator. + t_size estimate_wide_to_codepage(unsigned p_codepage,const wchar_t * p_source,t_size p_source_size); + + + //! Converts string from system codepage to wide character. + //! @param p_out Output buffer, receives converted string, with null terminator. + //! @param p_source String to convert. + //! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier. + //! @param p_out_size Size of output buffer, in characters. If converted string is too long, it will be truncated. Null terminator is always written, unless p_out_size is zero. + //! @returns Number of characters written, not counting null terminator. + inline t_size convert_ansi_to_wide(wchar_t * p_out,t_size p_out_size,const char * p_source,t_size p_source_size) { + return convert_codepage_to_wide(codepage_system,p_out,p_out_size,p_source,p_source_size); + } + + //! Estimates buffer size required to convert specified system codepage string to wide character. + //! @param p_source String to be converted. + //! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier. + //! @returns Number of characters to allocate, including space for null terminator. + inline t_size estimate_ansi_to_wide(const char * p_source,t_size p_source_size) { + return estimate_codepage_to_wide(codepage_system,p_source,p_source_size); + } + + //! Converts string from wide character to system codepage. + //! @param p_out Output buffer, receives converted string, with null terminator. + //! @param p_out_size Size of output buffer, in characters. If converted string is too long, it will be truncated. Null terminator is always written, unless p_out_size is zero. + //! @param p_source String to convert. + //! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier. + //! @returns Number of characters written, not counting null terminator. + inline t_size convert_wide_to_ansi(char * p_out,t_size p_out_size,const wchar_t * p_source,t_size p_source_size) { + return convert_wide_to_codepage(codepage_system,p_out,p_out_size,p_source,p_source_size); + } + + //! Estimates buffer size required to convert specified wide character string to system codepage. + //! @param p_source String to be converted. + //! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier. + //! @returns Number of characters to allocate, including space for null terminator. + inline t_size estimate_wide_to_ansi(const wchar_t * p_source,t_size p_source_size) { + return estimate_wide_to_codepage(codepage_system,p_source,p_source_size); + } + + + template class t_alloc = pfc::alloc_standard> + class string_wide_from_codepage_t { + public: + string_wide_from_codepage_t() {} + string_wide_from_codepage_t(const string_wide_from_codepage_t & p_source) : m_buffer(p_source.m_buffer) {} + string_wide_from_codepage_t(unsigned p_codepage,const char * p_source,t_size p_source_size = ~0) {convert(p_codepage,p_source,p_source_size);} + + void convert(unsigned p_codepage,const char * p_source,t_size p_source_size = ~0) { + t_size size = estimate_codepage_to_wide(p_codepage,p_source,p_source_size); + m_buffer.set_size(size); + convert_codepage_to_wide(p_codepage, m_buffer.get_ptr_var(),size,p_source,p_source_size); + } + + operator const wchar_t * () const {return get_ptr();} + const wchar_t * get_ptr() const {return m_buffer.get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + + private: + char_buffer_t m_buffer; + }; + typedef string_wide_from_codepage_t<> string_wide_from_codepage; + + + template class t_alloc = pfc::alloc_standard> + class string_codepage_from_wide_t { + public: + string_codepage_from_wide_t() {} + string_codepage_from_wide_t(const string_codepage_from_wide_t & p_source) : m_buffer(p_source.m_buffer) {} + string_codepage_from_wide_t(unsigned p_codepage,const wchar_t * p_source,t_size p_source_size = ~0) {convert(p_codepage,p_source,p_source_size);} + + void convert(unsigned p_codepage,const wchar_t * p_source,t_size p_source_size = ~0) { + t_size size = estimate_wide_to_codepage(p_codepage,p_source,p_source_size); + m_buffer.set_size(size); + convert_wide_to_codepage(p_codepage, m_buffer.get_ptr_var(),size,p_source,p_source_size); + } + + operator const char * () const {return get_ptr();} + const char * get_ptr() const {return m_buffer.get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + + private: + char_buffer_t m_buffer; + }; + typedef string_codepage_from_wide_t<> string_codepage_from_wide; + + class string_codepage_from_utf8 { + public: + string_codepage_from_utf8() {} + string_codepage_from_utf8(const string_codepage_from_utf8 & p_source) : m_buffer(p_source.m_buffer) {} + string_codepage_from_utf8(unsigned p_codepage,const char * p_source,t_size p_source_size = ~0) {convert(p_codepage,p_source,p_source_size);} + + void convert(unsigned p_codepage,const char * p_source,t_size p_source_size = ~0) { + string_wide_from_utf8 temp; + temp.convert(p_source,p_source_size); + t_size size = estimate_wide_to_codepage(p_codepage,temp,~0); + m_buffer.set_size(size); + convert_wide_to_codepage(p_codepage,m_buffer.get_ptr_var(),size,temp,~0); + } + + operator const char * () const {return get_ptr();} + const char * get_ptr() const {return m_buffer.get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + + private: + char_buffer_t m_buffer; + }; + + class string_utf8_from_codepage { + public: + string_utf8_from_codepage() {} + string_utf8_from_codepage(const string_utf8_from_codepage & p_source) : m_buffer(p_source.m_buffer) {} + string_utf8_from_codepage(unsigned p_codepage,const char * p_source,t_size p_source_size = ~0) {convert(p_codepage,p_source,p_source_size);} + + void convert(unsigned p_codepage,const char * p_source,t_size p_source_size = ~0) { + string_wide_from_codepage temp; + temp.convert(p_codepage,p_source,p_source_size); + t_size size = estimate_wide_to_utf8(temp,~0); + m_buffer.set_size(size); + convert_wide_to_utf8( m_buffer.get_ptr_var(),size,temp,~0); + } + + operator const char * () const {return get_ptr();} + const char * get_ptr() const {return m_buffer.get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + + private: + char_buffer_t m_buffer; + }; + + + class string_utf8_from_ansi { + public: + string_utf8_from_ansi() {} + string_utf8_from_ansi(const string_utf8_from_ansi & p_source) : m_buffer(p_source.m_buffer) {} + string_utf8_from_ansi(const char * p_source,t_size p_source_size = ~0) : m_buffer(codepage_system,p_source,p_source_size) {} + operator const char * () const {return get_ptr();} + const char * get_ptr() const {return m_buffer.get_ptr();} + const char * toString() const {return get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + void convert(const char * p_source,t_size p_source_size = ~0) {m_buffer.convert(codepage_system,p_source,p_source_size);} + + private: + string_utf8_from_codepage m_buffer; + }; + + class string_ansi_from_utf8 { + public: + string_ansi_from_utf8() {} + string_ansi_from_utf8(const string_ansi_from_utf8 & p_source) : m_buffer(p_source.m_buffer) {} + string_ansi_from_utf8(const char * p_source,t_size p_source_size = ~0) : m_buffer(codepage_system,p_source,p_source_size) {} + operator const char * () const {return get_ptr();} + const char * get_ptr() const {return m_buffer.get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + + void convert(const char * p_source,t_size p_source_size = ~0) {m_buffer.convert(codepage_system,p_source,p_source_size);} + + private: + string_codepage_from_utf8 m_buffer; + }; + + class string_wide_from_ansi { + public: + string_wide_from_ansi() {} + string_wide_from_ansi(const string_wide_from_ansi & p_source) : m_buffer(p_source.m_buffer) {} + string_wide_from_ansi(const char * p_source,t_size p_source_size = ~0) : m_buffer(codepage_system,p_source,p_source_size) {} + operator const wchar_t * () const {return get_ptr();} + const wchar_t * get_ptr() const {return m_buffer.get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + + void convert(const char * p_source,t_size p_source_size = ~0) {m_buffer.convert(codepage_system,p_source,p_source_size);} + + private: + string_wide_from_codepage m_buffer; + }; + + class string_ansi_from_wide { + public: + string_ansi_from_wide() {} + string_ansi_from_wide(const string_ansi_from_wide & p_source) : m_buffer(p_source.m_buffer) {} + string_ansi_from_wide(const wchar_t * p_source,t_size p_source_size = ~0) : m_buffer(codepage_system,p_source,p_source_size) {} + operator const char * () const {return get_ptr();} + const char * get_ptr() const {return m_buffer.get_ptr();} + bool is_empty() const {return string_is_empty_t(get_ptr());} + t_size length() const {return strlen_t(get_ptr());} + + void convert(const wchar_t * p_source,t_size p_source_size = ~0) {m_buffer.convert(codepage_system,p_source,p_source_size);} + + private: + string_codepage_from_wide m_buffer; + }; + +#ifdef UNICODE + typedef string_wide_from_utf8 string_os_from_utf8; + typedef string_utf8_from_wide string_utf8_from_os; + typedef string_wide_from_utf8_fast string_os_from_utf8_fast; +#else + typedef string_ansi_from_utf8 string_os_from_utf8; + typedef string_utf8_from_ansi string_utf8_from_os; + typedef string_ansi_from_utf8 string_os_from_utf8_fast; +#endif + + class string_utf8_from_os_ex { + public: + template string_utf8_from_os_ex(const t_source * source, t_size sourceLen = ~0) { + convert(source,sourceLen); + } + + void convert(const char * source, t_size sourceLen = ~0) { + m_buffer = string_utf8_from_ansi(source,sourceLen); + } + void convert(const wchar_t * source, t_size sourceLen = ~0) { + m_buffer = string_utf8_from_wide(source,sourceLen); + } + + operator const char * () const {return get_ptr();} + const char * get_ptr() const {return m_buffer.get_ptr();} + bool is_empty() const {return m_buffer.is_empty();} + t_size length() const {return m_buffer.length();} + const char * toString() const {return get_ptr();} + private: + string8 m_buffer; + }; + } + +#else + namespace stringcvt { + typedef string_win1252_from_wide string_ansi_from_wide; + typedef string_wide_from_win1252 string_wide_from_ansi; + typedef string_win1252_from_utf8 string_ansi_from_utf8; + typedef string_utf8_from_win1252 string_utf8_from_ansi; + } +#endif +}; + +inline pfc::string_base & operator<<(pfc::string_base & p_fmt, const wchar_t * p_str) { p_fmt.add_string(pfc::stringcvt::string_utf8_from_wide(p_str) ); return p_fmt; } diff --git a/SDK/pfc/string_list.h b/SDK/pfc/string_list.h new file mode 100644 index 0000000..295ce3f --- /dev/null +++ b/SDK/pfc/string_list.h @@ -0,0 +1,44 @@ +#ifndef _PFC_STRING_LIST_H_ +#define _PFC_STRING_LIST_H_ + +namespace pfc { + + typedef list_base_const_t string_list_const; + + class string_list_impl : public string_list_const + { + public: + t_size get_count() const {return m_data.get_size();} + void get_item_ex(const char* & p_out, t_size n) const {p_out = m_data[n];} + + const char * operator[] (t_size n) const {return m_data[n];} + void add_item(const char * p_string) {pfc::append_t(m_data, p_string);} + + template void add_items(const t_what & p_source) {_append(p_source);} + + void remove_all() {m_data.set_size(0);} + + string_list_impl() {} + template string_list_impl(const t_what & p_source) {_copy(p_source);} + template string_list_impl & operator=(const t_what & p_source) {_copy(p_source); return *this;} + template string_list_impl & operator|=(const string_list_impl & p_source) {_append(p_source); return *this;} + template string_list_impl & operator+=(const t_what & p_source) {pfc::append_t(m_data, p_source); return *this;} + + private: + template void _append(const t_what & p_source) { + const t_size toadd = p_source.get_size(), base = m_data.get_size(); + m_data.set_size(base+toadd); + for(t_size n=0;n void _copy(const t_what & p_source) { + const t_size newcount = p_source.get_size(); + m_data.set_size(newcount); + for(t_size n=0;n m_data; + }; +} + +#endif //_PFC_STRING_LIST_H_ diff --git a/SDK/pfc/syncd_storage.h b/SDK/pfc/syncd_storage.h new file mode 100644 index 0000000..c98d011 --- /dev/null +++ b/SDK/pfc/syncd_storage.h @@ -0,0 +1,93 @@ +namespace pfc { +// Read/write lock guarded object store for safe concurrent access +template +class syncd_storage { +private: + typedef syncd_storage t_self; +public: + syncd_storage() {} + template + syncd_storage(const t_source & p_source) : m_object(p_source) {} + template + void set(t_source const & p_in) { + inWriteSync(m_sync); + m_object = p_in; + } + template + void get(t_destination & p_out) const { + inReadSync(m_sync); + p_out = m_object; + } + t_object get() const { + inReadSync(m_sync); + return m_object; + } + template + const t_self & operator=(t_source const & p_source) {set(p_source); return *this;} +private: + mutable ::pfc::readWriteLock m_sync; + t_object m_object; +}; + +// Read/write lock guarded object store for safe concurrent access +// With 'has changed since last read' flag +template +class syncd_storage_flagged { +private: + typedef syncd_storage_flagged t_self; +public: + syncd_storage_flagged() : m_changed_flag(false) {} + template + syncd_storage_flagged(const t_source & p_source, bool initChanged = false) : m_changed_flag(initChanged), m_object(p_source) {} + void set_changed(bool p_flag = true) { + inWriteSync(m_sync); + m_changed_flag = p_flag; + } + template + void set(t_source const & p_in) { + inWriteSync(m_sync); + m_object = p_in; + m_changed_flag = true; + } + bool has_changed() const { + inReadSync(m_sync); + return m_changed_flag; + } + t_object peek() const {inReadSync(m_sync); return m_object;} + template + bool get_if_changed(t_destination & p_out) { + inReadSync(m_sync); + if (m_changed_flag) { + p_out = m_object; + m_changed_flag = false; + return true; + } else { + return false; + } + } + t_object get() { + inReadSync(m_sync); + m_changed_flag = false; + return m_object; + } + t_object get( bool & bHasChanged ) { + inReadSync(m_sync); + bHasChanged = m_changed_flag; + m_changed_flag = false; + return m_object; + } + template + void get(t_destination & p_out) { + inReadSync(m_sync); + p_out = m_object; + m_changed_flag = false; + } + template + const t_self & operator=(t_source const & p_source) {set(p_source); return *this;} +private: + mutable volatile bool m_changed_flag; + mutable ::pfc::readWriteLock m_sync; + t_object m_object; +}; + +} \ No newline at end of file diff --git a/SDK/pfc/synchro_nix.cpp b/SDK/pfc/synchro_nix.cpp new file mode 100644 index 0000000..a667eb1 --- /dev/null +++ b/SDK/pfc/synchro_nix.cpp @@ -0,0 +1,33 @@ +#include "pfc.h" + +#ifndef _WIN32 + +namespace pfc { + + void mutexBase::create( const pthread_mutexattr_t * attr ) { + if (pthread_mutex_init( &obj, attr) != 0) { + throw exception_bug_check(); + } + } + void mutexBase::destroy() { + pthread_mutex_destroy( &obj ); + } + void mutexBase::createRecur() { + mutexAttr a; a.setRecursive(); create(&a.attr); + } + void mutexBase::create( const mutexAttr & a ) { + create( & a.attr ); + } + + void readWriteLockBase::create( const pthread_rwlockattr_t * attr ) { + if (pthread_rwlock_init( &obj, attr) != 0) { + throw exception_bug_check(); + } + } + void readWriteLockBase::create( const readWriteLockAttr & a) { + create(&a.attr); + } + +} + +#endif // _WIN32 diff --git a/SDK/pfc/synchro_nix.h b/SDK/pfc/synchro_nix.h new file mode 100644 index 0000000..45a4360 --- /dev/null +++ b/SDK/pfc/synchro_nix.h @@ -0,0 +1,146 @@ +#include + +namespace pfc { + class mutexAttr { + public: + mutexAttr() {pthread_mutexattr_init(&attr);} + ~mutexAttr() {pthread_mutexattr_destroy(&attr);} + void setType(int type) {pthread_mutexattr_settype(&attr, type);} + int getType() const {int rv = 0; pthread_mutexattr_gettype(&attr, &rv); return rv; } + void setRecursive() {setType(PTHREAD_MUTEX_RECURSIVE);} + bool isRecursive() {return getType() == PTHREAD_MUTEX_RECURSIVE;} + void setProcessShared() {pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);} + operator const pthread_mutexattr_t & () const {return attr;} + operator pthread_mutexattr_t & () {return attr;} + pthread_mutexattr_t attr; + private: + mutexAttr(const mutexAttr&); void operator=(const mutexAttr&); + }; + + class mutexBase { + public: + void lock() throw() {pthread_mutex_lock(&obj);} + void unlock() throw() {pthread_mutex_unlock(&obj);} + + void enter() throw() {lock();} + void leave() throw() {unlock();} + + void create( const pthread_mutexattr_t * attr ); + void create( const mutexAttr & ); + void createRecur(); + void destroy(); + protected: + mutexBase() {} + ~mutexBase() {} + private: + pthread_mutex_t obj; + + void operator=( const mutexBase & ); + mutexBase( const mutexBase & ); + }; + + + + class mutex : public mutexBase { + public: + mutex() {create(NULL);} + ~mutex() {destroy();} + }; + + class mutexRecur : public mutexBase { + public: + mutexRecur() {createRecur();} + ~mutexRecur() {destroy();} + }; + + + class mutexRecurStatic : public mutexBase { + public: + mutexRecurStatic() {createRecur();} + }; + + + class mutexScope { + public: + mutexScope( mutexBase * m ) throw() : m_mutex(m) { m_mutex->enter(); } + mutexScope( mutexBase & m ) throw() : m_mutex(&m) { m_mutex->enter(); } + ~mutexScope( ) throw() {m_mutex->leave();} + private: + void operator=( const mutexScope & ); mutexScope( const mutexScope & ); + mutexBase * m_mutex; + }; + + + class readWriteLockAttr { + public: + readWriteLockAttr() {pthread_rwlockattr_init( & attr ); } + ~readWriteLockAttr() {pthread_rwlockattr_destroy( & attr ) ;} + + void setProcessShared( bool val = true ) { + pthread_rwlockattr_setpshared( &attr, val ? PTHREAD_PROCESS_SHARED : PTHREAD_PROCESS_PRIVATE ); + } + + pthread_rwlockattr_t attr; + + private: + readWriteLockAttr( const readWriteLockAttr &); void operator=(const readWriteLockAttr & ); + }; + + class readWriteLockBase { + public: + void create( const pthread_rwlockattr_t * attr ); + void create( const readWriteLockAttr & ); + void destroy() {pthread_rwlock_destroy( & obj ); } + + void enterRead() {pthread_rwlock_rdlock( &obj ); } + void enterWrite() {pthread_rwlock_wrlock( &obj ); } + void leaveRead() {pthread_rwlock_unlock( &obj ); } + void leaveWrite() {pthread_rwlock_unlock( &obj ); } + protected: + readWriteLockBase() {} + ~readWriteLockBase() {} + private: + pthread_rwlock_t obj; + + void operator=( const readWriteLockBase & ); readWriteLockBase( const readWriteLockBase & ); + }; + + + class readWriteLock : public readWriteLockBase { + public: + readWriteLock() {create(NULL);} + ~readWriteLock() {destroy();} + }; + + + class _readWriteLock_scope_read { + public: + _readWriteLock_scope_read( readWriteLockBase & lock ) : m_lock( lock ) { m_lock.enterRead(); } + ~_readWriteLock_scope_read() {m_lock.leaveRead();} + private: + _readWriteLock_scope_read( const _readWriteLock_scope_read &); + void operator=( const _readWriteLock_scope_read &); + readWriteLockBase & m_lock; + }; + class _readWriteLock_scope_write { + public: + _readWriteLock_scope_write( readWriteLockBase & lock ) : m_lock( lock ) { m_lock.enterWrite(); } + ~_readWriteLock_scope_write() {m_lock.leaveWrite();} + private: + _readWriteLock_scope_write( const _readWriteLock_scope_write &); + void operator=( const _readWriteLock_scope_write &); + readWriteLockBase & m_lock; + }; +} + + + +typedef pfc::mutexRecur critical_section; +typedef pfc::mutexRecurStatic critical_section_static; +typedef pfc::mutexScope c_insync; + +#define insync(X) c_insync blah____sync(X) + + +#define inReadSync( X ) ::pfc::_readWriteLock_scope_read _asdf_l_readWriteLock_scope_read( X ) +#define inWriteSync( X ) ::pfc::_readWriteLock_scope_write _asdf_l_readWriteLock_scope_write( X ) diff --git a/SDK/pfc/synchro_win.h b/SDK/pfc/synchro_win.h new file mode 100644 index 0000000..9c864d6 --- /dev/null +++ b/SDK/pfc/synchro_win.h @@ -0,0 +1,134 @@ +class _critical_section_base { +protected: + CRITICAL_SECTION sec; +public: + _critical_section_base() {} + inline void enter() throw() {EnterCriticalSection(&sec);} + inline void leave() throw() {LeaveCriticalSection(&sec);} + inline void create() throw() { +#ifdef PFC_WINDOWS_DESKTOP_APP + InitializeCriticalSection(&sec); +#else + InitializeCriticalSectionEx(&sec,0,0); +#endif + } + inline void destroy() throw() {DeleteCriticalSection(&sec);} +private: + _critical_section_base(const _critical_section_base&); + void operator=(const _critical_section_base&); +}; + +// Static-lifetime critical section, no cleanup - valid until process termination +class critical_section_static : public _critical_section_base { +public: + critical_section_static() {create();} +#if !PFC_LEAK_STATIC_OBJECTS + ~critical_section_static() {destroy();} +#endif +}; + +// Regular critical section, intended for any lifetime scopes +class critical_section : public _critical_section_base { +private: + CRITICAL_SECTION sec; +public: + critical_section() {create();} + ~critical_section() {destroy();} +}; + +class c_insync +{ +private: + _critical_section_base & m_section; +public: + c_insync(_critical_section_base * p_section) throw() : m_section(*p_section) {m_section.enter();} + c_insync(_critical_section_base & p_section) throw() : m_section(p_section) {m_section.enter();} + ~c_insync() throw() {m_section.leave();} +}; + +#define insync(X) c_insync blah____sync(X) + + +namespace pfc { + + +// Read write lock - Vista-and-newer friendly lock that allows concurrent reads from a resource that permits such +// Warning, non-recursion proof +#if _WIN32_WINNT < 0x600 + +// Inefficient fallback implementation for pre Vista OSes +class readWriteLock { +public: + readWriteLock() {} + void enterRead() { + m_obj.enter(); + } + void enterWrite() { + m_obj.enter(); + } + void leaveRead() { + m_obj.leave(); + } + void leaveWrite() { + m_obj.leave(); + } +private: + critical_section m_obj; + + readWriteLock( const readWriteLock & ); + void operator=( const readWriteLock & ); +}; + +#else +class readWriteLock { +public: + readWriteLock() : theLock() { + } + + void enterRead() { + AcquireSRWLockShared( & theLock ); + } + void enterWrite() { + AcquireSRWLockExclusive( & theLock ); + } + void leaveRead() { + ReleaseSRWLockShared( & theLock ); + } + void leaveWrite() { + ReleaseSRWLockExclusive( &theLock ); + } + +private: + readWriteLock(const readWriteLock&); + void operator=(const readWriteLock&); + + SRWLOCK theLock; +}; +#endif + +class _readWriteLock_scope_read { +public: + _readWriteLock_scope_read( readWriteLock & lock ) : m_lock( lock ) { m_lock.enterRead(); } + ~_readWriteLock_scope_read() {m_lock.leaveRead();} +private: + _readWriteLock_scope_read( const _readWriteLock_scope_read &); + void operator=( const _readWriteLock_scope_read &); + readWriteLock & m_lock; +}; +class _readWriteLock_scope_write { +public: + _readWriteLock_scope_write( readWriteLock & lock ) : m_lock( lock ) { m_lock.enterWrite(); } + ~_readWriteLock_scope_write() {m_lock.leaveWrite();} +private: + _readWriteLock_scope_write( const _readWriteLock_scope_write &); + void operator=( const _readWriteLock_scope_write &); + readWriteLock & m_lock; +}; + +#define inReadSync( X ) ::pfc::_readWriteLock_scope_read _asdf_l_readWriteLock_scope_read( X ) +#define inWriteSync( X ) ::pfc::_readWriteLock_scope_write _asdf_l_readWriteLock_scope_write( X ) + +typedef ::critical_section mutex; +typedef ::c_insync mutexScope; + +} diff --git a/SDK/pfc/threads.cpp b/SDK/pfc/threads.cpp new file mode 100644 index 0000000..34e3b89 --- /dev/null +++ b/SDK/pfc/threads.cpp @@ -0,0 +1,165 @@ +#include "pfc.h" + +#ifdef _WIN32 +#include "pp-winapi.h" +#endif + +#ifdef __APPLE__ +#include +#include +#endif + +#ifndef PFC_WINDOWS_DESKTOP_APP +#include +#endif + +namespace pfc { + t_size getOptimalWorkerThreadCount() { +#ifdef PFC_WINDOWS_DESKTOP_APP + DWORD_PTR mask,system; + t_size ret = 0; + GetProcessAffinityMask(GetCurrentProcess(),&mask,&system); + for(t_size n=0;n GetThreadPriority( m_thread ) ) SetThreadPriority( m_thread, ctxPriority ); + + if (WaitForSingleObject(m_thread,INFINITE) != WAIT_OBJECT_0) crash(); + CloseHandle(m_thread); m_thread = INVALID_HANDLE_VALUE; + } + } + bool thread::isActive() const { + return m_thread != INVALID_HANDLE_VALUE; + } + void thread::winStart(int priority, DWORD * outThreadID) { + close(); + HANDLE thread; +#ifdef PFC_WINDOWS_DESKTOP_APP + thread = (HANDLE)_beginthreadex(NULL, 0, g_entry, reinterpret_cast(this), CREATE_SUSPENDED, (unsigned int*)outThreadID); +#else + thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) g_entry, reinterpret_cast(this), CREATE_SUSPENDED, outThreadID); +#endif + if (thread == NULL) throw exception_creation(); + SetThreadPriority(thread, priority); + ResumeThread(thread); + m_thread = thread; + } + void thread::startWithPriority(int priority) { + winStart(priority, NULL); + } + void thread::setPriority(int priority) { + PFC_ASSERT(isActive()); + SetThreadPriority(m_thread, priority); + } + void thread::start() { + startWithPriority(GetThreadPriority(GetCurrentThread())); + } + + unsigned CALLBACK thread::g_entry(void* p_instance) { + reinterpret_cast(p_instance)->entry(); return 0; + } + + int thread::getPriority() { + PFC_ASSERT(isActive()); + return GetThreadPriority( m_thread ); + } + + int thread::currentPriority() { + return GetThreadPriority( GetCurrentThread() ); + } +#else + thread::thread() : m_thread(), m_threadValid() { + } + +#ifndef __APPLE__ // Apple specific entrypoint in obj-c.mm + void * thread::g_entry( void * arg ) { + reinterpret_cast( arg )->entry(); + return NULL; + } +#endif + + void thread::startWithPriority(int priority) { + close(); +#ifdef __APPLE__ + appleStartThreadPrologue(); +#endif + pthread_t thread; + pthread_attr_t attr; + pthread_attr_init(&attr); + + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); + + if (pthread_create(&thread, &attr, g_entry, reinterpret_cast(this)) < 0) throw exception_creation(); + + pthread_attr_destroy(&attr); + m_threadValid = true; + m_thread = thread; + } + + void thread::setPriority(int priority) { + PFC_ASSERT(isActive()); + // not avail + } + int thread::getPriority() { + return 0; // not avail + } + int thread::currentPriority() { + return 0; // not avail + } + + void thread::start() { + startWithPriority(currentPriority()); + } + + void thread::close() { + if (m_threadValid) { + void * rv = NULL; + pthread_join( m_thread, & rv ); m_thread = 0; + m_threadValid = false; + } + } + + bool thread::isActive() const { + return m_threadValid; + } +#endif +} diff --git a/SDK/pfc/threads.h b/SDK/pfc/threads.h new file mode 100644 index 0000000..204c583 --- /dev/null +++ b/SDK/pfc/threads.h @@ -0,0 +1,52 @@ +#ifdef _WIN32 +#include +#else +#include +#endif +namespace pfc { + t_size getOptimalWorkerThreadCount(); + t_size getOptimalWorkerThreadCountEx(t_size taskCountLimit); + + //! IMPORTANT: all classes derived from thread must call waitTillDone() in their destructor, to avoid object destruction during a virtual function call! + class thread { + public: + PFC_DECLARE_EXCEPTION(exception_creation, exception, "Could not create thread"); + thread(); + ~thread() {PFC_ASSERT(!isActive()); waitTillDone();} + void startWithPriority(int priority); + void setPriority(int priority); + int getPriority(); + void start(); + bool isActive() const; + void waitTillDone() {close();} + static int currentPriority(); +#ifdef _WIN32 + void winStart(int priority, DWORD * outThreadID); + HANDLE winThreadHandle() { return m_thread; } +#else + pthread_t posixThreadHandle() { return m_thread; } +#endif + protected: + virtual void threadProc() {PFC_ASSERT(!"Stub thread entry - should not get here");} + private: + void close(); +#ifdef _WIN32 + static unsigned CALLBACK g_entry(void* p_instance); +#else + static void * g_entry( void * arg ); +#endif + void entry(); + +#ifdef _WIN32 + HANDLE m_thread; +#else + pthread_t m_thread; + bool m_threadValid; // there is no invalid pthread_t, so we keep a separate 'valid' flag +#endif + +#ifdef __APPLE__ + static void appleStartThreadPrologue(); +#endif + PFC_CLASS_NOT_COPYABLE_EX(thread) + }; +} diff --git a/SDK/pfc/timers.cpp b/SDK/pfc/timers.cpp new file mode 100644 index 0000000..78b5a75 --- /dev/null +++ b/SDK/pfc/timers.cpp @@ -0,0 +1,76 @@ +#include "pfc.h" + +namespace pfc { + +#ifdef PFC_HAVE_PROFILER + +profiler_static::profiler_static(const char * p_name) +{ + name = p_name; + total_time = 0; + num_called = 0; +} + +profiler_static::~profiler_static() +{ + try { + pfc::string_fixed_t<511> message; + message << "profiler: " << pfc::format_pad_left >(48,' ',name) << " - " << + pfc::format_pad_right >(16,' ',pfc::format_uint(total_time) ) << " cycles"; + + if (num_called > 0) { + message << " (executed " << num_called << " times, " << (total_time / num_called) << " average)"; + } + message << "\n"; + OutputDebugStringA(message); + } catch(...) { + //should never happen + OutputDebugString(_T("unexpected profiler failure\n")); + } +} +#endif + +#ifndef _WIN32 + + void hires_timer::start() { + m_start = nixGetTime(); + } + double hires_timer::query() const { + return nixGetTime() - m_start; + } + double hires_timer::query_reset() { + double t = nixGetTime(); + double r = t - m_start; + m_start = t; + return r; + } + pfc::string8 hires_timer::queryString(unsigned precision) { + return format_time_ex( query(), precision ).get_ptr(); + } +#endif + + + uint64_t fileTimeWtoU(uint64_t ft) { + return (ft - 116444736000000000 + /*rounding*/10000000/2) / 10000000; + } + uint64_t fileTimeUtoW(uint64_t ft) { + return (ft * 10000000) + 116444736000000000; + } +#ifndef _WIN32 + uint64_t fileTimeUtoW(const timespec & ts) { + uint64_t ft = (uint64_t)ts.tv_sec * 10000000 + (uint64_t)ts.tv_nsec / 100; + return ft + 116444736000000000; + } +#endif + + uint64_t fileTimeNow() { +#ifdef _WIN32 + uint64_t ret; + GetSystemTimeAsFileTime((FILETIME*)&ret); + return ret; +#else + return fileTimeUtoW(time(NULL)); +#endif + } + +} diff --git a/SDK/pfc/timers.h b/SDK/pfc/timers.h new file mode 100644 index 0000000..088c54d --- /dev/null +++ b/SDK/pfc/timers.h @@ -0,0 +1,166 @@ +#ifndef _PFC_PROFILER_H_ +#define _PFC_PROFILER_H_ + +#if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) + +#define PFC_HAVE_PROFILER + +#include +namespace pfc { + class profiler_static { + public: + profiler_static(const char * p_name); + ~profiler_static(); + void add_time(t_int64 delta) { total_time += delta;num_called++; } + private: + const char * name; + t_uint64 total_time, num_called; + }; + + class profiler_local { + public: + profiler_local(profiler_static * p_owner) { + owner = p_owner; + start = __rdtsc(); + } + ~profiler_local() { + t_int64 end = __rdtsc(); + owner->add_time(end - start); + } + private: + t_int64 start; + profiler_static * owner; + }; + +} +#define profiler(name) \ + static pfc::profiler_static profiler_static_##name(#name); \ + pfc::profiler_local profiler_local_##name(&profiler_static_##name); + + +#endif + +#ifdef _WIN32 + +namespace pfc { +#if _WIN32_WINNT >= 0x600 +typedef uint64_t tickcount_t; +inline tickcount_t getTickCount() { return GetTickCount64(); } +#else +#define PFC_TICKCOUNT_32BIT +typedef uint32_t tickcount_t; +inline tickcount_t getTickCount() { return GetTickCount(); } +#endif + +class hires_timer { +public: + hires_timer() : m_start() {} + void start() { + m_start = g_query(); + } + double query() const { + return _query( g_query() ); + } + double query_reset() { + t_uint64 current = g_query(); + double ret = _query(current); + m_start = current; + return ret; + } + pfc::string8 queryString(unsigned precision = 6) { + return pfc::format_time_ex( query(), precision ).get_ptr(); + } +private: + double _query(t_uint64 p_val) const { + return (double)( p_val - m_start ) / (double) g_query_freq(); + } + static t_uint64 g_query() { + LARGE_INTEGER val; + if (!QueryPerformanceCounter(&val)) throw pfc::exception_not_implemented(); + return val.QuadPart; + } + static t_uint64 g_query_freq() { + LARGE_INTEGER val; + if (!QueryPerformanceFrequency(&val)) throw pfc::exception_not_implemented(); + return val.QuadPart; + } + t_uint64 m_start; +}; + +class lores_timer { +public: + lores_timer() : m_start() {} + void start() { + _start(getTickCount()); + } + + double query() const { + return _query(getTickCount()); + } + double query_reset() { + tickcount_t time = getTickCount(); + double ret = _query(time); + _start(time); + return ret; + } + pfc::string8 queryString(unsigned precision = 3) { + return pfc::format_time_ex( query(), precision ).get_ptr(); + } +private: + void _start(tickcount_t p_time) { +#ifdef PFC_TICKCOUNT_32BIT + m_last_seen = p_time; +#endif + m_start = p_time; + } + double _query(tickcount_t p_time) const { +#ifdef PFC_TICKCOUNT_32BIT + t_uint64 time = p_time; + if (time < (m_last_seen & 0xFFFFFFFF)) time += 0x100000000; + m_last_seen = (m_last_seen & 0xFFFFFFFF00000000) + time; + return (double)(m_last_seen - m_start) / 1000.0; +#else + return (double)(p_time - m_start) / 1000.0; +#endif + } + t_uint64 m_start; +#ifdef PFC_TICKCOUNT_32BIT + mutable t_uint64 m_last_seen; +#endif +}; +} +#else // not _WIN32 + +namespace pfc { + +class hires_timer { +public: + hires_timer() : m_start() {} + void start(); + double query() const; + double query_reset(); + pfc::string8 queryString(unsigned precision = 3); +private: + double m_start; +}; + +typedef hires_timer lores_timer; + +} + +#endif // _WIN32 + +#ifndef _WIN32 +struct timespec; +#endif + +namespace pfc { + uint64_t fileTimeWtoU(uint64_t ft); + uint64_t fileTimeUtoW(uint64_t ft); +#ifndef _WIN32 + uint64_t fileTimeUtoW( timespec const & ts ); +#endif + uint64_t fileTimeNow(); +} + +#endif diff --git a/SDK/pfc/traits.h b/SDK/pfc/traits.h new file mode 100644 index 0000000..243e6ee --- /dev/null +++ b/SDK/pfc/traits.h @@ -0,0 +1,83 @@ +namespace pfc { + + class traits_default { + public: + enum { + realloc_safe = false, + needs_destructor = true, + needs_constructor = true, + constructor_may_fail = true + }; + }; + + class traits_default_movable { + public: + enum { + realloc_safe = true, + needs_destructor = true, + needs_constructor = true, + constructor_may_fail = true + }; + }; + + class traits_rawobject : public traits_default { + public: + enum { + realloc_safe = true, + needs_destructor = false, + needs_constructor = false, + constructor_may_fail = false + }; + }; + + class traits_vtable { + public: + enum { + realloc_safe = true, + needs_destructor = true, + needs_constructor = true, + constructor_may_fail = false + }; + }; + + template class traits_t : public traits_default {}; + + template + class combine_traits { + public: + enum { + realloc_safe = (traits1::realloc_safe && traits2::realloc_safe), + needs_destructor = (traits1::needs_destructor || traits2::needs_destructor), + needs_constructor = (traits1::needs_constructor || traits2::needs_constructor), + constructor_may_fail = (traits1::constructor_may_fail || traits2::constructor_may_fail), + }; + }; + + template + class traits_combined : public combine_traits,traits_t > {}; + + template class traits_t : public traits_rawobject {}; + + template<> class traits_t : public traits_rawobject {}; + template<> class traits_t : public traits_rawobject {}; + template<> class traits_t : public traits_rawobject {}; + template<> class traits_t : public traits_rawobject {}; + template<> class traits_t : public traits_rawobject {}; + template<> class traits_t : public traits_rawobject {}; + template<> class traits_t : public traits_rawobject {}; + template<> class traits_t : public traits_rawobject {}; + template<> class traits_t : public traits_rawobject {}; + template<> class traits_t : public traits_rawobject {}; + template<> class traits_t : public traits_rawobject {}; + template<> class traits_t : public traits_rawobject {}; + template<> class traits_t : public traits_rawobject {}; + + template<> class traits_t : public traits_rawobject {}; + template<> class traits_t : public traits_rawobject {}; + + template<> class traits_t : public traits_rawobject {}; + + template + class traits_t : public traits_t {}; + +} diff --git a/SDK/pfc/utf8.cpp b/SDK/pfc/utf8.cpp new file mode 100644 index 0000000..e745576 --- /dev/null +++ b/SDK/pfc/utf8.cpp @@ -0,0 +1,346 @@ +#include "pfc.h" + +namespace pfc { +//utf8 stuff + +static const t_uint8 mask_tab[6]={0x80,0xE0,0xF0,0xF8,0xFC,0xFE}; + +static const t_uint8 val_tab[6]={0,0xC0,0xE0,0xF0,0xF8,0xFC}; + +t_size utf8_char_len_from_header(char p_c) throw() +{ + t_size cnt = 0; + for(;;) + { + if ((p_c & mask_tab[cnt])==val_tab[cnt]) break; + if (++cnt>=6) return 0; + } + + return cnt + 1; + +} +t_size utf8_decode_char(const char *p_utf8,unsigned & wide) throw() { + const t_uint8 * utf8 = (const t_uint8*)p_utf8; + const t_size max = 6; + + if (utf8[0]<0x80) { + wide = utf8[0]; + return utf8[0]>0 ? 1 : 0; + } + wide = 0; + + unsigned res=0; + unsigned n; + unsigned cnt=0; + for(;;) + { + if ((*utf8&mask_tab[cnt])==val_tab[cnt]) break; + if (++cnt>=max) return 0; + } + cnt++; + + if (cnt==2 && !(*utf8&0x1E)) return 0; + + if (cnt==1) + res=*utf8; + else + res=(0xFF>>(cnt+1))&*utf8; + + for (n=1;n> (7 - cnt))) + return 0; + + res=(res<<6)|(utf8[n]&0x3F); + } + + wide = res; + + return cnt; +} + +t_size utf8_decode_char(const char *p_utf8,unsigned & wide,t_size max) throw() +{ + const t_uint8 * utf8 = (const t_uint8*)p_utf8; + + if (max==0) { + wide = 0; + return 0; + } + + if (utf8[0]<0x80) { + wide = utf8[0]; + return utf8[0]>0 ? 1 : 0; + } + if (max>6) max = 6; + wide = 0; + + unsigned res=0; + unsigned n; + unsigned cnt=0; + for(;;) + { + if ((*utf8&mask_tab[cnt])==val_tab[cnt]) break; + if (++cnt>=max) return 0; + } + cnt++; + + if (cnt==2 && !(*utf8&0x1E)) return 0; + + if (cnt==1) + res=*utf8; + else + res=(0xFF>>(cnt+1))&*utf8; + + for (n=1;n> (7 - cnt))) + return 0; + + res=(res<<6)|(utf8[n]&0x3F); + } + + wide = res; + + return cnt; +} + + +t_size utf8_encode_char(unsigned wide,char * target) throw() +{ + t_size count; + + if (wide < 0x80) + count = 1; + else if (wide < 0x800) + count = 2; + else if (wide < 0x10000) + count = 3; + else if (wide < 0x200000) + count = 4; + else if (wide < 0x4000000) + count = 5; + else if (wide <= 0x7FFFFFFF) + count = 6; + else + return 0; + //if (count>max) return 0; + + if (target == 0) + return count; + + switch (count) + { + case 6: + target[5] = 0x80 | (wide & 0x3F); + wide = wide >> 6; + wide |= 0x4000000; + case 5: + target[4] = 0x80 | (wide & 0x3F); + wide = wide >> 6; + wide |= 0x200000; + case 4: + target[3] = 0x80 | (wide & 0x3F); + wide = wide >> 6; + wide |= 0x10000; + case 3: + target[2] = 0x80 | (wide & 0x3F); + wide = wide >> 6; + wide |= 0x800; + case 2: + target[1] = 0x80 | (wide & 0x3F); + wide = wide >> 6; + wide |= 0xC0; + case 1: + target[0] = wide; + } + + return count; +} + +t_size utf16_encode_char(unsigned cur_wchar,char16_t * out) throw() +{ + if (cur_wchar < 0x10000) { + *out = (char16_t) cur_wchar; return 1; + } else if (cur_wchar < (1 << 20)) { + unsigned c = cur_wchar - 0x10000; + //MSDN: + //The first (high) surrogate is a 16-bit code value in the range U+D800 to U+DBFF. The second (low) surrogate is a 16-bit code value in the range U+DC00 to U+DFFF. Using surrogates, Unicode can support over one million characters. For more details about surrogates, refer to The Unicode Standard, version 2.0. + out[0] = (char16_t)(0xD800 | (0x3FF & (c>>10)) ); + out[1] = (char16_t)(0xDC00 | (0x3FF & c) ) ; + return 2; + } else { + *out = '?'; return 1; + } +} + +t_size utf16_decode_char(const char16_t * p_source,unsigned * p_out,t_size p_source_length) throw() { + if (p_source_length == 0) {*p_out = 0; return 0; } + else if (p_source_length == 1) { + *p_out = p_source[0]; + return 1; + } else { + t_size retval = 0; + unsigned decoded = p_source[0]; + if (decoded != 0) + { + retval = 1; + if ((decoded & 0xFC00) == 0xD800) + { + unsigned low = p_source[1]; + if ((low & 0xFC00) == 0xDC00) + { + decoded = 0x10000 + ( ((decoded & 0x3FF) << 10) | (low & 0x3FF) ); + retval = 2; + } + } + } + *p_out = decoded; + return retval; + } +} +#ifdef _MSC_VER + t_size utf16_decode_char(const wchar_t * p_source,unsigned * p_out,t_size p_source_length) throw() { + PFC_STATIC_ASSERT( sizeof(wchar_t) == sizeof(char16_t) ); + return wide_decode_char( p_source, p_out, p_source_length ); + } + t_size utf16_encode_char(unsigned c,wchar_t * out) throw() { + PFC_STATIC_ASSERT( sizeof(wchar_t) == sizeof(char16_t) ); + return wide_encode_char( c, out ); + } +#endif + + t_size wide_decode_char(const wchar_t * p_source,unsigned * p_out,t_size p_source_length) throw() { + PFC_STATIC_ASSERT( sizeof( wchar_t ) == sizeof( char16_t ) || sizeof( wchar_t ) == sizeof( unsigned ) ); + if (sizeof( wchar_t ) == sizeof( char16_t ) ) { + return utf16_decode_char( reinterpret_cast< const char16_t *>(p_source), p_out, p_source_length ); + } else { + if (p_source_length == 0) { * p_out = 0; return 0; } + * p_out = p_source [ 0 ]; + return 1; + } + } + t_size wide_encode_char(unsigned c,wchar_t * out) throw() { + PFC_STATIC_ASSERT( sizeof( wchar_t ) == sizeof( char16_t ) || sizeof( wchar_t ) == sizeof( unsigned ) ); + if (sizeof( wchar_t ) == sizeof( char16_t ) ) { + return utf16_encode_char( c, reinterpret_cast< char16_t * >(out) ); + } else { + * out = (wchar_t) c; + return 1; + } + } + + +unsigned utf8_get_char(const char * src) +{ + unsigned rv = 0; + utf8_decode_char(src,rv); + return rv; +} + + +t_size utf8_char_len(const char * s,t_size max) throw() +{ + unsigned dummy; + return utf8_decode_char(s,dummy,max); +} + +t_size skip_utf8_chars(const char * ptr,t_size count) throw() +{ + t_size num = 0; + for(;count && ptr[num];count--) + { + t_size d = utf8_char_len(ptr+num); + if (d<=0) break; + num+=d; + } + return num; +} + +bool is_valid_utf8(const char * param,t_size max) { + t_size walk = 0; + while(walk < max && param[walk] != 0) { + t_size d; + unsigned dummy; + d = utf8_decode_char(param + walk,dummy,max - walk); + if (d==0) return false; + walk += d; + if (walk > max) { + PFC_ASSERT(0);//should not be triggerable + return false; + } + } + return true; +} + +bool is_lower_ascii(const char * param) +{ + while(*param) + { + if (*param<0) return false; + param++; + } + return true; +} + +static bool check_end_of_string(const char * ptr) +{ + return !*ptr; +} + +unsigned strcpy_utf8_truncate(const char * src,char * out,unsigned maxbytes) +{ + unsigned rv = 0 , ptr = 0; + if (maxbytes>0) + { + maxbytes--;//for null + while(!check_end_of_string(src) && maxbytes>0) + { + t_size delta = utf8_char_len(src); + if (delta>maxbytes || delta==0) break; + do + { + out[ptr++] = *(src++); + } while(--delta); + rv = ptr; + } + out[rv]=0; + } + return rv; +} + +t_size strlen_utf8(const char * p,t_size num) throw() +{ + unsigned w; + t_size d; + t_size ret = 0; + for(;num;) + { + d = utf8_decode_char(p,w); + if (w==0 || d<=0) break; + ret++; + p+=d; + num-=d; + } + return ret; +} + +t_size utf8_chars_to_bytes(const char * string,t_size count) throw() +{ + t_size bytes = 0; + while(count) + { + unsigned dummy; + t_size delta = utf8_decode_char(string+bytes,dummy); + if (delta==0) break; + bytes += delta; + count--; + } + return bytes; +} + +} \ No newline at end of file diff --git a/SDK/pfc/wildcard.cpp b/SDK/pfc/wildcard.cpp new file mode 100644 index 0000000..a5b87c2 --- /dev/null +++ b/SDK/pfc/wildcard.cpp @@ -0,0 +1,50 @@ +#include "pfc.h" + +static bool test_recur(const char * fn,const char * rm,bool b_sep) +{ + for(;;) + { + if ((b_sep && *rm==';') || *rm==0) return *fn==0; + else if (*rm=='*') + { + rm++; + do + { + if (test_recur(fn,rm,b_sep)) return true; + } while(pfc::utf8_advance(fn)); + return false; + } + else if (*fn==0) return false; + else if (*rm!='?' && pfc::charLower(pfc::utf8_get_char(fn))!=pfc::charLower(pfc::utf8_get_char(rm))) return false; + + fn = pfc::utf8_char_next(fn); rm = pfc::utf8_char_next(rm); + } +} + +bool wildcard_helper::test_path(const char * path,const char * pattern,bool b_sep) {return test(path + pfc::scan_filename(path),pattern,b_sep);} + +bool wildcard_helper::test(const char * fn,const char * pattern,bool b_sep) +{ + if (!b_sep) return test_recur(fn,pattern,false); + const char * rm=pattern; + while(*rm) + { + if (test_recur(fn,rm,true)) return true; + while(*rm && *rm!=';') rm++; + if (*rm==';') + { + while(*rm==';') rm++; + while(*rm==' ') rm++; + } + }; + + return false; +} + +bool wildcard_helper::has_wildcards(const char * str) {return strchr(str,'*') || strchr(str,'?');} + +const char * wildcard_helper::get_wildcard_list() {return "*?";} + +bool wildcard_helper::is_wildcard(char c) { + return c == '*' || c == '?'; +} diff --git a/SDK/pfc/wildcard.h b/SDK/pfc/wildcard.h new file mode 100644 index 0000000..f644b99 --- /dev/null +++ b/SDK/pfc/wildcard.h @@ -0,0 +1,8 @@ +namespace wildcard_helper +{ + bool test_path(const char * path,const char * pattern,bool b_separate_by_semicolon = false);//will extract filename from path first + bool test(const char * str,const char * pattern,bool b_separate_by_semicolon = false);//tests if str matches pattern + bool has_wildcards(const char * str); + const char * get_wildcard_list(); + bool is_wildcard(char c); +}; diff --git a/SDK/pfc/win-objects.cpp b/SDK/pfc/win-objects.cpp new file mode 100644 index 0000000..00e7b61 --- /dev/null +++ b/SDK/pfc/win-objects.cpp @@ -0,0 +1,330 @@ +#include "pfc.h" + +#include "pp-winapi.h" + +#ifdef _WIN32 + +BOOL pfc::winFormatSystemErrorMessage(pfc::string_base & p_out,DWORD p_code) { + switch(p_code) { + case ERROR_CHILD_NOT_COMPLETE: + p_out = "Application cannot be run in Win32 mode."; + return TRUE; + case ERROR_INVALID_ORDINAL: + p_out = "Invalid ordinal."; + return TRUE; + case ERROR_INVALID_STARTING_CODESEG: + p_out = "Invalid code segment."; + return TRUE; + case ERROR_INVALID_STACKSEG: + p_out = "Invalid stack segment."; + return TRUE; + case ERROR_INVALID_MODULETYPE: + p_out = "Invalid module type."; + return TRUE; + case ERROR_INVALID_EXE_SIGNATURE: + p_out = "Invalid executable signature."; + return TRUE; + case ERROR_BAD_EXE_FORMAT: + p_out = "Not a valid Win32 application."; + return TRUE; + case ERROR_EXE_MACHINE_TYPE_MISMATCH: + p_out = "Machine type mismatch."; + return TRUE; + case ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY: + case ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY: + p_out = "Unable to modify a signed binary."; + return TRUE; + default: + { + TCHAR temp[512]; + if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,0,p_code,0,temp,_countof(temp),0) == 0) return FALSE; + for(t_size n=0;n<_countof(temp);n++) { + switch(temp[n]) { + case '\n': + case '\r': + temp[n] = ' '; + break; + } + } + p_out = stringcvt::string_utf8_from_os(temp,_countof(temp)); + return TRUE; + } + break; + } +} +void pfc::winPrefixPath(pfc::string_base & out, const char * p_path) { + const char * prepend_header = "\\\\?\\"; + const char * prepend_header_net = "\\\\?\\UNC\\"; + if (pfc::strcmp_partial( p_path, prepend_header ) == 0) { out = p_path; return; } + out.reset(); + if (pfc::strcmp_partial(p_path,"\\\\") != 0) { + out << prepend_header << p_path; + } else { + out << prepend_header_net << (p_path+2); + } +}; + +void pfc::winUnPrefixPath(pfc::string_base & out, const char * p_path) { + const char * prepend_header = "\\\\?\\"; + const char * prepend_header_net = "\\\\?\\UNC\\"; + if (pfc::strcmp_partial(p_path, prepend_header_net) == 0) { + out = pfc::string_formatter() << "\\\\" << (p_path + strlen(prepend_header_net) ); + return; + } + if (pfc::strcmp_partial(p_path, prepend_header) == 0) { + out = (p_path + strlen(prepend_header)); + return; + } + out = p_path; +} + +format_win32_error::format_win32_error(DWORD p_code) { + LastErrorRevertScope revert; + if (p_code == 0) m_buffer = "Undefined error"; + else if (!pfc::winFormatSystemErrorMessage(m_buffer,p_code)) m_buffer << "Unknown error code (" << (unsigned)p_code << ")"; +} + +format_hresult::format_hresult(HRESULT p_code) { + if (!pfc::winFormatSystemErrorMessage(m_buffer,(DWORD)p_code)) m_buffer = "Unknown error code"; + stamp_hex(p_code); +} +format_hresult::format_hresult(HRESULT p_code, const char * msgOverride) { + m_buffer = msgOverride; + stamp_hex(p_code); +} + +void format_hresult::stamp_hex(HRESULT p_code) { + m_buffer << " (0x" << pfc::format_hex((t_uint32)p_code, 8) << ")"; +} + +#ifdef PFC_WINDOWS_DESKTOP_APP + +void uAddWindowStyle(HWND p_wnd,LONG p_style) { + SetWindowLong(p_wnd,GWL_STYLE, GetWindowLong(p_wnd,GWL_STYLE) | p_style); +} + +void uRemoveWindowStyle(HWND p_wnd,LONG p_style) { + SetWindowLong(p_wnd,GWL_STYLE, GetWindowLong(p_wnd,GWL_STYLE) & ~p_style); +} + +void uAddWindowExStyle(HWND p_wnd,LONG p_style) { + SetWindowLong(p_wnd,GWL_EXSTYLE, GetWindowLong(p_wnd,GWL_EXSTYLE) | p_style); +} + +void uRemoveWindowExStyle(HWND p_wnd,LONG p_style) { + SetWindowLong(p_wnd,GWL_EXSTYLE, GetWindowLong(p_wnd,GWL_EXSTYLE) & ~p_style); +} + +unsigned MapDialogWidth(HWND p_dialog,unsigned p_value) { + RECT temp; + temp.left = 0; temp.right = p_value; temp.top = temp.bottom = 0; + if (!MapDialogRect(p_dialog,&temp)) return 0; + return temp.right; +} + +bool IsKeyPressed(unsigned vk) { + return (GetKeyState(vk) & 0x8000) ? true : false; +} + +//! Returns current modifier keys pressed, using win32 MOD_* flags. +unsigned GetHotkeyModifierFlags() { + unsigned ret = 0; + if (IsKeyPressed(VK_CONTROL)) ret |= MOD_CONTROL; + if (IsKeyPressed(VK_SHIFT)) ret |= MOD_SHIFT; + if (IsKeyPressed(VK_MENU)) ret |= MOD_ALT; + if (IsKeyPressed(VK_LWIN) || IsKeyPressed(VK_RWIN)) ret |= MOD_WIN; + return ret; +} + + + +bool CClipboardOpenScope::Open(HWND p_owner) { + Close(); + if (OpenClipboard(p_owner)) { + m_open = true; + return true; + } else { + return false; + } +} +void CClipboardOpenScope::Close() { + if (m_open) { + m_open = false; + CloseClipboard(); + } +} + + +CGlobalLockScope::CGlobalLockScope(HGLOBAL p_handle) : m_handle(p_handle), m_ptr(GlobalLock(p_handle)) { + if (m_ptr == NULL) throw std::bad_alloc(); +} +CGlobalLockScope::~CGlobalLockScope() { + if (m_ptr != NULL) GlobalUnlock(m_handle); +} + +bool IsPointInsideControl(const POINT& pt, HWND wnd) { + HWND walk = WindowFromPoint(pt); + for(;;) { + if (walk == NULL) return false; + if (walk == wnd) return true; + if (GetWindowLong(walk,GWL_STYLE) & WS_POPUP) return false; + walk = GetParent(walk); + } +} + +bool IsWindowChildOf(HWND child, HWND parent) { + HWND walk = child; + while(walk != parent && walk != NULL && (GetWindowLong(walk,GWL_STYLE) & WS_CHILD) != 0) { + walk = GetParent(walk); + } + return walk == parent; +} + +void win32_menu::release() { + if (m_menu != NULL) { + DestroyMenu(m_menu); + m_menu = NULL; + } +} + +void win32_menu::create_popup() { + release(); + SetLastError(NO_ERROR); + m_menu = CreatePopupMenu(); + if (m_menu == NULL) throw exception_win32(GetLastError()); +} + +#endif // #ifdef PFC_WINDOWS_DESKTOP_APP + +void win32_event::create(bool p_manualreset,bool p_initialstate) { + release(); + SetLastError(NO_ERROR); + m_handle = CreateEvent(NULL,p_manualreset ? TRUE : FALSE, p_initialstate ? TRUE : FALSE,NULL); + if (m_handle == NULL) throw exception_win32(GetLastError()); +} + +void win32_event::release() { + HANDLE temp = detach(); + if (temp != NULL) CloseHandle(temp); +} + + +DWORD win32_event::g_calculate_wait_time(double p_seconds) { + DWORD time = 0; + if (p_seconds> 0) { + time = pfc::rint32(p_seconds * 1000.0); + if (time == 0) time = 1; + } else if (p_seconds < 0) { + time = INFINITE; + } + return time; +} + +//! Returns true when signaled, false on timeout +bool win32_event::g_wait_for(HANDLE p_event,double p_timeout_seconds) { + SetLastError(NO_ERROR); + DWORD status = WaitForSingleObject(p_event,g_calculate_wait_time(p_timeout_seconds)); + switch(status) { + case WAIT_FAILED: + throw exception_win32(GetLastError()); + default: + throw pfc::exception_bug_check(); + case WAIT_OBJECT_0: + return true; + case WAIT_TIMEOUT: + return false; + } +} + +void win32_event::set_state(bool p_state) { + PFC_ASSERT(m_handle != NULL); + if (p_state) SetEvent(m_handle); + else ResetEvent(m_handle); +} + +int win32_event::g_twoEventWait( HANDLE ev1, HANDLE ev2, double timeout ) { + HANDLE h[2] = {ev1, ev2}; + switch(WaitForMultipleObjects(2, h, FALSE, g_calculate_wait_time( timeout ) )) { + default: + pfc::crash(); + case WAIT_TIMEOUT: + return 0; + case WAIT_OBJECT_0: + return 1; + case WAIT_OBJECT_0 + 1: + return 2; + } +} + +int win32_event::g_twoEventWait( win32_event & ev1, win32_event & ev2, double timeout ) { + return g_twoEventWait( ev1.get_handle(), ev2.get_handle(), timeout ); +} + +#ifdef PFC_WINDOWS_DESKTOP_APP + +void win32_icon::release() { + HICON temp = detach(); + if (temp != NULL) DestroyIcon(temp); +} + + +void win32_accelerator::load(HINSTANCE p_inst,const TCHAR * p_id) { + release(); + SetLastError(NO_ERROR); + m_accel = LoadAccelerators(p_inst,p_id); + if (m_accel == NULL) { + throw exception_win32(GetLastError()); + } +} + +void win32_accelerator::release() { + if (m_accel != NULL) { + DestroyAcceleratorTable(m_accel); + m_accel = NULL; + } +} + +#endif // #ifdef PFC_WINDOWS_DESKTOP_APP + +void uSleepSeconds(double p_time,bool p_alertable) { + SleepEx(win32_event::g_calculate_wait_time(p_time),p_alertable ? TRUE : FALSE); +} + + +#ifdef PFC_WINDOWS_DESKTOP_APP + +WORD GetWindowsVersionCode() throw() { + const DWORD ver = GetVersion(); + return (WORD)HIBYTE(LOWORD(ver)) | ((WORD)LOBYTE(LOWORD(ver)) << 8); +} + + +namespace pfc { + bool isShiftKeyPressed() { + return IsKeyPressed(VK_SHIFT); + } + bool isCtrlKeyPressed() { + return IsKeyPressed(VK_CONTROL); + } + bool isAltKeyPressed() { + return IsKeyPressed(VK_MENU); + } +} + +#else +// If unknown / not available on this architecture, return false always +namespace pfc { + bool isShiftKeyPressed() { + return false; + } + bool isCtrlKeyPressed() { + return false; + } + bool isAltKeyPressed() { + return false; + } +} + +#endif // #ifdef PFC_WINDOWS_DESKTOP_APP + +#endif diff --git a/SDK/pfc/win-objects.h b/SDK/pfc/win-objects.h new file mode 100644 index 0000000..8a2dec0 --- /dev/null +++ b/SDK/pfc/win-objects.h @@ -0,0 +1,309 @@ +namespace pfc { + BOOL winFormatSystemErrorMessage(pfc::string_base & p_out,DWORD p_code); + + // Prefix filesystem paths with \\?\ and \\?\UNC where appropriate. + void winPrefixPath(pfc::string_base & out, const char * p_path); + // Reverse winPrefixPath + void winUnPrefixPath(pfc::string_base & out, const char * p_path); +} + + +class LastErrorRevertScope { +public: + LastErrorRevertScope() : m_val(GetLastError()) {} + ~LastErrorRevertScope() {SetLastError(m_val);} + +private: + const DWORD m_val; +}; + +class format_win32_error { +public: + format_win32_error(DWORD p_code); + + const char * get_ptr() const {return m_buffer.get_ptr();} + operator const char*() const {return m_buffer.get_ptr();} +private: + pfc::string8 m_buffer; +}; + +class format_hresult { +public: + format_hresult(HRESULT p_code); + format_hresult(HRESULT p_code, const char * msgOverride); + + const char * get_ptr() const {return m_buffer.get_ptr();} + operator const char*() const {return m_buffer.get_ptr();} +private: + void stamp_hex(HRESULT p_code); + pfc::string_formatter m_buffer; +}; + +struct exception_win32 : public std::exception { + exception_win32(DWORD p_code) : std::exception(format_win32_error(p_code)), m_code(p_code) {} + DWORD get_code() const {return m_code;} +private: + DWORD m_code; +}; + +#ifdef PFC_WINDOWS_DESKTOP_APP + +void uAddWindowStyle(HWND p_wnd,LONG p_style); +void uRemoveWindowStyle(HWND p_wnd,LONG p_style); +void uAddWindowExStyle(HWND p_wnd,LONG p_style); +void uRemoveWindowExStyle(HWND p_wnd,LONG p_style); +unsigned MapDialogWidth(HWND p_dialog,unsigned p_value); +bool IsKeyPressed(unsigned vk); + +//! Returns current modifier keys pressed, using win32 MOD_* flags. +unsigned GetHotkeyModifierFlags(); + +class CClipboardOpenScope { +public: + CClipboardOpenScope() : m_open(false) {} + ~CClipboardOpenScope() {Close();} + bool Open(HWND p_owner); + void Close(); +private: + bool m_open; + + PFC_CLASS_NOT_COPYABLE_EX(CClipboardOpenScope) +}; + +class CGlobalLockScope { +public: + CGlobalLockScope(HGLOBAL p_handle); + ~CGlobalLockScope(); + void * GetPtr() const {return m_ptr;} + t_size GetSize() const {return GlobalSize(m_handle);} +private: + void * m_ptr; + HGLOBAL m_handle; + + PFC_CLASS_NOT_COPYABLE_EX(CGlobalLockScope) +}; + +template class CGlobalLockScopeT { +public: + CGlobalLockScopeT(HGLOBAL handle) : m_scope(handle) {} + TItem * GetPtr() const {return reinterpret_cast(m_scope.GetPtr());} + t_size GetSize() const { + const t_size val = m_scope.GetSize(); + PFC_ASSERT( val % sizeof(TItem) == 0 ); + return val / sizeof(TItem); + } +private: + CGlobalLockScope m_scope; +}; + +bool IsPointInsideControl(const POINT& pt, HWND wnd); +bool IsWindowChildOf(HWND child, HWND parent); + +class win32_menu { +public: + win32_menu(HMENU p_initval) : m_menu(p_initval) {} + win32_menu() : m_menu(NULL) {} + ~win32_menu() {release();} + void release(); + void set(HMENU p_menu) {release(); m_menu = p_menu;} + void create_popup(); + HMENU get() const {return m_menu;} + HMENU detach() {return pfc::replace_t(m_menu,(HMENU)NULL);} + + bool is_valid() const {return m_menu != NULL;} +private: + win32_menu(const win32_menu &); + const win32_menu & operator=(const win32_menu &); + + HMENU m_menu; +}; + +#endif + +class win32_event { +public: + win32_event() : m_handle(NULL) {} + ~win32_event() {release();} + + void create(bool p_manualreset,bool p_initialstate); + + void set(HANDLE p_handle) {release(); m_handle = p_handle;} + HANDLE get() const {return m_handle;} + HANDLE get_handle() const {return m_handle;} + HANDLE detach() {return pfc::replace_t(m_handle,(HANDLE)NULL);} + bool is_valid() const {return m_handle != NULL;} + + void release(); + + //! Returns true when signaled, false on timeout + bool wait_for(double p_timeout_seconds) {return g_wait_for(get(),p_timeout_seconds);} + + static DWORD g_calculate_wait_time(double p_seconds); + + //! Returns true when signaled, false on timeout + static bool g_wait_for(HANDLE p_event,double p_timeout_seconds); + + void set_state(bool p_state); + + // Two-wait event functions, return 0 on timeout, 1 on evt1 set, 2 on evt2 set + static int g_twoEventWait( win32_event & ev1, win32_event & ev2, double timeout ); + static int g_twoEventWait( HANDLE ev1, HANDLE ev2, double timeout ); +private: + win32_event(const win32_event&); + const win32_event & operator=(const win32_event &); + + HANDLE m_handle; +}; + +void uSleepSeconds(double p_time,bool p_alertable); + +#ifdef PFC_WINDOWS_DESKTOP_APP + +class win32_icon { +public: + win32_icon(HICON p_initval) : m_icon(p_initval) {} + win32_icon() : m_icon(NULL) {} + ~win32_icon() {release();} + + void release(); + + void set(HICON p_icon) {release(); m_icon = p_icon;} + HICON get() const {return m_icon;} + HICON detach() {return pfc::replace_t(m_icon,(HICON)NULL);} + + bool is_valid() const {return m_icon != NULL;} + +private: + win32_icon(const win32_icon&) {throw pfc::exception_not_implemented();} + const win32_icon & operator=(const win32_icon &) {throw pfc::exception_not_implemented();} + + HICON m_icon; +}; + +class win32_accelerator { +public: + win32_accelerator() : m_accel(NULL) {} + ~win32_accelerator() {release();} + HACCEL get() const {return m_accel;} + + void load(HINSTANCE p_inst,const TCHAR * p_id); + void release(); +private: + HACCEL m_accel; + PFC_CLASS_NOT_COPYABLE(win32_accelerator,win32_accelerator); +}; + +class SelectObjectScope { +public: + SelectObjectScope(HDC p_dc,HGDIOBJ p_obj) throw() : m_dc(p_dc), m_obj(SelectObject(p_dc,p_obj)) {} + ~SelectObjectScope() throw() {SelectObject(m_dc,m_obj);} +private: + PFC_CLASS_NOT_COPYABLE_EX(SelectObjectScope) + HDC m_dc; + HGDIOBJ m_obj; +}; + +class OffsetWindowOrgScope { +public: + OffsetWindowOrgScope(HDC dc, const POINT & pt) throw() : m_dc(dc), m_pt(pt) { + OffsetWindowOrgEx(m_dc, m_pt.x, m_pt.y, NULL); + } + ~OffsetWindowOrgScope() throw() { + OffsetWindowOrgEx(m_dc, -m_pt.x, -m_pt.y, NULL); + } + +private: + const HDC m_dc; + const POINT m_pt; +}; +class DCStateScope { +public: + DCStateScope(HDC p_dc) throw() : m_dc(p_dc) { + m_state = SaveDC(m_dc); + } + ~DCStateScope() throw() { + RestoreDC(m_dc,m_state); + } +private: + const HDC m_dc; + int m_state; +}; +#endif // #ifdef PFC_WINDOWS_DESKTOP_APP + +class exception_com : public std::exception { +public: + exception_com(HRESULT p_code) : std::exception(format_hresult(p_code)), m_code(p_code) {} + exception_com(HRESULT p_code, const char * msg) : std::exception(format_hresult(p_code, msg)), m_code(p_code) {} + HRESULT get_code() const {return m_code;} +private: + HRESULT m_code; +}; + +#ifdef PFC_WINDOWS_DESKTOP_APP + +// Same format as _WIN32_WINNT macro. +WORD GetWindowsVersionCode() throw(); + +#endif + +//! Simple implementation of a COM reference counter. The initial reference count is zero, so it can be used with pfc::com_ptr_t<> with plain operator=/constructor rather than attach(). +template class ImplementCOMRefCounter : public TBase { +public: + TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(ImplementCOMRefCounter,TBase) + ULONG STDMETHODCALLTYPE AddRef() { + return ++m_refcounter; + } + ULONG STDMETHODCALLTYPE Release() { + long val = --m_refcounter; + if (val == 0) delete this; + return val; + } +protected: + virtual ~ImplementCOMRefCounter() {} +private: + pfc::refcounter m_refcounter; +}; + + + +template +class CoTaskMemObject { +public: + CoTaskMemObject() : m_ptr() {} + + ~CoTaskMemObject() {CoTaskMemFree(m_ptr);} + void Reset() {CoTaskMemFree(pfc::replace_null_t(m_ptr));} + TPtr * Receive() {Reset(); return &m_ptr;} + + TPtr m_ptr; + PFC_CLASS_NOT_COPYABLE(CoTaskMemObject, CoTaskMemObject ); +}; + + +namespace pfc { + bool isShiftKeyPressed(); + bool isCtrlKeyPressed(); + bool isAltKeyPressed(); + + + class winHandle { + public: + winHandle(HANDLE h_ = INVALID_HANDLE_VALUE) : h(h_) {} + ~winHandle() { Close(); } + void Close() { + if (h != INVALID_HANDLE_VALUE) { CloseHandle(h); h = INVALID_HANDLE_VALUE; } + } + + void Attach(HANDLE h_) { Close(); h = h_; } + HANDLE Detach() { HANDLE t = h; h = INVALID_HANDLE_VALUE; return t; } + + HANDLE Get() const { return h; } + operator HANDLE() const { return h; } + + HANDLE h; + private: + winHandle(const winHandle&); + void operator=(const winHandle&); + }; +} + diff --git a/SDK/put foobar2000 SDK here b/SDK/put foobar2000 SDK here deleted file mode 100644 index e69de29..0000000 diff --git a/SDK/sdk-license.txt b/SDK/sdk-license.txt new file mode 100644 index 0000000..f2b28b2 --- /dev/null +++ b/SDK/sdk-license.txt @@ -0,0 +1,18 @@ +foobar2000 1.3 SDK +Copyright (c) 2001-2015, Peter Pawlowski +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation or other materials provided with the distribution. + +Usage restrictions: +It is illegal to use this SDK as a part of foobar2000 components that operate outside of legally documented programming interfaces (APIs), such as using window procedure hooks to modify user interface behaviors. We believe components doing so to be harmful to our userbase by introducing compatibility issues and dependencies on undocumented behaviors of our code that may change at any time without any notice or an update to the SDK which would reflect the change. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + +Note that a separate less restrictive license applies to the included 'pfc' library. See pfc-license.txt for details. diff --git a/SDK/sdk-readme.css b/SDK/sdk-readme.css new file mode 100644 index 0000000..1020d9b --- /dev/null +++ b/SDK/sdk-readme.css @@ -0,0 +1,1291 @@ +a.interwiki { +padding-left : 16px; +} +a.iw_wp { +} +a.iw_wpde { +} +a.iw_wpmeta { +} +a.iw_doku { +} +a.iw_sb { +} +a.iw_amazon { +} +a.iw_amazon_de { +} +a.iw_amazon_uk { +} +a.iw_phpfn { +} +a.iw_dokubug { +} +a.iw_coral { +} +a.iw_google { +} +a.iw_meatball { +} +a.iw_wiki { +} +a.mediafile { +padding-left : 18px; +padding-bottom : 1px; +} +a.mf_jpg { +} +a.mf_jpeg { +} +a.mf_gif { +} +a.mf_png { +} +a.mf_tgz { +} +a.mf_tar { +} +a.mf_gz { +} +a.mf_zip { +} +a.mf_rar { +} +a.mf_pdf { +} +a.mf_ps { +} +a.mf_doc { +} +a.mf_xls { +} +a.mf_ppt { +} +a.mf_rtf { +} +a.mf_swf { +} +a.mf_rpm { +} +a.mf_deb { +} +a.mf_sxw { +} +a.mf_sxc { +} +a.mf_sxi { +} +a.mf_sxd { +} +a.mf_odc { +} +a.mf_odf { +} +a.mf_odg { +} +a.mf_odi { +} +a.mf_odp { +} +a.mf_ods { +} +a.mf_odt { +} +div.clearer { +clear : both; +line-height : 0; +height : 0; +overflow : hidden; +} +div.no { +display : inline; +margin : 0; +padding : 0; +} +.hidden { +display : none; +} +div.error { +background : #fcc; +color : #000; +border-bottom : 1px solid #faa; +font-size : 90%; +margin : 0; +padding-left : 3em; +overflow : hidden; +} +div.info { +background : #ccf; +color : #000; +border-bottom : 1px solid #aaf; +font-size : 90%; +margin : 0; +padding-left : 3em; +overflow : hidden; +} +div.success { +background : #cfc; +color : #000; +border-bottom : 1px solid #afa; +font-size : 90%; +margin : 0; +padding-left : 3em; +overflow : hidden; +} +div.notify { +background : #ffc; +color : #000; +border-bottom : 1px solid #ffa; +font-size : 90%; +margin : 0; +padding-left : 3em; +overflow : hidden; +} +.medialeft { +float : left; +} +.mediaright { +float : right; +} +.mediacenter { +display : block; +margin-left : auto; +margin-right : auto; +} +.leftalign { +text-align : left; +} +.centeralign { +text-align : center; +} +.rightalign { +text-align : right; +} +em.u { +font-style : normal; +text-decoration : underline; +} +em em.u { +font-style : italic; +} +.code .br0 { +color : #6c6; +} +.code .co1 { +color : #808080; +font-style : italic; +} +.code .co2 { +color : #808080; +font-style : italic; +} +.code .co3 { +color : #808080; +} +.code .coMULTI { +color : #808080; +font-style : italic; +} +.code .es0 { +color : #009; +font-weight : bold; +} +.code .kw1 { +color : #b1b100; +} +.code .kw2 { +color : #000; +font-weight : bold; +} +.code .kw3 { +color : #006; +} +.code .kw4 { +color : #933; +} +.code .kw5 { +color : #00f; +} +.code .me1 { +color : #060; +} +.code .me2 { +color : #060; +} +.code .nu0 { +color : #c6c; +} +.code .re0 { +color : #00f; +} +.code .re1 { +color : #00f; +} +.code .re2 { +color : #00f; +} +.code .re3 { +color : #f33; +font-weight : bold; +} +.code .re4 { +color : #099; +} +.code .st0 { +color : #f00; +} +.code .sy0 { +color : #6c6; +} +#acl__manager label { +text-align : left; +font-weight : normal; +display : inline; +} +#acl__manager table { +margin-left : 10%; +width : 80%; +} +#config__manager div.success, #config__manager div.error, #config__manager div.info { +background-position : 0.5em 0%; +padding : 0.5em; +text-align : center; +} +#config__manager fieldset { +margin : 1em; +width : auto; +margin-bottom : 2em; +background-color : #dee7ec; +color : #000; +padding : 0 1em; +} +#config__manager legend { +font-size : 1.25em; +} +#config__manager table { +margin : 1em 0; +width : 100%; +} +#config__manager fieldset td { +text-align : left; +} +#config__manager fieldset td.value { +width : 30em; +} +#config__manager td input.edit { +width : 30em; +} +#config__manager td textarea.edit { +width : 27.5em; +height : 4em; +} +#config__manager tr .input, #config__manager tr input, #config__manager tr textarea, #config__manager tr select { +background-color : #fff; +color : #000; +} +#config__manager tr.default .input, #config__manager tr.default input, #config__manager tr.default textarea, #config__manager tr.default select, #config__manager .selectiondefault { +background-color : #cdf; +color : #000; +} +#config__manager tr.protected .input, #config__manager tr.protected input, #config__manager tr.protected textarea, #config__manager tr.protected select, #config__manager tr.protected .selection { +background-color : #fcc !important ; +color : #000 !important ; +} +#config__manager td.error { +background-color : red; +color : #000; +} +#config__manager .selection { +width : 14.8em; +float : left; +margin : 0 0.3em 2px 0; +} +#config__manager .selection label { +float : right; +width : 14em; +font-size : 90%; +} +* html #config__manager .selection label { +padding-top : 2px; +} +#config__manager .selection input.checkbox { +padding-left : 0.7em; +} +#config__manager .other { +clear : both; +padding-top : 0.5em; +} +#config__manager .other label { +padding-left : 2px; +font-size : 90%; +} +#plugin__manager h2 { +margin-left : 0; +} +#plugin__manager form { +display : block; +margin : 0; +padding : 0; +} +#plugin__manager legend { +display : none; +} +#plugin__manager fieldset { +width : auto; +} +#plugin__manager .button { +margin : 0; +} +#plugin__manager p, #plugin__manager label { +text-align : left; +} +#plugin__manager .hidden { +display : none; +} +#plugin__manager .new { +background : #dee7ec; +} +#plugin__manager input[disabled] { +color : #ccc; +border-color : #ccc; +} +#plugin__manager .pm_menu, #plugin__manager .pm_info { +margin-left : 0; +text-align : left; +} +#plugin__manager .pm_menu { +float : left; +width : 48%; +} +#plugin__manager .pm_info { +float : right; +width : 50%; +} +#plugin__manager .common fieldset { +margin : 0; +padding : 0 0 1em 0; +text-align : left; +border : none; +} +#plugin__manager .common label { +padding : 0 0 0.5em 0; +} +#plugin__manager .common input.edit { +width : 24em; +margin : 0.5em; +} +#plugin__manager .plugins fieldset { +color : #000; +background : #fff; +text-align : right; +border-top : none; +border-right : none; +border-left : none; +} +#plugin__manager .plugins fieldset.protected { +background : #fdd; +color : #000; +} +#plugin__manager .plugins fieldset.disabled { +background : #e0e0e0; +color : #a8a8a8; +} +#plugin__manager .plugins .legend { +color : #000; +background : inherit; +display : block; +margin : 0; +padding : 0; +font-size : 1em; +line-height : 1.4em; +font-weight : normal; +text-align : left; +float : left; +padding : 0; +clear : none; +} +#plugin__manager .plugins .button { +font-size : 95%; +} +#plugin__manager .plugins fieldset.buttons { +border : none; +} +#plugin__manager .plugins fieldset.buttons .button { +float : left; +} +#plugin__manager .pm_info h3 { +margin-left : 0; +} +#plugin__manager .pm_info dl { +margin : 1em 0; +padding : 0; +} +#plugin__manager .pm_info dt { +width : 6em; +float : left; +clear : left; +margin : 0; +padding : 0; +} +#plugin__manager .pm_info dd { +margin : 0 0 0 7em; +padding : 0; +background : none; +} +#plugin__manager .plugins .enable { +float : left; +width : auto; +margin-right : 0.5em; +} +#user__manager tr.disabled { +color : #6f6f6f; +background : #e4e4e4; +} +#user__manager tr.user_info { +vertical-align : top; +} +#user__manager div.edit_user { +width : 46%; +float : left; +} +#user__manager table { +margin-bottom : 1em; +} +#user__manager input.button[disabled] { +color : #ccc !important ; +border-color : #ccc !important ; +} +div.dokuwiki .header { +padding : 3px 0 0 2px; +} +div.dokuwiki .pagename { +float : left; +font-size : 200%; +font-weight : bolder; +color : #dee7ec; +text-align : left; +vertical-align : middle; +} +div.dokuwiki .pagename a { +color : #436976 !important ; +text-decoration : none !important ; +} +div.dokuwiki .logo { +float : right; +font-size : 220%; +font-weight : bolder; +text-align : right; +vertical-align : middle; +} +div.dokuwiki .logo a { +color : #dee7ec !important ; +text-decoration : none !important ; +font-variant : small-caps; +letter-spacing : 2pt; +} +div.dokuwiki .bar { +border-top : 1px solid #8cacbb; +border-bottom : 1px solid #8cacbb; +background : #dee7ec; +padding : 0.1em 0.15em; +clear : both; +} +div.dokuwiki .bar-left { +float : left; +} +div.dokuwiki .bar-right { +float : right; +text-align : right; +} +div.dokuwiki #bar__bottom { +margin-bottom : 3px; +} +div.dokuwiki div.meta { +clear : both; +margin-top : 1em; +color : #638c9c; +font-size : 70%; +} +div.dokuwiki div.meta div.user { +float : left; +} +div.dokuwiki div.meta div.doc { +text-align : right; +} +* { +padding : 0; +margin : 0; +} +body { +font : 80% "Lucida Grande", Verdana, Lucida, Helvetica, Arial, sans-serif; +background-color : #fff; +color : #000; +} +div.dokuwiki div.page { +margin : 4px 2em 0 1em; +text-align : justify; +} +div.dokuwiki table { +font-size : 100%; +} +div.dokuwiki img { +border : 0; +} +div.dokuwiki p, div.dokuwiki blockquote, div.dokuwiki table, div.dokuwiki pre { +margin : 0 0 1em 0; +} +div.dokuwiki hr { +border : 0; +border-top : 1px solid #8cacbb; +text-align : center; +height : 0; +} +div.dokuwiki div.nothing { +text-align : center; +margin : 2em; +} +div.dokuwiki form { +border : none; +display : inline; +} +div.dokuwiki label.block { +display : block; +text-align : right; +font-weight : bold; +} +div.dokuwiki label.simple { +display : block; +text-align : left; +font-weight : normal; +} +div.dokuwiki label.block input.edit { +width : 50%; +} +div.dokuwiki fieldset { +width : 300px; +text-align : center; +border : 1px solid #8cacbb; +padding : 0.5em; +margin : auto; +} +div.dokuwiki textarea.edit { +font-family : monospace; +font-size : 14px; +color : #000; +background-color : #fff; +border : 1px solid #8cacbb; +padding : 0.3em 0 0 0.3em; +width : 100%; +} +html > body div.dokuwiki textarea.edit { +background : #fff; +} +div.dokuwiki input.edit, div.dokuwiki select.edit { +font-size : 100%; +border : 1px solid #8cacbb; +color : #000; +background-color : #fff; +vertical-align : middle; +margin : 1px; +padding : 0.2em 0.3em; +display : inline; +} +html > body div.dokuwiki input.edit, html > body div.dokuwiki select.edit { +background : #fff; +} +div.dokuwiki select.edit { +padding : 0.1em 0; +} +div.dokuwiki input.missing { +font-size : 100%; +border : 1px solid #8cacbb; +color : #000; +background-color : #fcc; +vertical-align : middle; +margin : 1px; +padding : 0.2em 0.3em; +display : inline; +} +div.dokuwiki textarea.edit[disabled], div.dokuwiki textarea.edit[readonly], div.dokuwiki input.edit[disabled], div.dokuwiki input.edit[readonly], div.dokuwiki select.edit[disabled] { +background-color : #f5f5f5 !important ; +color : #666 !important ; +} +div.dokuwiki div.toolbar, div.dokuwiki div#wiki__editbar { +margin : 2px 0; +text-align : left; +} +div.dokuwiki div#size__ctl { +float : right; +width : 60px; +height : 2.7em; +} +div.dokuwiki #size__ctl img { +cursor : pointer; +} +div.dokuwiki div#wiki__editbar div.editButtons { +float : left; +padding : 0 1em 0.7em 0; +} +div.dokuwiki div#wiki__editbar div.summary { +float : left; +} +div.dokuwiki .nowrap { +white-space : nowrap; +} +div.dokuwiki div#draft__status { +float : right; +color : #638c9c; +} +div.dokuwiki input.button, div.dokuwiki button.button { +border : 1px solid #8cacbb; +color : #000; +background-color : #fff; +vertical-align : middle; +text-decoration : none; +font-size : 100%; +cursor : pointer; +margin : 1px; +padding : 0.125em 0.4em; +} +html > body div.dokuwiki input.button, html > body div.dokuwiki button.button { +background : #fff; +} +* html div.dokuwiki input.button, * html div.dokuwiki button.button { +height : 1.8em; +} +div.dokuwiki div.secedit input.button { +border : 1px solid #8cacbb; +color : #000; +background-color : #fff; +vertical-align : middle; +text-decoration : none; +margin : 0; +padding : 0; +font-size : 10px; +cursor : pointer; +float : right; +display : inline; +} +div.dokuwiki div.pagenav { +margin : 1em 0 0 0; +} +div.dokuwiki div.pagenav-prev { +text-align : right; +float : left; +width : 49%; +} +div.dokuwiki div.pagenav-next { +text-align : left; +float : right; +width : 49%; +} +div.dokuwiki a:link, div.dokuwiki a:visited { +color : #436976; +text-decoration : none; +} +div.dokuwiki a:hover, div.dokuwiki a:active { +color : #000; +text-decoration : underline; +} +div.dokuwiki h1 a, div.dokuwiki h2 a, div.dokuwiki h3 a, div.dokuwiki h4 a, div.dokuwiki h5 a, div.dokuwiki a.nolink { +color : #000 !important ; +text-decoration : none !important ; +} +div.dokuwiki a.urlextern { +background : transparent; +padding : 1px 0 1px 16px; +} +div.dokuwiki a.windows { +background : transparent; +padding : 1px 0 1px 16px; +} +div.dokuwiki a.urlextern:link, div.dokuwiki a.windows:link, div.dokuwiki a.interwiki:link { +color : #436976; +} +div.dokuwiki a.urlextern:visited, div.dokuwiki a.windows:visited, div.dokuwiki a.interwiki:visited { +color : purple; +} +div.dokuwiki a.urlextern:hover, div.dokuwiki a.urlextern:active, div.dokuwiki a.windows:hover, div.dokuwiki a.windows:active, div.dokuwiki a.interwiki:hover, div.dokuwiki a.interwiki:active { +color : #000; +} +div.dokuwiki a.mail { +background : transparent; +padding : 1px 0 1px 16px; +} +div.dokuwiki a.wikilink1 { +color : #090 !important ; +} +div.dokuwiki a.wikilink2 { +color : #f30 !important ; +text-decoration : none !important ; +border-bottom : 1px dashed #f30 !important ; +} +div.dokuwiki div.preview { +background-color : #f5f5f5; +margin : 0 0 0 2em; +padding : 4px; +border : 1px dashed #000; +} +div.dokuwiki div.breadcrumbs { +background-color : #f5f5f5; +color : #666; +font-size : 80%; +padding : 0 0 0 4px; +} +div.dokuwiki span.user { +color : #ccc; +font-size : 90%; +} +div.dokuwiki li.minor { +color : #666; +font-style : italic; +} +div.dokuwiki img.media { +margin : 3px; +} +div.dokuwiki img.medialeft { +border : 0; +float : left; +margin : 0 1.5em 0 0; +} +div.dokuwiki img.mediaright { +border : 0; +float : right; +margin : 0 0 0 1.5em; +} +div.dokuwiki img.mediacenter { +border : 0; +display : block; +margin : 0 auto; +} +div.dokuwiki img.middle { +vertical-align : middle; +} +div.dokuwiki acronym { +cursor : help; +border-bottom : 1px dotted #000; +} +div.dokuwiki h1, div.dokuwiki h2, div.dokuwiki h3, div.dokuwiki h4, div.dokuwiki h5 { +color : #000; +background-color : inherit; +font-size : 100%; +font-weight : normal; +margin : 0 0 1em 0; +padding : 0.5em 0 0 0; +border-bottom : 1px solid #8cacbb; +clear : left; +} +div.dokuwiki h1 { +font-size : 160%; +margin-left : 0; +font-weight : bold; +} +div.dokuwiki h2 { +font-size : 150%; +margin-left : 20px; +} +div.dokuwiki h3 { +font-size : 140%; +margin-left : 40px; +border-bottom : none; +font-weight : bold; +} +div.dokuwiki h4 { +font-size : 120%; +margin-left : 60px; +border-bottom : none; +font-weight : bold; +} +div.dokuwiki h5 { +font-size : 100%; +margin-left : 80px; +border-bottom : none; +font-weight : bold; +} +div.dokuwiki div.level1 { +margin-left : 3px; +} +div.dokuwiki div.level2 { +margin-left : 23px; +} +div.dokuwiki div.level3 { +margin-left : 43px; +} +div.dokuwiki div.level4 { +margin-left : 63px; +} +div.dokuwiki div.level5 { +margin-left : 83px; +} +div.dokuwiki ul { +line-height : 1.5em; +list-style-type : square; +list-style-image : none; +margin : 0 0 0.5em 1.5em; +color : #638c9c; +} +div.dokuwiki ol { +line-height : 1.5em; +list-style-image : none; +margin : 0 0 0.5em 1.5em; +color : #638c9c; +font-weight : bold; +} +div.dokuwiki .li { +color : #000; +font-weight : normal; +} +div.dokuwiki ol { +list-style-type : decimal; +} +div.dokuwiki ol ol { +list-style-type : upper-roman; +} +div.dokuwiki ol ol ol { +list-style-type : lower-alpha; +} +div.dokuwiki ol ol ol ol { +list-style-type : lower-greek; +} +div.dokuwiki li.open { +} +div.dokuwiki li.closed { +} +div.dokuwiki blockquote { +border-left : 2px solid #8cacbb; +padding-left : 3px; +} +div.dokuwiki pre { +font-size : 120%; +padding : 0.5em; +border : 1px dashed #8cacbb; +color : #000; +overflow : auto; +} +div.dokuwiki pre.pre { +background-color : #f7f9fa; +} +div.dokuwiki pre.code { +background-color : #f7f9fa; +} +div.dokuwiki code { +font-size : 120%; +} +div.dokuwiki pre.file { +background-color : #dee7ec; +} +div.dokuwiki table.inline { +background-color : #fff; +border-spacing : 0; +border-collapse : collapse; +} +div.dokuwiki table.inline th { +padding : 3px; +border : 1px solid #8cacbb; +background-color : #dee7ec; +} +div.dokuwiki table.inline td { +padding : 3px; +border : 1px solid #8cacbb; +} +div.dokuwiki div.toc { +margin : 1.2em 0 0 2em; +float : right; +width : 200px; +font-size : 80%; +clear : both; +} +div.dokuwiki div.tocheader { +border : 1px solid #8cacbb; +background-color : #dee7ec; +text-align : left; +font-weight : bold; +padding : 3px; +margin-bottom : 2px; +} +div.dokuwiki span.toc_open, div.dokuwiki span.toc_close { +border : 0.4em solid #dee7ec; +float : right; +display : block; +margin : 0.4em 3px 0 0; +} +div.dokuwiki span.toc_open span, div.dokuwiki span.toc_close span { +display : none; +} +div.dokuwiki span.toc_open { +margin-top : 0.4em; +border-top : 0.4em solid #000; +} +div.dokuwiki span.toc_close { +margin-top : 0; +border-bottom : 0.4em solid #000; +} +div.dokuwiki #toc__inside { +border : 1px solid #8cacbb; +background-color : #fff; +text-align : left; +padding : 0.5em 0 0.7em 0; +} +div.dokuwiki ul.toc { +list-style-type : none; +list-style-image : none; +line-height : 1.2em; +padding-left : 1em; +margin : 0; +} +div.dokuwiki ul.toc li { +background : transparent; +padding-left : 0.4em; +} +div.dokuwiki ul.toc li.clear { +background-image : none; +padding-left : 0.4em; +} +div.dokuwiki a.toc:link, div.dokuwiki a.toc:visited { +color : #436976; +} +div.dokuwiki a.toc:hover, div.dokuwiki a.toc:active { +color : #000; +} +div.dokuwiki table.diff { +background-color : #fff; +width : 100%; +} +div.dokuwiki td.diff-blockheader { +font-weight : bold; +} +div.dokuwiki table.diff th { +border-bottom : 1px solid #8cacbb; +font-size : 120%; +width : 50%; +font-weight : normal; +text-align : left; +} +div.dokuwiki table.diff td { +font-family : monospace; +font-size : 100%; +} +div.dokuwiki td.diff-addedline { +background-color : #dfd; +} +div.dokuwiki td.diff-deletedline { +background-color : #ffb; +} +div.dokuwiki td.diff-context { +background-color : #f5f5f5; +} +div.dokuwiki table.diff td.diff-addedline strong, div.dokuwiki table.diff td.diff-deletedline strong { +color : red; +} +div.dokuwiki div.footnotes { +clear : both; +border-top : 1px solid #8cacbb; +padding-left : 1em; +margin-top : 1em; +} +div.dokuwiki div.fn { +font-size : 90%; +} +div.dokuwiki a.fn_top { +vertical-align : super; +font-size : 80%; +} +div.dokuwiki a.fn_bot { +vertical-align : super; +font-size : 80%; +font-weight : bold; +} +div.insitu-footnote { +font-size : 80%; +line-height : 1.2em; +border : 1px solid #8cacbb; +background-color : #f7f9fa; +text-align : left; +padding : 4px; +max-width : 40%; +} +* html .insitu-footnote pre.code, * html .insitu-footnote pre.file { +padding-bottom : 18px; +} +div.dokuwiki .search_result { +margin-bottom : 6px; +padding : 0 10px 0 30px; +} +div.dokuwiki .search_snippet { +color : #ccc; +font-size : 12px; +margin-left : 20px; +} +div.dokuwiki .search_sep { +color : #000; +} +div.dokuwiki .search_hit { +color : #000; +background-color : #ff9; +} +div.dokuwiki strong.search_hit { +font-weight : normal; +} +div.dokuwiki div.search_quickresult { +margin : 0 0 15px 30px; +padding : 0 10px 10px 0; +border-bottom : 1px dashed #8cacbb; +} +div.dokuwiki div.search_quickresult h3 { +margin : 0 0 1em 0; +font-size : 1em; +font-weight : bold; +} +div.dokuwiki ul.search_quickhits { +margin : 0 0 0.5em 1em; +} +div.dokuwiki ul.search_quickhits li { +margin : 0 1em 0 1em; +float : left; +width : 30%; +} +div.footerinc { +text-align : center; +} +.footerinc a img { +border : 0; +} +div.dokuwiki div.ajax_qsearch { +position : absolute; +right : 237px; +width : 200px; +display : none; +font-size : 80%; +line-height : 1.2em; +border : 1px solid #8cacbb; +background-color : #f7f9fa; +text-align : left; +padding : 4px; +} +button.toolbutton { +background-color : #fff; +padding : 0; +margin : 0 1px 0 0; +border : 1px solid #8cacbb; +cursor : pointer; +} +html > body button.toolbutton { +background : #fff; +} +div.picker { +width : 250px; +border : 1px solid #8cacbb; +background-color : #dee7ec; +} +button.pickerbutton { +padding : 0; +margin : 0 1px 1px 0; +border : 0; +background-color : transparent; +font-size : 80%; +cursor : pointer; +} +div.dokuwiki a.spell_error { +color : #f00; +text-decoration : underline; +} +div.dokuwiki div#spell__suggest { +background-color : #fff; +padding : 2px; +border : 1px solid #000; +font-size : 80%; +display : none; +} +div.dokuwiki div#spell__result { +border : 1px solid #8cacbb; +color : #000; +font-size : 14px; +padding : 3px; +background-color : #f7f9fa; +display : none; +} +div.dokuwiki span.spell_noerr { +color : #093; +} +div.dokuwiki span.spell_wait { +color : #06c; +} +div.dokuwiki div.img_big { +float : left; +margin-right : 0.5em; +} +div.dokuwiki dl.img_tags dt { +font-weight : bold; +background-color : #dee7ec; +} +div.dokuwiki dl.img_tags dd { +background-color : #f5f5f5; +} +div.dokuwiki div.imagemeta { +color : #666; +font-size : 70%; +line-height : 95%; +} +div.dokuwiki div.imagemeta img.thumb { +float : left; +margin-right : 0.1em; +} +#media__manager { +height : 100%; +overflow : hidden; +} +#media__left { +width : 30%; +border-right : 1px solid #8cacbb; +height : 100%; +overflow : auto; +position : absolute; +left : 0; +} +#media__right { +width : 69.7%; +height : 100%; +overflow : auto; +position : absolute; +right : 0; +} +#media__manager h1 { +margin : 0; +padding : 0; +margin-bottom : 0.5em; +} +#media__tree img { +float : left; +padding : 0.5em 0.3em 0 0; +} +#media__tree ul { +list-style-type : none; +list-style-image : none; +} +#media__tree li { +clear : left; +list-style-type : none; +list-style-image : none; +} +* html #media__tree li { +border : 1px solid #fff; +} +#media__opts { +padding-left : 1em; +margin-bottom : 0.5em; +} +#media__opts input { +float : left; +position : absolute; +} +* html #media__opts input { +position : static; +} +#media__opts label { +display : block; +float : left; +margin-left : 30px; +} +* html #media__opts label { +margin-left : 10px; +} +#media__opts br { +clear : left; +} +#media__content img.load { +margin : 1em auto; +} +#media__content #scroll__here { +border : 1px dashed #8cacbb; +} +#media__content .odd { +background-color : #f7f9fa; +padding : 0.4em; +} +#media__content .even { +padding : 0.4em; +} +#media__content a.mediafile { +margin-right : 1.5em; +font-weight : bold; +} +#media__content div.detail { +padding : 0.3em 0 0.3em 2em; +} +#media__content div.detail div.thumb { +float : left; +width : 130px; +text-align : center; +margin-right : 0.4em; +} +#media__content img.btn { +vertical-align : text-bottom; +} +#media__content div.example { +color : #666; +margin-left : 1em; +} +#media__content div.upload { +font-size : 90%; +padding : 0 0.5em 0.5em 0.5em; +} +#media__content form.upload { +display : block; +border-bottom : 1px solid #8cacbb; +padding : 0 0.5em 1em 0.5em; +} +#media__content form.upload fieldset { +padding : 0; +margin : 0; +border : none; +width : auto; +} +#media__content form.upload p { +clear : left; +text-align : left; +padding : 0.25em 0; +margin : 0; +line-height : 1em; +} +#media__content form.upload label { +float : left; +width : 30%; +} +#media__content form.upload label.check { +float : none; +width : auto; +} +#media__content form.upload input.check { +margin-left : 30%; +} +#media__content form.meta { +display : block; +padding : 0 0 1em 0; +} +#media__content form.meta label { +display : block; +width : 25%; +float : left; +font-weight : bold; +margin-left : 1em; +clear : left; +} +#media__content form.meta .edit { +font : 100% "Lucida Grande", Verdana, Lucida, Helvetica, Arial, sans-serif; +float : left; +width : 70%; +padding-right : 0; +padding-left : 0.2em; +margin : 2px; +} +#media__content form.meta textarea.edit { +height : 8em; +} +#media__content form.meta div.metafield { +clear : left; +} +#media__content form.meta div.buttons { +clear : left; +margin-left : 20%; +padding-left : 1em; +} \ No newline at end of file diff --git a/SDK/sdk-readme.html b/SDK/sdk-readme.html new file mode 100644 index 0000000..e570171 --- /dev/null +++ b/SDK/sdk-readme.html @@ -0,0 +1,414 @@ + + + + + help:sdk-readme + + + + + + + + +
+ + + + +

foobar2000 v1.3 SDK readme

+
+ +
+ +

Compatibility

+
+ +

+ Components built with this SDK are compatible with foobar2000 1.3. They are not compatible with any earlier versions (will fail to load), and not guaranteed to be compatible with any future versions, though upcoming releases will aim to maintain compatibility as far as possible without crippling newly added functionality. +

+ +
+ +

Microsoft Visual Studio compatibility

+
+ +

+ This SDK contains project files for Visual Studio 2010. This version of VS has been used for foobar2000 core development for a long time and it is the safest version to use. +

+ +

+VS2012, 2013 and 2015 currently produce incorrect output in release mode on foobar2000 code - see forum thread for details. You can mitigate this issue by compiling all affected code (foobar2000 SDK code along with everything that uses foobar2000 SDK classes) with /d2notypeopt option. +

+ +
+ +

Version 1.3 notes

+
+ +

+foobar2000 version 1.3 uses different metadb behavior semantics than older versions, to greatly improve the performance of multithreaded operation by reducing the time spent within global metadb locks. +

+ +

+Any methods that: +

+
    +
  • Lock the metadb - database_lock() etc
    +
  • +
  • Retrieve direct pointers to metadb info - get_info_locked() style
    +
  • +
+ +

+ .. are now marked deprecated and implemented only for backwards compatibility; they should not be used in any new code. +

+ +

+It is recommended that you change your existing code using these to obtain track information using new get_info_ref() style methods for much better performance as these methods have minimal overhead and require no special care when used in multiple concurrent threads. +

+ +
+ +

Basic usage

+
+ +

+ Each component must link against: +

+
    +
  • foobar2000_SDK project (contains declarations of services and various service-specific helper code)
    +
  • +
  • foobar2000_component_client project (contains DLL entrypoint)
    +
  • +
  • shared.dll (various helper code, mainly win32 function wrappers taking UTF-8 strings)
    +
  • +
  • PFC (non-OS-specific helper class library)
    +
  • +
+ +

+Optionally, components can use helper libraries with various non-critical code that is commonly reused across various foobar2000 components: +

+
    +
  • foobar2000_SDK_helpers - a library of various helper code commonly used by foobar2000 components.
    +
  • +
  • foobar2000_ATL_helpers - another library of various helper code commonly used by foobar2000 components; requires WTL.
    +
  • +
+ +

+ Foobar2000_SDK, foobar2000_component_client and PFC are included in sourcecode form; you can link against them by adding them to your workspace and using dependencies. To link against shared.dll, you must add “shared.lib” to linker input manually. +

+ +

+Component code should include the following header files: +

+
    +
  • foobar2000.h from SDK - do not include other headers from the SDK directory directly, they're meant to be referenced by foobar2000.h only; it also includes PFC headers and shared.dll helper declaration headers.
    +
  • +
  • Optionally: helpers.h from helpers directory (foobar2000_SDK_helpers project) - a library of various helper code commonly used by foobar2000 components.
    +
  • +
  • Optionally: ATLHelpers.h from ATLHelpers directory (foobar2000_ATL_helpers project) - another library of various helper code commonly used by foobar2000 components; requires WTL. Note that ATLHelpers.h already includes SDK/foobar2000.h and helpers/helpers.h so you can replace your other include lines with a reference to ATLHelpers.h.
    +
  • +
+ +
+ +

Structure of a component

+
+ +

+ A component is a DLL that implements one or more entrypoint services and interacts with services provided by other components. +

+ +
+ +

Services

+
+ +

+ A service type is an interface class, deriving directly or indirectly from service_base class. A service type class must not have any data members; it can only provide virtual methods (to be overridden by service implementation), helper non-virtual methods built around virtual methods, static helper methods, and constants / enums. Each service interface class must have a static class_guid member, used for identification when enumerating services or querying for supported functionality. A service type declaration should declare a class with public virtual/helper/static methods, and use FB2K_MAKE_SERVICE_INTERFACE() / FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT() macro to implement standard service behaviors for the class; additionally, class_guid needs to be defined outside class declaration (e.g. const GUID someclass::class_guid = {….}; ). Note that most of components will not declare their own service types, they will only implement existing ones declared in the SDK. +

+ +

+A service implementation is a class derived from relevant service type class, implementing virtual methods declared by service type class. Note that service implementation class does not implement virtual methods declared by service_base; those are implemented by service type declaration framework (service_query) or by instantiation framework (service_add_ref / service_release). Service implementation classes are instantiated using service_factory templates in case of entrypoint services (see below), or using service_impl_t template and operator new: ”myserviceptr = new service_impl_t<myservice_impl>(params);”. +

+ +

+Each service object provides reference counter features and (service_add_ref() and service_release() methods) as well as a method to query for extended functionality (service_query() method). Those methods are implemented by service framework and should be never overridden by service implementations. These methods should also never be called directly - reference counter methods are managed by relevant autopointer templates, service_query_t function template should be used instead of calling service_query directly, to ensure type safety and correct type conversions. +

+ +
+ +

Entrypoint services

+
+ +

+ An entrypoint service type is a special case of a service type that can be registered using service_factory templates, and then accessed from any point of service system (excluding DLL startup/shutdown code, such as code inside static object constructors/destructors). An entrypoint service type class must directly derive from service_base. +

+ +

+Registered entrypoint services can be accessed using: +

+
    +
  • For services types with variable number of implementations registered: service_enum_t<T> template, service_class_helper_t<T> template, etc, e.g.
    service_enum_t<someclass> e; service_ptr_t<someclass> ptr; while(e.next(ptr)) ptr->dosomething();
    +
  • +
  • For services types with single always-present implementation registered - such as core services like playlist_manager - using static_api_ptr_t<T> template, e.g.:
    static_api_ptr_t<someclass> api; api->dosomething(); api->dosomethingelse();
    +
  • +
  • Using per-service-type defined static helper functions, e.g. someclass::g_dosomething() - those use relevant service enumeration methods internally.
    +
  • +
+ +

+ An entrypoint service type must use FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT() macro to implement standard entrypoint service behaviors, as opposed to all other service types that use FB2K_MAKE_SERVICE_INTERFACE() macro instead. +

+ +

+You can register your own entrypoint service implementations using either service_factory_t or service_factory_single_t template - the difference between the two is that the former instantiates the class on demand, while the latter keeps a single static instance and returns references to it when requested; the latter is faster but usable only for things that have no per-instance member data to maintain. Each service_factory_t / service_factory_single_t instance should be a static variable, such as: ”static service_factory_t<myclass> g_myclass_factory;”. +

+ +

+Certain service types require custom service_factory helper templates to be used instead of standard service_factory_t / service_factory_single_t templates; see documentation of specific service type for exact info about registering. +

+ +

+A typical entrypoint service implementation looks like this: +

+
class myservice_impl : public myservice {
+public:
+	void dosomething() {....};
+	void dosomethingelse(int meh) {...};
+};
+static service_factory_single_t<myservice_impl> g_myservice_impl_factory;
+
+ +

Service extensions

+
+ +

+ Additional methods can be added to any service type, by declaring a new service type class deriving from service type class you want to extend. For example: +

+
class myservice : public service_base { public: virtual void dosomething() = 0; FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(myservice); };
+class myservice_v2 : public myservice { public: virtual void dosomethingelse() = 0; FB2K_MAKE_SERVICE_INTERFACE(myservice_v2, myservice); };
+

+ In such scenario, to query whether a myservice instance is a myservice_v2 and to retrieve myservice_v2 pointer, use service_query functionality: +

+
service_ptr_t<myservice> ptr;
+(...)
+service_ptr_t<myservice_v2> ptr_ex;
+if (ptr->service_query_t(ptr_ex)) { /* ptr_ex is a valid pointer to myservice_v2 interface of our myservice instance */ (...) }
+else {/* this myservice implementation does not implement myservice_v2 */ (...) }
+
+ +

Autopointer template use

+
+ +

+ When performing most kinds of service operations, service_ptr_t<T> template should be used rather than working with service pointers directly; it automatically manages reference counter calls, ensuring that the service object is deleted when it is no longer referenced. Additionally, static_api_ptr_t<T> can be used to automatically acquire/release a pointer to single-implementation entrypoint service, such as one of standard APIs like playlist_manager. +

+ +
+ +

Exception use

+
+ +

+ Most of API functions use C++ exceptions to signal failure conditions. All used exception classes must derive from std::exception (which pfc::exception is typedef'd to); this design allows various instances of code to use single catch() line to get human-readable description of the problem to display. +

+ +

+Additionally, special subclasses of exceptions are defined for use in specific conditions, such as exception_io for I/O failures. As a result, you must provide an exception handler whenever you invoke any kind of I/O code that may fail, unless in specific case calling context already handles exceptions (e.g. input implementation code - any exceptions should be forwarded to calling context, since exceptions are a part of input API). +

+ +

+Implementations of global callback services such as playlist_callback, playback_callback or library_callback must not throw unhandled exceptions; behaviors in case they do are undefined (app termination is to be expected). +

+ +
+ +

Storing configuration

+
+ +

+ In order to create your entries in the configuration file, you must instantiate some objects that derive from cfg_var class. Those can be either predefined classes (cfg_int, cfg_string, etc) or your own classes implementing relevant methods. +

+ +

+Each cfg_var instance has a GUID assigned, to identify its configuration file entry. The GUID is passed to its constructor (which implementations must take care of, typically by providing a constructor that takes a GUID and forwards it to cfg_var constructor). +

+ +

+Note that cfg_var objects can only be instantiated statically (either directly as static objects, or as members of other static objects). Additionally, you can create configuration data objects that can be accessed by other components, by implementing config_object service. Some standard configuration variables can be also accessed using config_object interface. +

+ +
+ +

Use of global callback services

+
+ +

+ Multiple service classes presented by the SDK allow your component to receive notifications about various events: +

+
    +
  • file_operation_callback - tracking file move/copy/delete operations.
    +
  • +
  • library_callback - tracking Media Library content changes.
    +
  • +
  • metadb_io_callback - tracking tag read / write operations altering cached/displayed media information.
    +
  • +
  • play_callback - tracking playback related events.
    +
  • +
  • playback_statistics_collector - collecting information about played tracks.
    +
  • +
  • playlist_callback, playlist_callback_single - tracking playlist changes (the latter tracks only active playlist changes).
    +
  • +
  • playback_queue_callback - tracking playback queue changes.
    +
  • +
  • titleformat_config_callback - tracking changes of title formatting configuration.
    +
  • +
  • ui_drop_item_callback - filtering items dropped into the UI.
    +
  • +
+ +

+All of global callbacks operate only within main app thread, allowing easy cooperation with windows GUI - for an example, you perform playlist view window repainting directly from your playlist_callback implementation. +

+ +
+ +

Global callback recursion issues

+
+ +

+There are restrictions on things that are legal to call from within global callbacks. For an example, you can't modify a playlist from inside a playlist callback, because there are other registered callbacks tracking playlist changes that haven't been notified about the change being currently processed yet. +

+ +

+You must not enter modal message loops from inside global callbacks, as those allow any unrelated code (queued messages, user input, etc.) to be executed, without being aware that a global callback is being processed. Certain global API methods such as metadb_io::load_info_multi or threaded_process::run_modal enter modal loops when called. Use main_thread_callback service to avoid this problem and delay execution of problematic code. +

+ +

+You should also avoid firing a cross-thread SendMessage() inside global callbacks as well as performing any operations that dispatch global callbacks when handling a message that was sent through a cross-thread SendMessage(). Doing so may result in rare unwanted recursions - SendMessage() call will block the calling thread and immediately process any incoming cross-thread SendMessage() messages. If you're handling a cross-thread SendMessage() and need to perform such operation, delay it using PostMessage() or main_thread_callback. +

+ +
+ +

Service class design guidelines (advanced)

+
+ +

+ This chapter describes things you should keep on your mind when designing your own service type classes. Since 99% of components will only implement existing service types rather than adding their own cross-DLL-communication protocols, you can probably skip reading this chapter. +

+ +
+ +

Cross-DLL safety

+
+ +

+ It is important that all function parameters used by virtual methods of services are cross-DLL safe (do not depend on compiler-specific or runtime-specific behaviors, so no unexpected behaviors occur when calling code is built with different compiler/runtime than callee). To achieve this, any classes passed around must be either simple objects with no structure that could possibly vary with different compilers/runtimes (i.e. make sure that any memory blocks are freed on the side that allocated them); easiest way to achieve this is to reduce all complex data objects or classes passed around to interfaces with virtual methods, with implementation details hidden from callee. For an example, use pfc::string_base& as parameter to a function that is meant to return variable-length strings. +

+ +
+ +

Entrypoint service efficiency

+
+ +

+ When designing an entrypoint service interface meant to have multiple different implementations, you should consider making it possible for all its implementations to use service_factory_single_t (i.e. no per-instance member data); by e.g. moving functionality that needs multi-instance operation to a separate service type class that is created on-demand by one of entrypoint service methods. For example: +

+
class myservice : public service_base {
+public:
+	//this method accesses per-instance member data of the implementation class
+	virtual void workerfunction(const void * p_databuffer,t_size p_buffersize) = 0;
+	//this method is used to determine which implementation can be used to process specific data stream.
+	virtual bool queryfunction(const char * p_dataformat) = 0;
+ 
+	FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(myservice);
+};
+(...)
+service_ptr_t<myservice> findservice(const char * p_dataformat) {
+	service_enum_t<myservice> e; service_ptr_t<myservice> ptr;
+	//BOTTLENECK, this dynamically instantiates the service for each query.
+	while(e.next(ptr)) {
+		if (ptr->queryfunction(p_dataformat)) return ptr;
+	}
+	throw exception_io_data();
+}
+

+.. should be changed to: +

+
//no longer an entrypoint service - use myservice::instantiate to get an instance instead.
+class myservice_instance : public service_base {
+public:
+	virtual void workerfunction(const void * p_databuffer,t_size p_buffersize) = 0;
+	FB2K_MAKE_SERVICE_INTERFACE(myservice_instance,service_base);
+};
+ 
+class myservice : public service_base {
+public:
+	//this method is used to determine which implementation can be used to process specific data stream.
+	virtual bool queryfunction(const char * p_dataformat) = 0;
+	virtual service_ptr_t<myservice_instance> instantiate() = 0;
+	FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(myservice);
+};
+ 
+template<typename t_myservice_instance_impl>
+class myservice_impl_t : public myservice {
+public:
+	//implementation of myservice_instance must provide static bool g_queryformatfunction(const char*);
+	bool queryfunction(const char * p_dataformat) {return t_myservice_instance_impl::g_queryfunction(p_dataformat);}
+	service_ptr_t<myservice_instance> instantiate() {return new service_impl_t<t_myservice_instance_impl>();}
+};
+ 
+template<typename t_myservice_instance_impl> class myservice_factory_t :
+	public service_factory_single_t<myservice_impl_t<t_myservice_instance_impl> > {};
+//usage: static myservice_factory_t<myclass> g_myclass_factory;
+ 
+(...)
+ 
+service_ptr_t<myservice_instance> findservice(const char * p_dataformat) {
+	service_enum_t<myservice> e; service_ptr_t<myservice> ptr;
+	//no more bottleneck, enumerated service does not perform inefficient operations when requesting an instance.
+	while(e.next(ptr)) {
+		//"inefficient" part is used only once, with implementation that actually supports what we request.
+		if (ptr->queryfunction(p_dataformat)) return ptr->instantiate();
+	}
+	throw exception_io_data();
+}
+
+
+ + diff --git a/clean.sh b/clean.sh index f368ed2..306f635 100644 --- a/clean.sh +++ b/clean.sh @@ -1,3 +1,4 @@ find -name Debug | xargs rm -rf find -name Release | xargs rm -rf +find -name x64 | xargs rm -rf rm -rf .vs *.sdf diff --git a/foo_thbgm.sln b/foo_thbgm.sln index aef884f..7b0c3ed 100644 --- a/foo_thbgm.sln +++ b/foo_thbgm.sln @@ -1,5 +1,5 @@  -Microsoft Visual Studio Solution File, Format Version 11.00 +Microsoft Visual Studio Solution File, Format Version 12.00 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "foo_thbgm", "src\foo_thbgm.vcxproj", "{A03D36AE-0B97-4B77-AEBB-05B1A6B80287}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pfc", "SDK\pfc\pfc.vcxproj", "{EBFFFB4E-261D-44D3-B89C-957B31A0BF9C}" @@ -13,29 +13,51 @@ EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 Release|Win32 = Release|Win32 + Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {A03D36AE-0B97-4B77-AEBB-05B1A6B80287}.Debug|Win32.ActiveCfg = Debug|Win32 {A03D36AE-0B97-4B77-AEBB-05B1A6B80287}.Debug|Win32.Build.0 = Debug|Win32 + {A03D36AE-0B97-4B77-AEBB-05B1A6B80287}.Debug|x64.ActiveCfg = Debug|x64 + {A03D36AE-0B97-4B77-AEBB-05B1A6B80287}.Debug|x64.Build.0 = Debug|x64 {A03D36AE-0B97-4B77-AEBB-05B1A6B80287}.Release|Win32.ActiveCfg = Release|Win32 {A03D36AE-0B97-4B77-AEBB-05B1A6B80287}.Release|Win32.Build.0 = Release|Win32 + {A03D36AE-0B97-4B77-AEBB-05B1A6B80287}.Release|x64.ActiveCfg = Release|x64 + {A03D36AE-0B97-4B77-AEBB-05B1A6B80287}.Release|x64.Build.0 = Release|x64 {EBFFFB4E-261D-44D3-B89C-957B31A0BF9C}.Debug|Win32.ActiveCfg = Debug|Win32 {EBFFFB4E-261D-44D3-B89C-957B31A0BF9C}.Debug|Win32.Build.0 = Debug|Win32 + {EBFFFB4E-261D-44D3-B89C-957B31A0BF9C}.Debug|x64.ActiveCfg = Debug|x64 + {EBFFFB4E-261D-44D3-B89C-957B31A0BF9C}.Debug|x64.Build.0 = Debug|x64 {EBFFFB4E-261D-44D3-B89C-957B31A0BF9C}.Release|Win32.ActiveCfg = Release|Win32 {EBFFFB4E-261D-44D3-B89C-957B31A0BF9C}.Release|Win32.Build.0 = Release|Win32 + {EBFFFB4E-261D-44D3-B89C-957B31A0BF9C}.Release|x64.ActiveCfg = Release|x64 + {EBFFFB4E-261D-44D3-B89C-957B31A0BF9C}.Release|x64.Build.0 = Release|x64 {E8091321-D79D-4575-86EF-064EA1A4A20D}.Debug|Win32.ActiveCfg = Debug|Win32 {E8091321-D79D-4575-86EF-064EA1A4A20D}.Debug|Win32.Build.0 = Debug|Win32 + {E8091321-D79D-4575-86EF-064EA1A4A20D}.Debug|x64.ActiveCfg = Debug|x64 + {E8091321-D79D-4575-86EF-064EA1A4A20D}.Debug|x64.Build.0 = Debug|x64 {E8091321-D79D-4575-86EF-064EA1A4A20D}.Release|Win32.ActiveCfg = Release|Win32 {E8091321-D79D-4575-86EF-064EA1A4A20D}.Release|Win32.Build.0 = Release|Win32 + {E8091321-D79D-4575-86EF-064EA1A4A20D}.Release|x64.ActiveCfg = Release|x64 + {E8091321-D79D-4575-86EF-064EA1A4A20D}.Release|x64.Build.0 = Release|x64 {EE47764E-A202-4F85-A767-ABDAB4AFF35F}.Debug|Win32.ActiveCfg = Debug|Win32 {EE47764E-A202-4F85-A767-ABDAB4AFF35F}.Debug|Win32.Build.0 = Debug|Win32 + {EE47764E-A202-4F85-A767-ABDAB4AFF35F}.Debug|x64.ActiveCfg = Debug|x64 + {EE47764E-A202-4F85-A767-ABDAB4AFF35F}.Debug|x64.Build.0 = Debug|x64 {EE47764E-A202-4F85-A767-ABDAB4AFF35F}.Release|Win32.ActiveCfg = Release|Win32 {EE47764E-A202-4F85-A767-ABDAB4AFF35F}.Release|Win32.Build.0 = Release|Win32 + {EE47764E-A202-4F85-A767-ABDAB4AFF35F}.Release|x64.ActiveCfg = Release|x64 + {EE47764E-A202-4F85-A767-ABDAB4AFF35F}.Release|x64.Build.0 = Release|x64 {71AD2674-065B-48F5-B8B0-E1F9D3892081}.Debug|Win32.ActiveCfg = Debug|Win32 {71AD2674-065B-48F5-B8B0-E1F9D3892081}.Debug|Win32.Build.0 = Debug|Win32 + {71AD2674-065B-48F5-B8B0-E1F9D3892081}.Debug|x64.ActiveCfg = Debug|x64 + {71AD2674-065B-48F5-B8B0-E1F9D3892081}.Debug|x64.Build.0 = Debug|x64 {71AD2674-065B-48F5-B8B0-E1F9D3892081}.Release|Win32.ActiveCfg = Release|Win32 {71AD2674-065B-48F5-B8B0-E1F9D3892081}.Release|Win32.Build.0 = Release|Win32 + {71AD2674-065B-48F5-B8B0-E1F9D3892081}.Release|x64.ActiveCfg = Release|x64 + {71AD2674-065B-48F5-B8B0-E1F9D3892081}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/config.cc b/src/config.cc index e4f9e46..413fd0d 100644 --- a/src/config.cc +++ b/src/config.cc @@ -28,8 +28,8 @@ int WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { WS_CHILD | WS_VISIBLE, 5, 5, - 275, - 70, + 400, + 100, hWnd, (HMENU)1000, _hInstance, @@ -38,10 +38,10 @@ int WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { "Button", "OK(&K)", WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON, - 285, + 400, 5, - 65, - 20, + 150, + 50, hWnd, (HMENU)IDOK, _hInstance, @@ -50,10 +50,10 @@ int WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { "Button", "Cancel(&C)", WS_CHILD | WS_VISIBLE, - 285, - 30, - 65, - 20, + 400, + 55, + 150, + 50, hWnd, (HMENU)IDCANCEL, _hInstance, @@ -63,16 +63,16 @@ int WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { "", _nEditStyle, 5, - 80, - 350, - 20, + 60, + 300, + 30, hWnd, (HMENU)2000, _hInstance, 0); ::SendMessage(_hEdit, EM_SETLIMITTEXT, _nMaxLine, 0); - _hWndFont = ::CreateFont(12, - 6, + _hWndFont = ::CreateFont(20, + 12, 0, 0, 12, @@ -137,8 +137,8 @@ HWND _CreateWindow(HINSTANCE hInst) { WS_DLGFRAME | WS_SYSMENU | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, - 365, - 130, + 600, + 200, _hParent, 0, hInst, diff --git a/src/foo_thbgm.vcxproj b/src/foo_thbgm.vcxproj index e9ab07a..649049b 100644 --- a/src/foo_thbgm.vcxproj +++ b/src/foo_thbgm.vcxproj @@ -5,10 +5,18 @@ Debug Win32 + + Debug + x64 + Release Win32 + + Release + x64 + {A03D36AE-0B97-4B77-AEBB-05B1A6B80287} @@ -25,6 +33,13 @@ Unicode v143 + + DynamicLibrary + false + false + Unicode + v143 + DynamicLibrary false @@ -33,15 +48,29 @@ v143 true + + DynamicLibrary + false + false + Unicode + v143 + true + + + + + + + false @@ -49,11 +78,21 @@ false $(SolutionDir)$(Configuration)\components\ + + false + false + false + false false false + + false + false + false + Level3 @@ -63,11 +102,28 @@ ../SDK/foobar2000;%(AdditionalIncludeDirectories) - MultiThreadedDebug + MultiThreadedDebugDLL true - ../SDK/foobar2000/shared/shared.lib;%(AdditionalDependencies) + ../SDK/foobar2000/shared/shared-Win32.lib;%(AdditionalDependencies) + $(OutDir)foo_thbgm$(TargetExt) + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;FOO_THBGM_EXPORTS;%(PreprocessorDefinitions) + NotUsing + ../SDK/foobar2000;%(AdditionalIncludeDirectories) + + + MultiThreadedDebugDLL + + + true + ../SDK/foobar2000/shared/shared-x64.lib;%(AdditionalDependencies) $(OutDir)foo_thbgm$(TargetExt) @@ -84,7 +140,36 @@ true Cdecl true - MultiThreaded + MultiThreadedDLL + true + true + Fast + false + true + + + false + ../SDK/foobar2000/shared/shared-Win32.lib;%(AdditionalDependencies) + Windows + true + true + UseLinkTimeCodeGeneration + + + + + Level3 + WIN32;NDEBUG;_WINDOWS;_USRDLL;FOO_THBGM_EXPORTS%(PreprocessorDefinitions) + NotUsing + AnySuitable + Speed + ../SDK/foobar2000;%(AdditionalIncludeDirectories) + MaxSpeed + false + true + Cdecl + true + MultiThreadedDLL true true Fast @@ -93,7 +178,7 @@ false - ../SDK/foobar2000/shared/shared.lib;%(AdditionalDependencies) + ../SDK/foobar2000/shared/shared-x64.lib;%(AdditionalDependencies) Windows true true diff --git a/src/foo_thbgm.vcxproj.user b/src/foo_thbgm.vcxproj.user index cf9a361..cd52730 100644 --- a/src/foo_thbgm.vcxproj.user +++ b/src/foo_thbgm.vcxproj.user @@ -5,4 +5,9 @@ WindowsLocalDebugger $(SolutionDir)$(Configuration)\ + + foobar2000.exe + WindowsLocalDebugger + $(SolutionDir)$(Configuration)\ + \ No newline at end of file