diff --git a/engine/foundation/BUILD.gn b/engine/foundation/BUILD.gn index 3d7a8b4b05d7cc94ff14aae0cc4a036069f09be1..45a12d127e0b6bdeb3723a2bd7ca60c8f18d5d7f 100644 --- a/engine/foundation/BUILD.gn +++ b/engine/foundation/BUILD.gn @@ -13,6 +13,7 @@ # import("//build/lite/config/component/lite_component.gni") +import("//build/lite/config/subsystem/multimedia/config.gni") histreamer_foundation_src = [ "osal/thread/task.cpp", @@ -46,12 +47,23 @@ lite_library("histreamer_foundation") { public_deps = [ "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", "//foundation/multimedia/utils/lite:media_common", - "//third_party/bounds_checking_function:libsec_shared", - ] - cflags = [ - "-O2", - "-fPIC", - "-Wall", ] + if (ohos_kernel_type == "liteos_m") { + public_deps += [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_static", + "//third_party/bounds_checking_function:libsec_static", + ] + } else { + public_deps += [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//third_party/bounds_checking_function:libsec_shared", + ] + } + cflags = [ "-O2" ] cflags_cc = cflags + if (defined(config_ohos_multimedia_histreamer_stack_size) && + config_ohos_multimedia_histreamer_stack_size > 0) { + defines = + [ "THREAD_STACK_SIZE=$config_ohos_multimedia_histreamer_stack_size" ] + } } diff --git a/engine/foundation/error_code.h b/engine/foundation/error_code.h index 83451292516d238075ac7c48b5643bfe9cab23b1..ff3e2b732c7900afdec8b0115e23703380b5e3b6 100644 --- a/engine/foundation/error_code.h +++ b/engine/foundation/error_code.h @@ -18,32 +18,29 @@ namespace OHOS { namespace Media { -enum ErrorCode { +enum struct ErrorCode : int32_t { + END_OF_STREAM = 1, SUCCESS = 0, - UNKNOWN_ERROR, - UNIMPLEMENT, - BUSY, - NOT_FOUND, - INVALID_PARAM_TYPE, - INVALID_PARAM_VALUE, - INVALID_OPERATION, - INVALID_SOURCE, - INVALID_STREAM_INDEX, - INITIALIZATION_FAILURE, - NULL_POINTER_ERROR, - ACTIVATE_ERROR, - NEGOTIATE_ERROR, - LOAD_URI_FAILED, - END_OF_STREAM, - PLUGIN_NOT_FOUND, - PORT_NOT_FOUND, - PORT_UNEXPECTED, - ASYNC, - ERROR_STATE, - PARSE_META_FAILED, - SEEK_FAILURE, - ALREADY_EXISTS, - ERROR_TIMEOUT + ERROR_UNKNOWN = -1, + ERROR_UNIMPLEMENTED = -2, + ERROR_NOT_FOUND = -3, + ERROR_INVALID_PARAM_TYPE = -4, + ERROR_INVALID_PARAM_VALUE = -5, + ERROR_INVALID_OPERATION = -6, + ERROR_INVALID_SOURCE = -7, + ERROR_INVALID_STREAM_INDEX = -8, + ERROR_INITIALIZATION_FAILURE = -9, + ERROR_NULL_POINTER = -10, + ERROR_ACTIVATE = -11, + ERROR_NEGOTIATE_FAILED = -12, + ERROR_LOAD_URI_FAILED = -13, + ERROR_PLUGIN_NOT_FOUND = -14, + ERROR_PORT_UNEXPECTED = -15, + ERROR_STATE = -16, + ERROR_PARSE_META_FAILED = -17, + ERROR_SEEK_FAILURE = -18, + ERROR_ALREADY_EXISTS = -19, + ERROR_TIMEOUT = -20 }; } // namespace Media } // namespace OHOS diff --git a/engine/foundation/log.h b/engine/foundation/log.h index 025cf4f5a46062e5b70c5c30ede217573ce5c556..7e96cc5729a84cf1c37d196c2ebaf7f223d8e81d 100644 --- a/engine/foundation/log.h +++ b/engine/foundation/log.h @@ -76,7 +76,7 @@ inline std::string MediaGetFileName(std::string file) #define FAIL_RETURN(exec) \ do { \ ErrorCode ret = (exec); \ - if (ret != SUCCESS) { \ + if (ret != ErrorCode::SUCCESS) { \ MEDIA_LOG_E("FAIL_RETURN on ErrorCode(%d).", ret); \ return ret; \ } \ @@ -87,7 +87,7 @@ inline std::string MediaGetFileName(std::string file) #define FAIL_LOG(exec) \ do { \ ErrorCode ret = (exec); \ - if (ret != SUCCESS) { \ + if (ret != ErrorCode::SUCCESS) { \ MEDIA_LOG_E("FAIL_LOG on ErrorCode(%d).", ret); \ } \ } while (0) @@ -136,7 +136,7 @@ inline std::string MediaGetFileName(std::string file) #endif #define RETURN_TARGET_ERR_MESSAGE_LOG_IF_FAIL(err, returnErr, msg) \ - if ((err) != SUCCESS) { \ + if ((err) != ErrorCode::SUCCESS) { \ MEDIA_LOG_E(msg); \ return returnErr; \ } diff --git a/engine/foundation/osal/base/synchronizer.h b/engine/foundation/osal/base/synchronizer.h index 9a6b16211cd26a4327e3e79318a0a16ec88c877e..775a2af48e53aa9b3160ac6b520a46ceacebd6fe 100644 --- a/engine/foundation/osal/base/synchronizer.h +++ b/engine/foundation/osal/base/synchronizer.h @@ -16,6 +16,7 @@ #ifndef HISTREAMER_FOUNDATION_OSAL_BASE_SYNCHRONIZER_H #define HISTREAMER_FOUNDATION_OSAL_BASE_SYNCHRONIZER_H +#include #include #include #include @@ -27,7 +28,7 @@ namespace OHOS { namespace Media { namespace OSAL { -template +template class Synchronizer { public: explicit Synchronizer(std::string name) : name_(std::move(name)) @@ -40,20 +41,27 @@ public: virtual ~Synchronizer() = default; - void Wait(SyncIdType syncId) + void Wait(SyncIdType syncId, const std::function& asyncOps) { MEDIA_LOG_I("Synchronizer %s Wait for %d", name_.c_str(), static_cast(syncId)); - OSAL::ScopedLock lock(mutex_); - waitSet_.insert(syncId); - cv_.Wait(lock, [this, syncId] { return syncMap_.find(syncId) != syncMap_.end(); }); - syncMap_.erase(syncId); + if (asyncOps) { + OSAL::ScopedLock lock(mutex_); + waitSet_.insert(syncId); + asyncOps(); + cv_.Wait(lock, [this, syncId] { return syncMap_.find(syncId) != syncMap_.end(); }); + syncMap_.erase(syncId); + } } - bool WaitFor(SyncIdType syncId, int timeoutMs) + bool WaitFor(SyncIdType syncId, const std::function& asyncOps, int timeoutMs) { MEDIA_LOG_I("Synchronizer %s Wait for %d, timeout: %d", name_.c_str(), static_cast(syncId), timeoutMs); + if (!asyncOps) { + return false; + } OSAL::ScopedLock lock(mutex_); waitSet_.insert(syncId); + asyncOps(); auto rtv = cv_.WaitFor(lock, timeoutMs, [this, syncId] { return syncMap_.find(syncId) != syncMap_.end(); }); if (rtv) { syncMap_.erase(syncId); @@ -63,21 +71,28 @@ public: return rtv; } - void Wait(SyncIdType syncId, ResultType& result) + void Wait(SyncIdType syncId, const std::function& asyncOps, ResultType& result) { MEDIA_LOG_I("Synchronizer %s Wait for %d", name_.c_str(), static_cast(syncId)); - OSAL::ScopedLock lock(mutex_); - waitSet_.insert(syncId); - cv_.Wait(lock, [this, syncId] { return syncMap_.find(syncId) != syncMap_.end(); }); - result = syncMap_[syncId]; - syncMap_.erase(syncId); + if (asyncOps) { + OSAL::ScopedLock lock(mutex_); + waitSet_.insert(syncId); + asyncOps(); + cv_.Wait(lock, [this, syncId] { return syncMap_.find(syncId) != syncMap_.end(); }); + result = syncMap_[syncId]; + syncMap_.erase(syncId); + } } - bool WaitFor(SyncIdType syncId, int timeoutMs, ResultType& result) + bool WaitFor(SyncIdType syncId, const std::function& asyncOps, int timeoutMs, ResultType& result) { MEDIA_LOG_I("Synchronizer %s Wait for %d, timeout: %d", name_.c_str(), static_cast(syncId), timeoutMs); + if (!asyncOps) { + return false; + } OSAL::ScopedLock lock(mutex_); waitSet_.insert(syncId); + asyncOps(); auto rtv = cv_.WaitFor(lock, timeoutMs, [this, syncId] { return syncMap_.find(syncId) != syncMap_.end(); }); if (rtv) { result = syncMap_[syncId]; diff --git a/engine/foundation/osal/thread/condition_variable.cpp b/engine/foundation/osal/thread/condition_variable.cpp index ca60cb68501189730b8152e765f1fed6e6b05ae7..13f1c7a1097df148ca313a4c9d8cb27955bfd063 100644 --- a/engine/foundation/osal/thread/condition_variable.cpp +++ b/engine/foundation/osal/thread/condition_variable.cpp @@ -29,10 +29,12 @@ ConditionVariable::ConditionVariable() noexcept : condInited_(true) { pthread_condattr_t attr; pthread_condattr_init(&attr); +#ifndef __LITEOS_M__ #ifdef USING_CLOCK_REALTIME pthread_condattr_setclock(&attr, CLOCK_REALTIME); #else pthread_condattr_setclock(&attr, CLOCK_MONOTONIC); +#endif #endif int rtv = pthread_cond_init(&cond_, &attr); if (rtv != 0) { @@ -83,4 +85,4 @@ bool ConditionVariable::WaitFor(ScopedLock& lock, int timeoutMs) } } // namespace OSAL } // namespace Media -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/engine/foundation/osal/thread/task.cpp b/engine/foundation/osal/thread/task.cpp index d93cfe148fb8e97cd0c998636fbe6fdb3a9e78f9..5424de1f418ca57e4bf8b12b1c0b26cfb77d1fda 100644 --- a/engine/foundation/osal/thread/task.cpp +++ b/engine/foundation/osal/thread/task.cpp @@ -23,14 +23,18 @@ namespace OHOS { namespace Media { namespace OSAL { -Task::Task(std::string name) - : name_(std::move(name)), runningState_(RunningState::PAUSED), loop_(), pauseDone_(false), workInProgress_(false) +Task::Task(std::string name, ThreadPriority priority) + : name_(std::move(name)), + runningState_(RunningState::PAUSED), + loop_(priority), + pauseDone_(false), + workInProgress_(false) { MEDIA_LOG_D("task %s ctor called", name_.c_str()); loop_.SetName(name_); } -Task::Task(std::string name, std::function handler) : Task(std::move(name)) +Task::Task(std::string name, std::function handler, ThreadPriority priority) : Task(std::move(name), priority) { MEDIA_LOG_D("task %s ctor called", name_.c_str()); handler_ = std::move(handler); diff --git a/engine/foundation/osal/thread/task.h b/engine/foundation/osal/thread/task.h index 0b8d38f493020110f10a97a477d9cefa02c1406c..fd59fd8271b0d4f04b4974b342131998a3952ac0 100644 --- a/engine/foundation/osal/thread/task.h +++ b/engine/foundation/osal/thread/task.h @@ -28,11 +28,12 @@ namespace OHOS { namespace Media { namespace OSAL { + class Task { public: - explicit Task(std::string name); + explicit Task(std::string name, ThreadPriority priority = ThreadPriority::NORMAL); - explicit Task(std::string name, std::function handler); + explicit Task(std::string name, std::function handler, ThreadPriority priority = ThreadPriority::NORMAL); virtual ~Task(); diff --git a/engine/foundation/osal/thread/thread.cpp b/engine/foundation/osal/thread/thread.cpp index fa35cc0bf8769ab39db07c4db578c43864c93031..ff9a0bf6a7eb901bec87fa53cbe5c3f74bbccfca 100644 --- a/engine/foundation/osal/thread/thread.cpp +++ b/engine/foundation/osal/thread/thread.cpp @@ -21,7 +21,7 @@ namespace OHOS { namespace Media { namespace OSAL { -Thread::Thread() noexcept : id_(), name_(), state_() +Thread::Thread(ThreadPriority priority) noexcept : id_(), name_(), priority_(priority), state_() { } @@ -35,6 +35,7 @@ Thread& Thread::operator=(Thread&& other) noexcept if (this != &other) { id_ = other.id_; name_ = std::move(other.name_); + priority_ = other.priority_; state_ = std::move(other.state_); } return *this; @@ -64,9 +65,15 @@ bool Thread::CreateThread(const std::function& func) pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); + struct sched_param sched = {static_cast(priority_)}; + pthread_attr_setschedparam(&attr, &sched); +#if defined(THREAD_STACK_SIZE) and THREAD_STACK_SIZE > 0 + pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE); + MEDIA_LOG_I("thread stack size set to %d", THREAD_STACK_SIZE); +#endif int rtv = pthread_create(&id_, &attr, Thread::Run, state_.get()); if (rtv == 0) { - MEDIA_LOG_I("thread create succ"); + MEDIA_LOG_I("thread %d, id %s create succ", pthread_self(), name_.c_str()); SetNameInternal(); } else { state_.reset(); @@ -79,7 +86,7 @@ void Thread::SetNameInternal() { #ifdef SUPPORT_PTHREAD_NAME if (state_ && !name_.empty()) { - constexpr size_t threadNameMaxSize = 15; + constexpr int threadNameMaxSize = 15; if (name_.size() > threadNameMaxSize) { MEDIA_LOG_W("task name %s exceed max size: %d", name_.c_str(), threadNameMaxSize); name_ = name_.substr(0, threadNameMaxSize); diff --git a/engine/foundation/osal/thread/thread.h b/engine/foundation/osal/thread/thread.h index 0ea5f641dc2581290c6607077567fa23241f31c7..4d74930a04c95d12b610901700043b1c5a6ac393 100644 --- a/engine/foundation/osal/thread/thread.h +++ b/engine/foundation/osal/thread/thread.h @@ -16,17 +16,24 @@ #ifndef HISTREAMER_FOUNDATION_OSAL_THREAD_H #define HISTREAMER_FOUNDATION_OSAL_THREAD_H +#include // NOLINT #include #include // NOLINT -#include // NOLINT #include namespace OHOS { namespace Media { namespace OSAL { +enum class ThreadPriority : int { + HIGHEST = 5, + HIGH = 10, + NORMAL = 20, + LOW = 30, +}; + class Thread { public: - Thread() noexcept; + explicit Thread(ThreadPriority priority = ThreadPriority::NORMAL) noexcept; Thread(const Thread&) = delete; @@ -47,15 +54,16 @@ public: private: struct State { virtual ~State() = default; - std::function func_ {}; + std::function func_{}; }; void SetNameInternal(); static void* Run(void* arg); // NOLINT: void* - pthread_t id_ {}; + pthread_t id_{}; std::string name_; - std::unique_ptr state_ {}; + ThreadPriority priority_; + std::unique_ptr state_{}; }; } // namespace OSAL } // namespace Media diff --git a/engine/foundation/osal/utils/util.h b/engine/foundation/osal/utils/util.h index 327e2bcc1ac25f4afe3f564e823f752923057b4a..9b2f55e9f236edbf5aeb75031ac640f7697e84fa 100644 --- a/engine/foundation/osal/utils/util.h +++ b/engine/foundation/osal/utils/util.h @@ -20,7 +20,7 @@ namespace OHOS { namespace Media { namespace OSAL { void SleepFor(unsigned ms); -} // OSAL +} // namespace OSAL } // namespace Media } // namespace OHOS diff --git a/engine/pipeline/core/filter_base.cpp b/engine/pipeline/core/filter_base.cpp index 67b2b4154c0dda50463de4ca71c29fc76407c6cc..cfad5f44d0930684da9234490ec08b4957261661 100644 --- a/engine/pipeline/core/filter_base.cpp +++ b/engine/pipeline/core/filter_base.cpp @@ -65,20 +65,20 @@ ErrorCode FilterBase::Prepare() ErrorCode FilterBase::Start() { state_ = FilterState::RUNNING; - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode FilterBase::Pause() { state_ = FilterState::PAUSED; - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode FilterBase::Stop() { state_ = FilterState::INITIALIZED; mediaTypeCntMap_.clear(); - return SUCCESS; + return ErrorCode::SUCCESS; } void FilterBase::UnlinkPrevFilters() @@ -115,7 +115,7 @@ ErrorCode FilterBase::PushData(const std::string& inPort, AVBufferPtr buffer) { UNUSED_VARIABLE(inPort); UNUSED_VARIABLE(buffer); - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode FilterBase::PullData(const std::string& outPort, uint64_t offset, size_t size, AVBufferPtr& data) @@ -124,7 +124,7 @@ ErrorCode FilterBase::PullData(const std::string& outPort, uint64_t offset, size UNUSED_VARIABLE(offset); UNUSED_VARIABLE(size); UNUSED_VARIABLE(data); - return SUCCESS; + return ErrorCode::SUCCESS; } void FilterBase::OnEvent(Event event) diff --git a/engine/pipeline/core/filter_base.h b/engine/pipeline/core/filter_base.h index bd942dcb4bcb4d9855928b47d5e9569f9f8a3dac..fb92294e16516dd1c8bc89ba0e95f01ab7a1ad38 100644 --- a/engine/pipeline/core/filter_base.h +++ b/engine/pipeline/core/filter_base.h @@ -64,13 +64,13 @@ public: { UNUSED_VARIABLE(key); UNUSED_VARIABLE(value); - return UNIMPLEMENT; + return ErrorCode::ERROR_UNIMPLEMENTED; } ErrorCode GetParameter(int32_t key, Plugin::Any& value) override { UNUSED_VARIABLE(key); UNUSED_VARIABLE(value); - return UNIMPLEMENT; + return ErrorCode::ERROR_UNIMPLEMENTED; } void UnlinkPrevFilters() override; diff --git a/engine/pipeline/core/pipeline_core.cpp b/engine/pipeline/core/pipeline_core.cpp index 4e94b7ef239602dc31e7aba2b232ea0ac1860817..2d8d971dcaafb8a5d5c8a18950321414af61de09 100644 --- a/engine/pipeline/core/pipeline_core.cpp +++ b/engine/pipeline/core/pipeline_core.cpp @@ -84,12 +84,12 @@ void PipelineCore::Init(EventReceiver* receiver, FilterCallback* callback) ErrorCode PipelineCore::Prepare() { state_ = FilterState::PREPARING; - ErrorCode rtv = SUCCESS; + ErrorCode rtv = ErrorCode::SUCCESS; OSAL::ScopedLock lock(mutex_); for (auto it = filters_.rbegin(); it != filters_.rend(); ++it) { auto& filterPtr = *it; if (filterPtr) { - if ((rtv = filterPtr->Prepare()) != SUCCESS) { + if ((rtv = filterPtr->Prepare()) != ErrorCode::SUCCESS) { break; } } else { @@ -104,26 +104,26 @@ ErrorCode PipelineCore::Start() state_ = FilterState::RUNNING; for (auto it = filters_.rbegin(); it != filters_.rend(); ++it) { auto rtv = (*it)->Start(); - FALSE_RETURN_V(rtv == SUCCESS, rtv); + FALSE_RETURN_V(rtv == ErrorCode::SUCCESS, rtv); } - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode PipelineCore::Pause() { if (state_ == FilterState::PAUSED) { - return SUCCESS; + return ErrorCode::SUCCESS; } if (state_ != FilterState::READY && state_ != FilterState::RUNNING) { - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } state_ = FilterState::PAUSED; for (auto it = filters_.rbegin(); it != filters_.rend(); ++it) { - if ((*it)->Pause() != SUCCESS) { + if ((*it)->Pause() != ErrorCode::SUCCESS) { MEDIA_LOG_I("pause filter: %s", (*it)->GetName().c_str()); } } - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode PipelineCore::Resume() @@ -131,10 +131,10 @@ ErrorCode PipelineCore::Resume() for (auto it = filters_.rbegin(); it != filters_.rend(); ++it) { MEDIA_LOG_I("Resume filter: %s", (*it)->GetName().c_str()); auto rtv = (*it)->Resume(); - FALSE_RETURN_V(rtv == SUCCESS, rtv); + FALSE_RETURN_V(rtv == ErrorCode::SUCCESS, rtv); } state_ = FilterState::RUNNING; - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode PipelineCore::Stop() @@ -150,13 +150,13 @@ ErrorCode PipelineCore::Stop() } auto filterName = (*it)->GetName(); auto rtv = (*it)->Stop(); - FALSE_RETURN_V(rtv == SUCCESS, rtv); + FALSE_RETURN_V(rtv == ErrorCode::SUCCESS, rtv); } for (const auto& filter : filtersToRemove_) { RemoveFilter(filter); } MEDIA_LOG_I("Stop finished, filter number: %zu", filters_.size()); - return SUCCESS; + return ErrorCode::SUCCESS; } void PipelineCore::FlushStart() @@ -194,25 +194,25 @@ ErrorCode PipelineCore::AddFilters(std::initializer_list filtersIn) } } if (filtersToAdd.empty()) { - return ALREADY_EXISTS; + return ErrorCode::ERROR_ALREADY_EXISTS; } { OSAL::ScopedLock lock(mutex_); this->filters_.insert(this->filters_.end(), filtersToAdd.begin(), filtersToAdd.end()); } InitFilters(filtersToAdd); - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode PipelineCore::RemoveFilter(Filter* filter) { auto it = std::find_if(filters_.begin(), filters_.end(), [&filter](const Filter* filterPtr) { return filterPtr == filter; }); - ErrorCode rtv = INVALID_PARAM_VALUE; + ErrorCode rtv = ErrorCode::ERROR_INVALID_PARAM_VALUE; if (it != filters_.end()) { MEDIA_LOG_I("RemoveFilter %s", (*it)->GetName().c_str()); filters_.erase(it); - rtv = SUCCESS; + rtv = ErrorCode::SUCCESS; } return rtv; } @@ -220,7 +220,7 @@ ErrorCode PipelineCore::RemoveFilter(Filter* filter) ErrorCode PipelineCore::RemoveFilterChain(Filter* firstFilter) { if (!firstFilter) { - return NULL_POINTER_ERROR; + return ErrorCode::ERROR_NULL_POINTER; } std::queue levelFilters; levelFilters.push(firstFilter); @@ -233,7 +233,7 @@ ErrorCode PipelineCore::RemoveFilterChain(Filter* firstFilter) levelFilters.push(nextFilter); } } - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode PipelineCore::LinkFilters(std::initializer_list filters) @@ -245,14 +245,14 @@ ErrorCode PipelineCore::LinkFilters(std::initializer_list filters) filtersToLink[i]->GetOutPort(PORT_NAME_DEFAULT)->Connect(filtersToLink[i + 1]->GetInPort(PORT_NAME_DEFAULT)); filtersToLink[i + 1]->GetInPort(PORT_NAME_DEFAULT)->Connect(filtersToLink[i]->GetOutPort(PORT_NAME_DEFAULT)); } - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode PipelineCore::LinkPorts(std::shared_ptr port1, std::shared_ptr port2) { FAIL_RETURN(port1->Connect(port2)); FAIL_RETURN(port2->Connect(port1)); - return SUCCESS; + return ErrorCode::SUCCESS; } void PipelineCore::OnEvent(Event event) diff --git a/engine/pipeline/core/pipeline_core.h b/engine/pipeline/core/pipeline_core.h index dfd1b63060737bf241f693856aa01d1c8f5f65c8..d06613ca3e990124fdc0f14a54848aa4606122fe 100644 --- a/engine/pipeline/core/pipeline_core.h +++ b/engine/pipeline/core/pipeline_core.h @@ -102,7 +102,7 @@ public: { UNUSED_VARIABLE(inPort); UNUSED_VARIABLE(buffer); - return UNIMPLEMENT; + return ErrorCode::ERROR_UNIMPLEMENTED; } ErrorCode PullData(const std::string& outPort, uint64_t offset, size_t size, AVBufferPtr& data) override { @@ -110,7 +110,7 @@ public: UNUSED_VARIABLE(offset); UNUSED_VARIABLE(size); UNUSED_VARIABLE(data); - return UNIMPLEMENT; + return ErrorCode::ERROR_UNIMPLEMENTED; } std::vector GetWorkModes() override { @@ -132,13 +132,13 @@ public: { UNUSED_VARIABLE(key); UNUSED_VARIABLE(value); - return UNIMPLEMENT; + return ErrorCode::ERROR_UNIMPLEMENTED; } ErrorCode GetParameter(int32_t key, Plugin::Any& value) override { UNUSED_VARIABLE(key); UNUSED_VARIABLE(value); - return UNIMPLEMENT; + return ErrorCode::ERROR_UNIMPLEMENTED; } void InitFilters(const std::vector& filters); diff --git a/engine/pipeline/core/port.cpp b/engine/pipeline/core/port.cpp index 764ad29d9893d81e9e213bf872308ea6b2ee07fb..6ba867e2b3607a685f6e183694676a7a49260207 100644 --- a/engine/pipeline/core/port.cpp +++ b/engine/pipeline/core/port.cpp @@ -44,13 +44,13 @@ std::shared_ptr Port::GetPeerPort() ErrorCode InPort::Connect(std::shared_ptr port) { prevPort = port; - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode InPort::Disconnect() { prevPort.reset(); - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode InPort::Activate(const std::vector& modes, WorkMode& outMode) @@ -58,10 +58,10 @@ ErrorCode InPort::Activate(const std::vector& modes, WorkMode& outMode if (auto ptr = prevPort.lock()) { FAIL_RETURN(ptr->Activate(modes, workMode)); outMode = workMode; - return SUCCESS; + return ErrorCode::SUCCESS; } MEDIA_LOG_E("[Filter %s] InPort %s Activate error: prevPort destructed", filter->GetName().c_str(), name.c_str()); - return NULL_POINTER_ERROR; + return ErrorCode::ERROR_NULL_POINTER; } std::shared_ptr InPort::GetPeerPort() @@ -89,23 +89,23 @@ ErrorCode InPort::PullData(uint64_t offset, size_t size, AVBufferPtr& data) return ptr->PullData(offset, size, data); } MEDIA_LOG_E("prevPort destructed"); - return NULL_POINTER_ERROR; + return ErrorCode::ERROR_NULL_POINTER; } ErrorCode OutPort::Connect(std::shared_ptr port) { if (InSamePipeline(port)) { nextPort = port; - return SUCCESS; + return ErrorCode::SUCCESS; } MEDIA_LOG_E("Connect filters that are not in the same pipeline."); - return INVALID_PARAM_VALUE; + return ErrorCode::ERROR_INVALID_PARAM_VALUE; } ErrorCode OutPort::Disconnect() { nextPort.reset(); - return SUCCESS; + return ErrorCode::SUCCESS; } bool OutPort::InSamePipeline(std::shared_ptr port) const @@ -130,13 +130,13 @@ ErrorCode OutPort::Activate(const std::vector& modes, WorkMode& outMod if (found != supportedModes.cend()) { outMode = mode; workMode = mode; - return SUCCESS; // 最先找到的兼容的mode,作为最后结果 + return ErrorCode::SUCCESS; // 最先找到的兼容的mode,作为最后结果 } } } else { MEDIA_LOG_E("filter destructed"); } - return NEGOTIATE_ERROR; + return ErrorCode::ERROR_NEGOTIATE_FAILED; } std::shared_ptr OutPort::GetPeerPort() @@ -160,21 +160,21 @@ ErrorCode OutPort::PullData(uint64_t offset, size_t size, AVBufferPtr& data) return filter->PullData(name, offset, size, data); } MEDIA_LOG_E("filter destructed"); - return NULL_POINTER_ERROR; + return ErrorCode::ERROR_NULL_POINTER; } ErrorCode EmptyInPort::Connect(std::shared_ptr port) { UNUSED_VARIABLE(port); MEDIA_LOG_E("Connect in EmptyInPort"); - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode EmptyInPort::Activate(const std::vector& modes, WorkMode& outMode) { UNUSED_VARIABLE(modes); UNUSED_VARIABLE(outMode); MEDIA_LOG_E("Activate in EmptyInPort"); - return SUCCESS; + return ErrorCode::SUCCESS; } bool EmptyInPort::Negotiate(const std::shared_ptr& inMeta, CapabilitySet& outCaps) { @@ -194,21 +194,21 @@ ErrorCode EmptyInPort::PullData(uint64_t offset, size_t size, AVBufferPtr& data) UNUSED_VARIABLE(size); UNUSED_VARIABLE(data); MEDIA_LOG_E("PullData in EmptyInPort"); - return UNIMPLEMENT; + return ErrorCode::ERROR_UNIMPLEMENTED; } ErrorCode EmptyOutPort::Connect(std::shared_ptr port) { UNUSED_VARIABLE(port); MEDIA_LOG_E("Connect in EmptyOutPort"); - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode EmptyOutPort::Activate(const std::vector& modes, WorkMode& outMode) { UNUSED_VARIABLE(modes); UNUSED_VARIABLE(outMode); MEDIA_LOG_E("Activate in EmptyOutPort"); - return SUCCESS; + return ErrorCode::SUCCESS; } bool EmptyOutPort::Negotiate(const std::shared_ptr& inMeta, CapabilitySet& outCaps) { @@ -228,7 +228,7 @@ ErrorCode EmptyOutPort::PullData(uint64_t offset, size_t size, AVBufferPtr& data UNUSED_VARIABLE(size); UNUSED_VARIABLE(data); MEDIA_LOG_E("PullData in EmptyOutPort"); - return UNIMPLEMENT; + return ErrorCode::ERROR_UNIMPLEMENTED; } } // namespace Pipeline } // namespace Media diff --git a/engine/pipeline/filters/codec/audio_decoder/audio_decoder_filter.cpp b/engine/pipeline/filters/codec/audio_decoder/audio_decoder_filter.cpp index 5b167b2e5668322fbaaf3e30900dc59d1f59a81a..2bbb2104f3fd7fa37d1aa4450c6dc95b41682ad6 100644 --- a/engine/pipeline/filters/codec/audio_decoder/audio_decoder_filter.cpp +++ b/engine/pipeline/filters/codec/audio_decoder/audio_decoder_filter.cpp @@ -38,7 +38,7 @@ int32_t CalculateBufferSize(const std::shared_ptrGetInt32(Plugin::MetaID::AUDIO_SAMPLE_PRE_FRAME, samplesPerFrame)) { + if (!meta->GetInt32(Plugin::MetaID::AUDIO_SAMPLE_PER_FRAME, samplesPerFrame)) { return 0; } int32_t channels; @@ -130,7 +130,7 @@ AudioDecoderFilter::~AudioDecoderFilter() ErrorCode AudioDecoderFilter::QueueAllBufferInPoolToPluginLocked() { - ErrorCode err = SUCCESS; + ErrorCode err = ErrorCode::SUCCESS; while (!outBufferPool_->Empty()) { auto ptr = outBufferPool_->AllocateBuffer(); if (ptr == nullptr) { @@ -138,7 +138,7 @@ ErrorCode AudioDecoderFilter::QueueAllBufferInPoolToPluginLocked() continue; } err = TranslatePluginStatus(plugin_->QueueOutputBuffer(ptr, -1)); - if (err != SUCCESS) { + if (err != ErrorCode::SUCCESS) { MEDIA_LOG_E("queue output buffer error"); } } @@ -150,7 +150,7 @@ ErrorCode AudioDecoderFilter::Start() MEDIA_LOG_D("audio decoder start called"); if (state_ != FilterState::READY && state_ != FilterState::PAUSED) { MEDIA_LOG_W("call decoder start() when state is not ready or working"); - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } return FilterBase::Start(); } @@ -159,7 +159,7 @@ ErrorCode AudioDecoderFilter::Prepare() { if (state_ != FilterState::INITIALIZED) { MEDIA_LOG_W("decoder filter is not in init state"); - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } if (!outBufferQ_) { outBufferQ_ = std::make_shared>("adecOutBuffQueue", @@ -194,7 +194,7 @@ ErrorCode AudioDecoderFilter::Prepare() } auto err = FilterBase::Prepare(); RETURN_ERR_MESSAGE_LOG_IF_FAIL(err, "Audio Decoder prepare error because of filter base prepare error"); - return SUCCESS; + return ErrorCode::SUCCESS; } bool AudioDecoderFilter::Negotiate(const std::string& inPort, const std::shared_ptr &inMeta, @@ -228,7 +228,7 @@ bool AudioDecoderFilter::Negotiate(const std::string& inPort, const std::shared_ return false; } err = ConfigureToStartPluginLocked(inMeta); - if (err != SUCCESS) { + if (err != ErrorCode::SUCCESS) { MEDIA_LOG_E("decoder configure error"); OnEvent({EVENT_ERROR, err}); return false; @@ -246,30 +246,22 @@ bool AudioDecoderFilter::Negotiate(const std::string& inPort, const std::shared_ ErrorCode AudioDecoderFilter::ConfigureWithMetaLocked(const std::shared_ptr &meta) { - uint32_t channels; - if (meta->GetUint32(Plugin::MetaID::AUDIO_CHANNELS, channels)) { - MEDIA_LOG_D("found audio channel meta"); - SetPluginParameterLocked(Tag::AUDIO_CHANNELS, channels); - } - uint32_t sampleRate; - if (meta->GetUint32(Plugin::MetaID::AUDIO_SAMPLE_RATE, sampleRate)) { - MEDIA_LOG_D("found audio sample rate meta"); - SetPluginParameterLocked(Tag::AUDIO_SAMPLE_RATE, sampleRate); - } - int64_t bitRate; - if (meta->GetInt64(Plugin::MetaID::MEDIA_BITRATE, bitRate)) { - MEDIA_LOG_D("found audio bit rate meta"); - SetPluginParameterLocked(Tag::MEDIA_BITRATE, bitRate); - } - auto audioFormat = Plugin::AudioSampleFormat::U8; - if (meta->GetData(Plugin::MetaID::AUDIO_SAMPLE_FORMAT, audioFormat)) { - SetPluginParameterLocked(Tag::AUDIO_SAMPLE_FORMAT, audioFormat); - } - std::vector codecConfig; - if (meta->GetData>(Plugin::MetaID::MEDIA_CODEC_CONFIG, codecConfig)) { - SetPluginParameterLocked(Tag::MEDIA_CODEC_CONFIG, std::move(codecConfig)); - } - return SUCCESS; +#define SET_TAG_AND_LOG(T, metaId, tagId) \ +do { \ + ret = SetTagFromMetaLocked(meta, metaId, tagId); \ + if (ret != ErrorCode::SUCCESS) { \ + MEDIA_LOG_W("set plugin audio " #tagId " error with code %d", ret); \ + } \ +} while (0) + + ErrorCode ret; + SET_TAG_AND_LOG(uint32_t, Plugin::MetaID::AUDIO_CHANNELS, Tag::AUDIO_CHANNELS); + SET_TAG_AND_LOG(uint32_t, Plugin::MetaID::AUDIO_SAMPLE_RATE, Tag::AUDIO_SAMPLE_RATE); + SET_TAG_AND_LOG(int64_t, Plugin::MetaID::MEDIA_BITRATE, Tag::MEDIA_BITRATE); + SET_TAG_AND_LOG(Plugin::AudioSampleFormat, Plugin::MetaID::AUDIO_SAMPLE_FORMAT, Tag::AUDIO_SAMPLE_FORMAT); + SET_TAG_AND_LOG(uint32_t, Plugin::MetaID::AUDIO_SAMPLE_PER_FRAME, Tag::AUDIO_SAMPLE_PER_FRAME); + SET_TAG_AND_LOG(std::vector, Plugin::MetaID::MEDIA_CODEC_CONFIG, Tag::MEDIA_CODEC_CONFIG); + return ErrorCode::SUCCESS; } ErrorCode AudioDecoderFilter::ConfigureToStartPluginLocked(const std::shared_ptr& meta) @@ -283,7 +275,7 @@ ErrorCode AudioDecoderFilter::ConfigureToStartPluginLocked(const std::shared_ptr RETURN_ERR_MESSAGE_LOG_IF_FAIL(err, "configure decoder plugin error"); uint32_t bufferCnt = 0; - if (GetPluginParameterLocked(Tag::REQUIRED_OUT_BUFFER_CNT, bufferCnt) != SUCCESS) { + if (GetPluginParameterLocked(Tag::REQUIRED_OUT_BUFFER_CNT, bufferCnt) != ErrorCode::SUCCESS) { bufferCnt = DEFAULT_OUT_BUFFER_POOL_SIZE; } @@ -315,27 +307,27 @@ ErrorCode AudioDecoderFilter::ConfigureToStartPluginLocked(const std::shared_ptr err = TranslatePluginStatus(plugin_->Start()); RETURN_ERR_MESSAGE_LOG_IF_FAIL(err, "decoder start failed"); - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode AudioDecoderFilter::PushData(const std::string &inPort, AVBufferPtr buffer) { if (state_ != FilterState::READY && state_ != FilterState::PAUSED && state_ != FilterState::RUNNING) { MEDIA_LOG_W("pushing data to decoder when state is %d", static_cast(state_.load())); - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } if (isFlushing_) { MEDIA_LOG_I("decoder is flushing, discarding this data from port %s", inPort.c_str()); - return SUCCESS; + return ErrorCode::SUCCESS; } // async if (drivingMode_ == ThreadDrivingMode::ASYNC) { inBufferQ_->Push(buffer); - return SUCCESS; + return ErrorCode::SUCCESS; } // sync HandleOneFrame(buffer); - return SUCCESS; + return ErrorCode::SUCCESS; } void AudioDecoderFilter::FlushStart() @@ -352,7 +344,7 @@ void AudioDecoderFilter::FlushStart() pushTask_->PauseAsync(); if (plugin_ != nullptr) { auto err = TranslatePluginStatus(plugin_->Flush()); - if (err != SUCCESS) { + if (err != ErrorCode::SUCCESS) { MEDIA_LOG_E("decoder plugin flush error"); } } @@ -423,7 +415,7 @@ ErrorCode AudioDecoderFilter::Release() outBufferQ_->SetActive(false); outBufferQ_.reset(); } - return SUCCESS; + return ErrorCode::SUCCESS; } void AudioDecoderFilter::HandleFrame() diff --git a/engine/pipeline/filters/codec/audio_decoder/audio_decoder_filter.h b/engine/pipeline/filters/codec/audio_decoder/audio_decoder_filter.h index 28eccf3f7d444cfc99b4c0760698086e0720fdcf..d90aa7021d6cb2111e614480b4589bd985b12957 100644 --- a/engine/pipeline/filters/codec/audio_decoder/audio_decoder_filter.h +++ b/engine/pipeline/filters/codec/audio_decoder/audio_decoder_filter.h @@ -64,6 +64,17 @@ private: private: ErrorCode QueueAllBufferInPoolToPluginLocked(); + template + inline ErrorCode SetTagFromMetaLocked(const std::shared_ptr &meta, Plugin::MetaID metaId, + Tag tag) + { + T tmp; + if (meta->GetData(metaId, tmp)) { + return SetPluginParameterLocked(tag, tmp); + } + return ErrorCode::ERROR_NOT_FOUND; + } + std::shared_ptr> inBufferQ_; std::shared_ptr> outBufferQ_; // PCM data std::shared_ptr handleFrameTask_ {}; // dequeue from es bufferQ then enqueue to plugin diff --git a/engine/pipeline/filters/codec/decoder_filter_base.cpp b/engine/pipeline/filters/codec/decoder_filter_base.cpp index f8c01d0d6ac5a1d4bcdbd412e7c1ca197b1a5f33..9ee498a0d3a0a98c32815a602cce3d34b381d6cd 100644 --- a/engine/pipeline/filters/codec/decoder_filter_base.cpp +++ b/engine/pipeline/filters/codec/decoder_filter_base.cpp @@ -38,25 +38,25 @@ ErrorCode DecoderFilterBase::SetPluginParameterLocked(Tag tag, const Plugin::Val ErrorCode DecoderFilterBase::SetParameter(int32_t key, const Plugin::Any& value) { if (state_.load() == FilterState::CREATED) { - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } switch (key) { case KEY_CODEC_DRIVE_MODE: { if (state_ == FilterState::READY || state_ == FilterState::RUNNING || state_ == FilterState::PAUSED) { MEDIA_LOG_W("decoder cannot set parameter KEY_CODEC_DRIVE_MODE in this state"); - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } if (value.Type() != typeid(ThreadDrivingMode)) { - return INVALID_PARAM_TYPE; + return ErrorCode::ERROR_INVALID_PARAM_TYPE; } drivingMode_ = Plugin::AnyCast(value); - return SUCCESS; + return ErrorCode::SUCCESS; } default: { Tag tag = Tag::INVALID; if (!TranslateIntoParameter(key, tag)) { MEDIA_LOG_I("SetParameter key %d is out of boundary", key); - return INVALID_PARAM_VALUE; + return ErrorCode::ERROR_INVALID_PARAM_VALUE; } RETURN_PLUGIN_NOT_FOUND_IF_NULL(plugin_); return SetPluginParameterLocked(tag, value); @@ -67,17 +67,17 @@ ErrorCode DecoderFilterBase::SetParameter(int32_t key, const Plugin::Any& value) ErrorCode DecoderFilterBase::GetParameter(int32_t key, Plugin::Any& value) { if (state_.load() == FilterState::CREATED) { - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } switch (key) { case KEY_CODEC_DRIVE_MODE: value = drivingMode_; - return SUCCESS; + return ErrorCode::SUCCESS; default: { Tag tag = Tag::INVALID; if (!TranslateIntoParameter(key, tag)) { MEDIA_LOG_I("GetParameter key %d is out of boundary", key); - return INVALID_PARAM_VALUE; + return ErrorCode::ERROR_INVALID_PARAM_VALUE; } RETURN_PLUGIN_NOT_FOUND_IF_NULL(plugin_); return TranslatePluginStatus(plugin_->GetParameter(tag, value)); diff --git a/engine/pipeline/filters/codec/decoder_filter_base.h b/engine/pipeline/filters/codec/decoder_filter_base.h index 8c5b6fa250103b7d0029c14bae068024e6ab9bae..da67ac8c84867e8cb583805907c235513fc9ce12 100644 --- a/engine/pipeline/filters/codec/decoder_filter_base.h +++ b/engine/pipeline/filters/codec/decoder_filter_base.h @@ -50,7 +50,7 @@ protected: { Plugin::Any tmp; auto err = TranslatePluginStatus(plugin_->GetParameter(tag, tmp)); - if (err == SUCCESS && tmp.Type() == typeid(T)) { + if (err == ErrorCode::SUCCESS && tmp.Type() == typeid(T)) { value = Plugin::AnyCast(tmp); } return err; diff --git a/engine/pipeline/filters/codec/video_decoder/video_decoder_filter.cpp b/engine/pipeline/filters/codec/video_decoder/video_decoder_filter.cpp index 6a34d1b242ece87ca3ebb0bdb90e3f75749780fb..8ae11ce910c45838ec04be9aa07d5e1c513e26dc 100644 --- a/engine/pipeline/filters/codec/video_decoder/video_decoder_filter.cpp +++ b/engine/pipeline/filters/codec/video_decoder/video_decoder_filter.cpp @@ -98,7 +98,7 @@ ErrorCode VideoDecoderFilter::Start() MEDIA_LOG_D("video decoder start called"); if (state_ != FilterState::READY && state_ != FilterState::PAUSED) { MEDIA_LOG_W("call decoder start() when state_ is not ready or working"); - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } return FilterBase::Start(); } @@ -108,7 +108,7 @@ ErrorCode VideoDecoderFilter::Prepare() MEDIA_LOG_D("video decoder prepare called"); if (state_ != FilterState::INITIALIZED) { MEDIA_LOG_W("decoder filter is not in init state_"); - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } if (!outBufQue_) { outBufQue_ = std::make_shared>("vdecFilterOutBufQue", DEFAULT_OUT_BUFFER_POOL_SIZE); @@ -192,7 +192,7 @@ ErrorCode VideoDecoderFilter::AllocateOutputBuffers() } else { // need to check video sink support and calc buffer size MEDIA_LOG_E("Unsupported video pixel format: %d", vdecFormat_.format); - return ErrorCode::UNIMPLEMENT; + return ErrorCode::ERROR_UNIMPLEMENTED; } auto outAllocator = plugin_->GetAllocator(); // zero copy need change to use sink allocator if (outAllocator == nullptr) { @@ -213,13 +213,13 @@ ErrorCode VideoDecoderFilter::SetVideoDecoderFormat(const std::shared_ptr(Plugin::VideoPixelFormat::NV12); if (!meta->GetString(Plugin::MetaID::MIME, vdecFormat_.mime)) { - return ErrorCode::INVALID_PARAM_VALUE; + return ErrorCode::ERROR_INVALID_PARAM_VALUE; } if (!meta->GetUint32(Plugin::MetaID::VIDEO_WIDTH, vdecFormat_.width)) { - return ErrorCode::INVALID_PARAM_VALUE; + return ErrorCode::ERROR_INVALID_PARAM_VALUE; } if (!meta->GetUint32(Plugin::MetaID::VIDEO_HEIGHT, vdecFormat_.height)) { - return ErrorCode::INVALID_PARAM_VALUE; + return ErrorCode::ERROR_INVALID_PARAM_VALUE; } if (!meta->GetInt64(Plugin::MetaID::MEDIA_BITRATE, vdecFormat_.bitRate)) { MEDIA_LOG_D("Do not have codec bit rate"); @@ -235,19 +235,19 @@ ErrorCode VideoDecoderFilter::ConfigurePluginParams() { if (SetPluginParameterLocked(Tag::MIME, vdecFormat_.mime) != ErrorCode::SUCCESS) { MEDIA_LOG_W("Set mime to plugin fail"); - return ErrorCode::UNKNOWN_ERROR; + return ErrorCode::ERROR_UNKNOWN; } if (SetPluginParameterLocked(Tag::VIDEO_WIDTH, vdecFormat_.width) != ErrorCode::SUCCESS) { MEDIA_LOG_W("Set width to plugin fail"); - return ErrorCode::UNKNOWN_ERROR; + return ErrorCode::ERROR_UNKNOWN; } if (SetPluginParameterLocked(Tag::VIDEO_HEIGHT, vdecFormat_.height) != ErrorCode::SUCCESS) { MEDIA_LOG_W("Set height to plugin fail"); - return ErrorCode::UNKNOWN_ERROR; + return ErrorCode::ERROR_UNKNOWN; } if (SetPluginParameterLocked(Tag::VIDEO_PIXEL_FORMAT, vdecFormat_.format) != ErrorCode::SUCCESS) { MEDIA_LOG_W("Set pixel format to plugin fail"); - return ErrorCode::UNKNOWN_ERROR; + return ErrorCode::ERROR_UNKNOWN; } if (vdecFormat_.bitRate != -1) { if (SetPluginParameterLocked(Tag::MEDIA_BITRATE, vdecFormat_.bitRate) != ErrorCode::SUCCESS) { @@ -358,7 +358,7 @@ void VideoDecoderFilter::FlushStart() } if (plugin_ != nullptr) { auto err = TranslatePluginStatus(plugin_->Flush()); - if (err != SUCCESS) { + if (err != ErrorCode::SUCCESS) { MEDIA_LOG_E("decoder plugin flush error"); } } diff --git a/engine/pipeline/filters/common/plugin_utils.cpp b/engine/pipeline/filters/common/plugin_utils.cpp index 96d3c65462a330c9725bdb236856d62bcc1b84bb..98c4249380de0c7a2778dbfed21bbe78010d1429 100644 --- a/engine/pipeline/filters/common/plugin_utils.cpp +++ b/engine/pipeline/filters/common/plugin_utils.cpp @@ -26,7 +26,7 @@ namespace Pipeline { OHOS::Media::ErrorCode TranslatePluginStatus(Plugin::Status pluginError) { if (pluginError != OHOS::Media::Plugin::Status::OK) { - return OHOS::Media::ErrorCode::UNKNOWN_ERROR; + return OHOS::Media::ErrorCode::ERROR_UNKNOWN; } return OHOS::Media::ErrorCode::SUCCESS; } @@ -54,24 +54,24 @@ ErrorCode FindPluginAndUpdate(const std::shared_ptr& inMeta, } } if (info == nullptr) { - return PLUGIN_NOT_FOUND; + return ErrorCode::ERROR_PLUGIN_NOT_FOUND; } // try to reuse the plugin if their name are the same if (plugin != nullptr && pluginInfo != nullptr) { if (info->name == pluginInfo->name) { - if (TranslatePluginStatus(plugin->Reset()) == SUCCESS) { - return SUCCESS; + if (TranslatePluginStatus(plugin->Reset()) == ErrorCode::SUCCESS) { + return ErrorCode::SUCCESS; } } plugin->Deinit(); } plugin = pluginCreator(info->name); if (plugin == nullptr) { - return PLUGIN_NOT_FOUND; + return ErrorCode::ERROR_PLUGIN_NOT_FOUND; } pluginInfo = info; - return SUCCESS; + return ErrorCode::SUCCESS; } template ErrorCode FindPluginAndUpdate(const std::shared_ptr&, Plugin::PluginType, diff --git a/engine/pipeline/filters/common/plugin_utils.h b/engine/pipeline/filters/common/plugin_utils.h index 3eba45b43c10542fdd1de2e050e9b630e9e25673..dc33293ced692e8b5b139d0394c43550dc09f7ef 100644 --- a/engine/pipeline/filters/common/plugin_utils.h +++ b/engine/pipeline/filters/common/plugin_utils.h @@ -34,7 +34,7 @@ namespace Media { namespace Pipeline { #define RETURN_PLUGIN_NOT_FOUND_IF_NULL(plugin) \ if ((plugin) == nullptr) { \ - return PLUGIN_NOT_FOUND; \ + return ErrorCode::ERROR_PLUGIN_NOT_FOUND; \ } /** diff --git a/engine/pipeline/filters/demux/demuxer_filter.cpp b/engine/pipeline/filters/demux/demuxer_filter.cpp index 769f26bd79689b4719ec40beb57e1df74ed364f8..663c75e6c76991e6d099ba8000feddb6ee74a2c8 100644 --- a/engine/pipeline/filters/demux/demuxer_filter.cpp +++ b/engine/pipeline/filters/demux/demuxer_filter.cpp @@ -17,9 +17,9 @@ #include "demuxer_filter.h" #include +#include "factory/filter_factory.h" #include "foundation/log.h" #include "utils/constants.h" -#include "factory/filter_factory.h" namespace OHOS { namespace Media { @@ -189,7 +189,7 @@ ErrorCode DemuxerFilter::Prepare() } SetCurrentTime(0); state_ = FilterState::PREPARING; - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode DemuxerFilter::PushData(const std::string& inPort, AVBufferPtr buffer) @@ -198,7 +198,7 @@ ErrorCode DemuxerFilter::PushData(const std::string& inPort, AVBufferPtr buffer) if (dataPacker_) { dataPacker_->PushData(std::move(buffer)); } - return SUCCESS; + return ErrorCode::SUCCESS; } bool DemuxerFilter::Negotiate(const std::string& inPort, const std::shared_ptr& inMeta, @@ -206,17 +206,17 @@ bool DemuxerFilter::Negotiate(const std::string& inPort, const std::shared_ptrGetString(Plugin::MetaID::MEDIA_FILE_EXTENSION, uriSuffix_) && - inMeta->GetUint64(Plugin::MetaID::MEDIA_FILE_SIZE, mediaDataSize_); + (void)inMeta->GetUint64(Plugin::MetaID::MEDIA_FILE_SIZE, mediaDataSize_); + return inMeta->GetString(Plugin::MetaID::MEDIA_FILE_EXTENSION, uriSuffix_); } ErrorCode DemuxerFilter::SeekTo(int64_t msec) { if (!plugin_) { MEDIA_LOG_E("SeekTo failed due to no valid plugin"); - return NULL_POINTER_ERROR; + return ErrorCode::ERROR_NULL_POINTER; } - ErrorCode rtv = SUCCESS; + ErrorCode rtv = ErrorCode::SUCCESS; auto ret = plugin_->SeekTo(-1, msec * 1000, Plugin::SeekMode::BACKWARD); // 1000 if (ret == Plugin::Status::OK) { if (task_) { @@ -224,7 +224,7 @@ ErrorCode DemuxerFilter::SeekTo(int64_t msec) } } else { MEDIA_LOG_E("SeekTo failed with return value: %d", static_cast(ret)); - rtv = SEEK_FAILURE; + rtv = ErrorCode::ERROR_SEEK_FAILURE; } return rtv; } @@ -243,7 +243,7 @@ ErrorCode DemuxerFilter::GetCurrentTime(int64_t& time) const { OSAL::ScopedLock lock(timeMutex_); time = curTimeUs_ / 1000; // 1000, time in milliseconds - return SUCCESS; + return ErrorCode::SUCCESS; } void DemuxerFilter::Reset() @@ -271,12 +271,17 @@ bool DemuxerFilter::InitPlugin(std::string pluginName) plugin_->Deinit(); } plugin_ = Plugin::PluginManager::Instance().CreateDemuxerPlugin(pluginName); + if (!plugin_ || plugin_->Init() != Plugin::Status::OK) { + MEDIA_LOG_E("InitPlugin for %s failed.", pluginName.c_str()); + return false; + } pluginAllocator_ = plugin_->GetAllocator(); pluginName_.swap(pluginName); - } - if (plugin_->Init() != Plugin::Status::OK) { - MEDIA_LOG_E("InitPlugin for %s failed due to plugin not found.", pluginName.c_str()); - return false; + } else { + if (plugin_->Reset() != Plugin::Status::OK) { + MEDIA_LOG_E("plugin %s failed to reset.", pluginName.c_str()); + return false; + } } MEDIA_LOG_W("InitPlugin, %s used.", pluginName_.c_str()); plugin_->SetDataSource(std::dynamic_pointer_cast(dataSource_)); @@ -297,7 +302,7 @@ void DemuxerFilter::ActivatePullMode() return (offset < mediaDataSize_) && (size <= mediaDataSize_) && (offset <= (mediaDataSize_ - size)); }; peekRange_ = [this](uint64_t offset, size_t size, AVBufferPtr& bufferPtr) -> bool { - return inPorts_.front()->PullData(offset, size, bufferPtr) == SUCCESS; + return inPorts_.front()->PullData(offset, size, bufferPtr) == ErrorCode::SUCCESS; }; getRange_ = peekRange_; typeFinder_->Init(uriSuffix_, mediaDataSize_, checkRange_, peekRange_); @@ -327,7 +332,7 @@ void DemuxerFilter::MediaTypeFound(std::string pluginName) if (InitPlugin(std::move(pluginName))) { task_->Start(); } else { - OnEvent({EVENT_ERROR, PLUGIN_NOT_FOUND}); + OnEvent({EVENT_ERROR, ErrorCode::ERROR_PLUGIN_NOT_FOUND}); } } @@ -390,25 +395,25 @@ bool DemuxerFilter::PrepareStreams(const Plugin::MediaInfoHelper& mediaInfo) MEDIA_LOG_E("PrepareStreams failed due to no valid port."); return false; } - ErrorCode ret = SUCCESS; + ErrorCode ret = ErrorCode::SUCCESS; if (callback_) { ret = callback_->OnCallback(FilterCallbackType::PORT_ADDED, static_cast(this), portInfo); } - return ret == SUCCESS; + return ret == ErrorCode::SUCCESS; } -int DemuxerFilter::ReadFrame(AVBuffer& buffer, uint32_t& streamIndex) +ErrorCode DemuxerFilter::ReadFrame(AVBuffer& buffer, uint32_t& streamIndex) { MEDIA_LOG_D("ReadFrame called"); - ErrorCode result = UNKNOWN_ERROR; + ErrorCode result = ErrorCode::ERROR_UNKNOWN; auto rtv = plugin_->ReadFrame(buffer, 0); if (rtv == Plugin::Status::OK) { streamIndex = buffer.streamID; SetCurrentTime(buffer.pts); - result = SUCCESS; + result = ErrorCode::SUCCESS; } MEDIA_LOG_D("ReadFrame return with rtv = %d", static_cast(rtv)); - return (rtv != Plugin::Status::END_OF_STREAM) ? result : END_OF_STREAM; + return (rtv != Plugin::Status::END_OF_STREAM) ? result : ErrorCode::END_OF_STREAM; } std::shared_ptr DemuxerFilter::GetStreamMeta(uint32_t streamIndex) @@ -447,7 +452,7 @@ void DemuxerFilter::NegotiateDownstream() stream.needNegoCaps = false; } else { task_->PauseAsync(); - OnEvent({EVENT_ERROR, PLUGIN_NOT_FOUND}); + OnEvent({EVENT_ERROR, ErrorCode::ERROR_PLUGIN_NOT_FOUND}); } } } @@ -459,12 +464,12 @@ void DemuxerFilter::DemuxerLoop() AVBufferPtr bufferPtr = std::make_shared(); uint32_t streamIndex = 0; auto rtv = ReadFrame(*bufferPtr, streamIndex); - if (rtv == SUCCESS) { + if (rtv == ErrorCode::SUCCESS) { HandleFrame(bufferPtr, streamIndex); } else { SendEventEos(); task_->PauseAsync(); - if (rtv != END_OF_STREAM) { + if (rtv != ErrorCode::END_OF_STREAM) { MEDIA_LOG_E("ReadFrame failed with rtv = %d", rtv); } } @@ -477,7 +482,7 @@ void DemuxerFilter::DemuxerLoop() OnEvent({EVENT_READY, {}}); } else { task_->PauseAsync(); - OnEvent({EVENT_ERROR, PARSE_META_FAILED}); + OnEvent({EVENT_ERROR, ErrorCode::ERROR_PARSE_META_FAILED}); } } } diff --git a/engine/pipeline/filters/demux/demuxer_filter.h b/engine/pipeline/filters/demux/demuxer_filter.h index a4dd9eedf14b6dfdcdd31e75cb5fea2b25c44ca4..2965f94da176cdc1b26439db718a540532cf898d 100644 --- a/engine/pipeline/filters/demux/demuxer_filter.h +++ b/engine/pipeline/filters/demux/demuxer_filter.h @@ -105,7 +105,7 @@ private: bool PrepareStreams(const Plugin::MediaInfoHelper& mediaInfo); - int ReadFrame(AVBuffer& buffer, uint32_t& streamIndex); + ErrorCode ReadFrame(AVBuffer& buffer, uint32_t& streamIndex); std::shared_ptr GetStreamMeta(uint32_t streamIndex); diff --git a/engine/pipeline/filters/sink/audio_sink/audio_sink_filter.cpp b/engine/pipeline/filters/sink/audio_sink/audio_sink_filter.cpp index ff8bc604d0bc4c1852f5bac5f08f92a6a5844c25..a5f58115a8e6f53ca205f511ef4f6614f418b89d 100644 --- a/engine/pipeline/filters/sink/audio_sink/audio_sink_filter.cpp +++ b/engine/pipeline/filters/sink/audio_sink/audio_sink_filter.cpp @@ -52,12 +52,12 @@ ErrorCode AudioSinkFilter::SetPluginParameter(Tag tag, const Plugin::ValueType& ErrorCode AudioSinkFilter::SetParameter(int32_t key, const Plugin::Any& value) { if (state_.load() == FilterState::CREATED) { - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } Tag tag = Tag::INVALID; if (!TranslateIntoParameter(key, tag)) { MEDIA_LOG_I("SetParameter key %d is out of boundary", key); - return INVALID_PARAM_VALUE; + return ErrorCode::ERROR_INVALID_PARAM_VALUE; } RETURN_PLUGIN_NOT_FOUND_IF_NULL(plugin_); return SetPluginParameter(tag, value); @@ -68,7 +68,7 @@ ErrorCode AudioSinkFilter::GetPluginParameter(Tag tag, T& value) { Plugin::Any tmp; auto err = TranslatePluginStatus(plugin_->GetParameter(tag, tmp)); - if (err == SUCCESS && tmp.Type() == typeid(T)) { + if (err == ErrorCode::SUCCESS && tmp.Type() == typeid(T)) { value = Plugin::AnyCast(tmp); } return err; @@ -77,12 +77,12 @@ ErrorCode AudioSinkFilter::GetPluginParameter(Tag tag, T& value) ErrorCode AudioSinkFilter::GetParameter(int32_t key, Plugin::Any& value) { if (state_.load() == FilterState::CREATED) { - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } Tag tag = Tag::INVALID; if (!TranslateIntoParameter(key, tag)) { MEDIA_LOG_I("GetParameter key %d is out of boundary", key); - return INVALID_PARAM_VALUE; + return ErrorCode::ERROR_INVALID_PARAM_VALUE; } RETURN_PLUGIN_NOT_FOUND_IF_NULL(plugin_); return TranslatePluginStatus(plugin_->GetParameter(tag, value)); @@ -102,7 +102,7 @@ bool AudioSinkFilter::Negotiate(const std::string& inPort, const std::shared_ptr outCaps = targetPluginInfo_->inCaps; err = ConfigureToPreparePlugin(inMeta); - if (err != SUCCESS) { + if (err != ErrorCode::SUCCESS) { MEDIA_LOG_E("sink configure error"); OnEvent({EVENT_ERROR, err}); return false; @@ -142,24 +142,24 @@ ErrorCode AudioSinkFilter::ConfigureWithMeta(const std::shared_ptrGetUint32(Plugin::MetaID::AUDIO_SAMPLE_PRE_FRAME, samplePerFrame)) { - SetPluginParameter(Tag::AUDIO_SAMPLE_PRE_FRAME, samplePerFrame); + if (meta->GetUint32(Plugin::MetaID::AUDIO_SAMPLE_PER_FRAME, samplePerFrame)) { + SetPluginParameter(Tag::AUDIO_SAMPLE_PER_FRAME, samplePerFrame); } - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode AudioSinkFilter::ConfigureToPreparePlugin(const std::shared_ptr& meta) { auto err = TranslatePluginStatus(plugin_->Init()); RETURN_ERR_MESSAGE_LOG_IF_FAIL(err, "sink plugin init error."); err = ConfigureWithMeta(meta); - if (err != SUCCESS) { + if (err != ErrorCode::SUCCESS) { MEDIA_LOG_E("sink configuration failed "); return err; } err = TranslatePluginStatus(plugin_->Prepare()); RETURN_ERR_MESSAGE_LOG_IF_FAIL(err, "sink prepare failed"); - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode AudioSinkFilter::PushData(const std::string& inPort, AVBufferPtr buffer) @@ -167,7 +167,7 @@ ErrorCode AudioSinkFilter::PushData(const std::string& inPort, AVBufferPtr buffe MEDIA_LOG_D("audio sink push data started, state: %d", state_.load()); if (isFlushing || state_.load() == FilterState::INITIALIZED) { MEDIA_LOG_I("audio sink is flushing ignore this buffer"); - return SUCCESS; + return ErrorCode::SUCCESS; } if (state_.load() != FilterState::RUNNING) { pushThreadIsBlocking = true; @@ -179,7 +179,7 @@ ErrorCode AudioSinkFilter::PushData(const std::string& inPort, AVBufferPtr buffe } if (isFlushing || state_.load() == FilterState::INITIALIZED) { MEDIA_LOG_I("PushData return due to: isFlushing = %d, state = %d", isFlushing, static_cast(state_.load())); - return SUCCESS; + return ErrorCode::SUCCESS; } if ((buffer->flag & BUFFER_FLAG_EOS) != 0) { @@ -189,7 +189,7 @@ ErrorCode AudioSinkFilter::PushData(const std::string& inPort, AVBufferPtr buffe MEDIA_LOG_D("audio sink push data send event_complete"); OnEvent(event); MEDIA_LOG_D("audio sink push data end"); - return SUCCESS; + return ErrorCode::SUCCESS; } auto err = TranslatePluginStatus(plugin_->Write(buffer)); RETURN_ERR_MESSAGE_LOG_IF_FAIL(err, "audio sink write failed"); @@ -202,10 +202,10 @@ ErrorCode AudioSinkFilter::Start() MEDIA_LOG_D("start called"); if (state_ != FilterState::READY && state_ != FilterState::PAUSED) { MEDIA_LOG_W("sink is not ready when start, state: %d", state_.load()); - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } auto err = FilterBase::Start(); - if (err != SUCCESS) { + if (err != ErrorCode::SUCCESS) { MEDIA_LOG_E("audio sink filter start error"); return err; } @@ -214,7 +214,7 @@ ErrorCode AudioSinkFilter::Start() if (pushThreadIsBlocking.load()) { startWorkingCondition_.NotifyOne(); } - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode AudioSinkFilter::Stop() @@ -226,7 +226,7 @@ ErrorCode AudioSinkFilter::Stop() startWorkingCondition_.NotifyOne(); } MEDIA_LOG_I("audio sink stop finish"); - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode AudioSinkFilter::Pause() @@ -235,7 +235,7 @@ ErrorCode AudioSinkFilter::Pause() // only worked when state is working if (state_ != FilterState::READY && state_ != FilterState::RUNNING) { MEDIA_LOG_W("audio sink cannot pause when not working"); - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } auto err = FilterBase::Pause(); RETURN_ERR_MESSAGE_LOG_IF_FAIL(err, "audio sink pause failed"); @@ -254,7 +254,7 @@ ErrorCode AudioSinkFilter::Resume() } return TranslatePluginStatus(plugin_->Resume()); } - return SUCCESS; + return ErrorCode::SUCCESS; } void AudioSinkFilter::FlushStart() @@ -277,7 +277,7 @@ ErrorCode AudioSinkFilter::SetVolume(float volume) { if (state_ != FilterState::READY && state_ != FilterState::RUNNING && state_ != FilterState::PAUSED) { MEDIA_LOG_E("audio sink filter cannot set volume in state %d", state_.load()); - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } MEDIA_LOG_W("set volume %.3f", volume); return TranslatePluginStatus(plugin_->SetVolume(volume)); diff --git a/engine/pipeline/filters/sink/video_sink/video_sink_filter.cpp b/engine/pipeline/filters/sink/video_sink/video_sink_filter.cpp index 2b7793c5565cddf064c5b2eb7b6d1c162cfafb22..8e1a4fbdf820a3144bc4f4d91b94f093e89b3ee2 100644 --- a/engine/pipeline/filters/sink/video_sink/video_sink_filter.cpp +++ b/engine/pipeline/filters/sink/video_sink/video_sink_filter.cpp @@ -64,12 +64,12 @@ void VideoSinkFilter::Init(EventReceiver* receiver, FilterCallback* callback) ErrorCode VideoSinkFilter::SetParameter(int32_t key, const Plugin::Any& value) { if (state_.load() == FilterState::CREATED) { - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } Tag tag = Tag::INVALID; if (!TranslateIntoParameter(key, tag)) { MEDIA_LOG_I("SetParameter key %d is out of boundary", key); - return INVALID_PARAM_VALUE; + return ErrorCode::ERROR_INVALID_PARAM_VALUE; } RETURN_PLUGIN_NOT_FOUND_IF_NULL(plugin_); return TranslatePluginStatus(plugin_->SetParameter(tag, value)); @@ -78,12 +78,12 @@ ErrorCode VideoSinkFilter::SetParameter(int32_t key, const Plugin::Any& value) ErrorCode VideoSinkFilter::GetParameter(int32_t key, Plugin::Any& value) { if (state_.load() == FilterState::CREATED) { - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } Tag tag = Tag::INVALID; if (!TranslateIntoParameter(key, tag)) { MEDIA_LOG_I("GetParameter key %d is out of boundary", key); - return INVALID_PARAM_VALUE; + return ErrorCode::ERROR_INVALID_PARAM_VALUE; } RETURN_PLUGIN_NOT_FOUND_IF_NULL(plugin_); return TranslatePluginStatus(plugin_->GetParameter(tag, value)); @@ -218,7 +218,7 @@ ErrorCode VideoSinkFilter::Start() MEDIA_LOG_D("start called"); if (state_ != FilterState::READY && state_ != FilterState::PAUSED) { MEDIA_LOG_W("sink is not ready when start, state_: %d", state_.load()); - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } inBufQueue_->SetActive(true); renderTask_->Start(); @@ -252,7 +252,7 @@ ErrorCode VideoSinkFilter::Pause() MEDIA_LOG_D("Video sink filter pause start"); if (state_ != FilterState::READY && state_ != FilterState::RUNNING) { MEDIA_LOG_W("video sink cannot pause when not working"); - return ERROR_STATE; + return ErrorCode::ERROR_STATE; } RETURN_ERR_MESSAGE_LOG_IF_FAIL(FilterBase::Pause(), "Video sink pause fail"); RETURN_ERR_MESSAGE_LOG_IF_FAIL(TranslatePluginStatus(plugin_->Pause()), "Pause plugin fail"); diff --git a/engine/pipeline/filters/source/media_source_filter.cpp b/engine/pipeline/filters/source/media_source_filter.cpp index ec07efa902535f38315f3425c11d5561ce05c8f9..62a6a086cc20b460187dac886fecc841f85c3518 100644 --- a/engine/pipeline/filters/source/media_source_filter.cpp +++ b/engine/pipeline/filters/source/media_source_filter.cpp @@ -20,30 +20,15 @@ #include "factory/filter_factory.h" #include "plugin/interface/source_plugin.h" #include "plugin/core/plugin_meta.h" +#include "common/plugin_utils.h" +#include "utils/type_define.h" namespace OHOS { namespace Media { namespace Pipeline { using namespace Plugin; -namespace { -AutoRegisterFilter g_registerFilterHelper("builtin.player.mediasource"); - -ErrorCode TranslateError(Status err) -{ - ErrorCode ret = UNKNOWN_ERROR; - switch (err) { - case Status::OK: - ret = SUCCESS; - break; - case Status::END_OF_STREAM: - ret = END_OF_STREAM; - default: - break; - } - return ret; -} -} // namespace +static AutoRegisterFilter g_registerFilterHelper("builtin.player.mediasource"); MediaSourceFilter::MediaSourceFilter(const std::string& name) : FilterBase(name), @@ -71,13 +56,14 @@ MediaSourceFilter::~MediaSourceFilter() } } -ErrorCode MediaSourceFilter::SetSource(std::shared_ptr source) +ErrorCode MediaSourceFilter::SetSource(const std::shared_ptr& source) { MEDIA_LOG_D("IN"); if (source == nullptr) { MEDIA_LOG_E("Invalid source"); - return ErrorCode::INVALID_SOURCE; + return ErrorCode::ERROR_INVALID_SOURCE; } + protocol_.clear(); ErrorCode err = FindPlugin(source); if (err != ErrorCode::SUCCESS) { return err; @@ -90,10 +76,10 @@ ErrorCode MediaSourceFilter::SetSource(std::shared_ptr source) return DoNegotiate(source); } -ErrorCode MediaSourceFilter::InitPlugin(std::shared_ptr source) +ErrorCode MediaSourceFilter::InitPlugin(const std::shared_ptr& source) { MEDIA_LOG_D("IN"); - ErrorCode err = TranslateError(plugin_->Init()); + ErrorCode err = TranslatePluginStatus(plugin_->Init()); if (err != ErrorCode::SUCCESS) { return err; } @@ -107,7 +93,7 @@ ErrorCode MediaSourceFilter::InitPlugin(std::shared_ptr source) params->insert(std::pair(key, value)); } else { // network protocl need to add params - err = TranslateError(plugin_->SetSource(uri_, nullptr)); + err = TranslatePluginStatus(plugin_->SetSource(uri_, nullptr)); } return err; } @@ -139,9 +125,9 @@ ErrorCode MediaSourceFilter::Prepare() { MEDIA_LOG_D("IN"); if (plugin_ == nullptr) { - return ErrorCode::PLUGIN_NOT_FOUND; + return ErrorCode::ERROR_PLUGIN_NOT_FOUND; } - auto err = TranslateError(plugin_->Prepare()); + auto err = TranslatePluginStatus(plugin_->Prepare()); if (err == ErrorCode::SUCCESS) { MEDIA_LOG_D("media source send EVENT_READY"); OnEvent(Event{EVENT_READY, {}}); @@ -155,14 +141,14 @@ ErrorCode MediaSourceFilter::Start() if (taskPtr_) { taskPtr_->Start(); } - return plugin_ ? TranslateError(plugin_->Start()) : PLUGIN_NOT_FOUND; + return plugin_ ? TranslatePluginStatus(plugin_->Start()) : ErrorCode::ERROR_PLUGIN_NOT_FOUND; } ErrorCode MediaSourceFilter::PullData(const std::string& outPort, uint64_t offset, size_t size, AVBufferPtr& data) { MEDIA_LOG_D("IN, offset: %llu, size: %zu, outPort: %s", offset, size, outPort.c_str()); if (!plugin_) { - return ErrorCode::PLUGIN_NOT_FOUND; + return ErrorCode::ERROR_PLUGIN_NOT_FOUND; } ErrorCode err; auto readSize = size; @@ -183,7 +169,7 @@ ErrorCode MediaSourceFilter::PullData(const std::string& outPort, uint64_t offse MEDIA_LOG_D("totalSize_: %zu", totalSize); } if (position_ != offset) { - err = TranslateError(plugin_->SeekTo(offset)); + err = TranslatePluginStatus(plugin_->SeekTo(offset)); if (err != ErrorCode::SUCCESS) { MEDIA_LOG_E("Seek to %llu fail", offset); return err; @@ -194,7 +180,7 @@ ErrorCode MediaSourceFilter::PullData(const std::string& outPort, uint64_t offse if (data == nullptr) { data = std::make_shared(); } - err = TranslateError(plugin_->Read(data, readSize)); + err = TranslatePluginStatus(plugin_->Read(data, readSize)); if (err == ErrorCode::SUCCESS) { position_ += data->GetMemory()->GetSize(); } @@ -209,9 +195,9 @@ ErrorCode MediaSourceFilter::Stop() } protocol_.clear(); uri_.clear(); - ErrorCode ret = PLUGIN_NOT_FOUND; + ErrorCode ret = ErrorCode::ERROR_PLUGIN_NOT_FOUND; if (plugin_) { - ret = TranslateError(plugin_->Stop()); + ret = TranslatePluginStatus(plugin_->Stop()); } return ret; } @@ -259,7 +245,7 @@ ErrorCode MediaSourceFilter::DoNegotiate(const std::shared_ptr& sou CapabilitySet peerCaps; if (!GetOutPort(PORT_NAME_DEFAULT)->Negotiate(suffixMeta, peerCaps)) { MEDIA_LOG_E("Negotiate fail!"); - return ErrorCode::INVALID_PARAM_VALUE; + return ErrorCode::ERROR_INVALID_PARAM_VALUE; } } } @@ -281,8 +267,8 @@ void MediaSourceFilter::ReadLoop() { MEDIA_LOG_D("IN"); AVBufferPtr bufferPtr = std::make_shared(); - ErrorCode ret = TranslateError(plugin_->Read(bufferPtr, 4096)); // 4096: default push data size - if (ret == END_OF_STREAM) { + ErrorCode ret = TranslatePluginStatus(plugin_->Read(bufferPtr, 4096)); // 4096: default push data size + if (ret == ErrorCode::END_OF_STREAM) { Stop(); OnEvent({EVENT_COMPLETE, {}}); return; @@ -317,18 +303,18 @@ ErrorCode MediaSourceFilter::CreatePlugin(const std::shared_ptr& inf PluginManager& manager) { if ((plugin_ != nullptr) && (pluginInfo_ != nullptr)) { - if (info->name == pluginInfo_->name && TranslateError(plugin_->Reset()) == ErrorCode::SUCCESS) { + if (info->name == pluginInfo_->name && TranslatePluginStatus(plugin_->Reset()) == ErrorCode::SUCCESS) { MEDIA_LOG_I("Reuse last plugin: %s", name.c_str()); return ErrorCode::SUCCESS; } - if (TranslateError(plugin_->Deinit()) != ErrorCode::SUCCESS) { + if (TranslatePluginStatus(plugin_->Deinit()) != ErrorCode::SUCCESS) { MEDIA_LOG_E("Deinit last plugin: %s error", pluginInfo_->name.c_str()); } } plugin_ = manager.CreateSourcePlugin(name); if (plugin_ == nullptr) { MEDIA_LOG_E("PluginManager CreatePlugin %s fail", name.c_str()); - return ErrorCode::UNKNOWN_ERROR; + return ErrorCode::ERROR_UNKNOWN; } pluginInfo_ = info; MEDIA_LOG_I("Create new plugin: \"%s\" success", pluginInfo_->name.c_str()); @@ -340,7 +326,7 @@ ErrorCode MediaSourceFilter::FindPlugin(const std::shared_ptr& sour ParseProtocol(source); if (protocol_.empty()) { MEDIA_LOG_E("protocol_ is empty"); - return ErrorCode::NULL_POINTER_ERROR; + return ErrorCode::ERROR_NULL_POINTER; } PluginManager& pluginManager = PluginManager::Instance(); std::set nameList = pluginManager.ListPlugins(PluginType::SOURCE); @@ -358,7 +344,7 @@ ErrorCode MediaSourceFilter::FindPlugin(const std::shared_ptr& sour } } MEDIA_LOG_I("Cannot find any plugin"); - return ErrorCode::PLUGIN_NOT_FOUND; + return ErrorCode::ERROR_PLUGIN_NOT_FOUND; } } // namespace Pipeline } // namespace Media diff --git a/engine/pipeline/filters/source/media_source_filter.h b/engine/pipeline/filters/source/media_source_filter.h index 57a49255197444deab78ffa7983b73540a3a7685..80ce7cebd6d5a93012a1ca342d573c88998a52e8 100644 --- a/engine/pipeline/filters/source/media_source_filter.h +++ b/engine/pipeline/filters/source/media_source_filter.h @@ -43,8 +43,8 @@ public: std::vector GetWorkModes() override; ErrorCode PullData(const std::string& outPort, uint64_t offset, size_t size, AVBufferPtr& data) override; - virtual ErrorCode SetSource(std::shared_ptr source); - ErrorCode InitPlugin(std::shared_ptr source); + virtual ErrorCode SetSource(const std::shared_ptr& source); + ErrorCode InitPlugin(const std::shared_ptr& source); virtual ErrorCode SetBufferSize(size_t size); bool IsSeekable() const; ErrorCode Prepare() override; diff --git a/engine/player/BUILD.gn b/engine/player/BUILD.gn index 03038d8b1640d4cbfa9ac6ec45dfb71b4bfadd02..4e249f7eb8730ad0c4d9a5dbb25fdabd36f73a9f 100644 --- a/engine/player/BUILD.gn +++ b/engine/player/BUILD.gn @@ -27,7 +27,6 @@ if (defined(ohos_lite)) { "//foundation/multimedia/histreamer/engine", "//foundation/multimedia/histreamer/engine/player", "//foundation/multimedia/histreamer/interface", - "//foundation/multimedia/media_lite/interfaces", "//foundation/multimedia/media_lite/interfaces/innerkits", "//foundation/multimedia/media_lite/interfaces/kits/player_lite", ] diff --git a/engine/player/hiplayer.cpp b/engine/player/hiplayer.cpp index 3e4573ad7f317a16e99225983bd90c08fb2dea3c..aa3f9f6d90b947940a71fd66f5a8e9f3348996f3 100644 --- a/engine/player/hiplayer.cpp +++ b/engine/player/hiplayer.cpp @@ -17,273 +17,13 @@ #include "histreamer/hiplayer.h" -#include #include "hiplayer_impl.h" -namespace { -const float MAX_MEDIA_VOLUME = 300.0f; -} - namespace OHOS { namespace Media { -HiPlayer::HiPlayer() - : player_(HiPlayerImpl::CreateHiPlayerImpl()), - curState_(Media::PlayerStates::PLAYER_IDLE), - isInited_(false), - isSingleLoop_(false), - audioStreamType_(-1) -{ - MEDIA_LOG_I("ctor entered."); -} - -HiPlayer::~HiPlayer() -{ - MEDIA_LOG_I("dtor entered."); - player_ = nullptr; - isInited_ = false; - isSingleLoop_ = false; -} - -int32_t HiPlayer::SetSource(const Media::Source& source) -{ - MEDIA_LOG_I("SetSource entered."); - Init(); - auto src = std::make_shared(source); - int ret = -1; - if (player_ && player_->SetSource(src) == SUCCESS) { - ret = 0; - } - return ret; -} - -int32_t HiPlayer::Prepare() -{ - MEDIA_LOG_I("Prepare entered."); - int ret = -1; - if (player_ && player_->Prepare() == SUCCESS) { - curState_ = Media::PlayerStates::PLAYER_PREPARED; - ret = 0; - } - return ret; -} - -int32_t HiPlayer::Play() -{ - MEDIA_LOG_I("Play entered."); - int ret = -1; - if (curState_ == Media::PlayerStates::PLAYER_PAUSED) { - if (player_ && player_->Resume() == SUCCESS) { - ret = 0; - } - } else if (player_ && player_->Play() == SUCCESS) { - curState_ = Media::PlayerStates::PLAYER_STARTED; - ret = 0; - } - return ret; -} - -bool HiPlayer::IsPlaying() -{ - return player_ && curState_ == Media::PlayerStates::PLAYER_STARTED; -} - -int32_t HiPlayer::Pause() -{ - MEDIA_LOG_I("Pause entered."); - int ret = -1; - if (player_ && player_->Pause() == SUCCESS) { - curState_ = Media::PlayerStates::PLAYER_PAUSED; - ret = 0; - } - return ret; -} - -int32_t HiPlayer::Stop() -{ - MEDIA_LOG_I("Stop entered."); - int ret = -1; - if (player_ && player_->Stop() == SUCCESS) { - curState_ = Media::PlayerStates::PLAYER_STOPPED; - ret = 0; - } - return ret; -} - -int32_t HiPlayer::Rewind(int64_t mSeconds, int32_t mode) -{ - MEDIA_LOG_I("Rewind entered."); - int ret = -1; - size_t pos = 0; - if (player_ && player_->Seek(mSeconds, pos) == SUCCESS) { - ret = 0; - } - return ret; -} - -int32_t HiPlayer::SetVolume(float leftVolume, float rightVolume) -{ - if ((curState_ != Media::PlayerStates::PLAYER_STARTED) && (curState_ != Media::PlayerStates::PLAYER_PAUSED) && - (curState_ != Media::PlayerStates::PLAYER_PREPARED)) { - MEDIA_LOG_E("cannot set volume in state %d", curState_); - return -1; - } - if (leftVolume < 0 || leftVolume > MAX_MEDIA_VOLUME || rightVolume < 0 || rightVolume > MAX_MEDIA_VOLUME) { - MEDIA_LOG_E("volume not valid, should be in range [0,300]"); - return -1; - } - float volume = 0.f; - if (leftVolume < 1e-6 && rightVolume >= 1e-6) { // 1e-6 - volume = rightVolume; - } else if (rightVolume < 1e-6 && leftVolume >= 1e-6) { // 1e-6 - volume = leftVolume; - } else { - volume = (leftVolume + rightVolume) / 2; // 2 - } - volume /= MAX_MEDIA_VOLUME; // normalize to 0~1 - int ret = -1; // -1 - MEDIA_LOG_W("set volume %.3f", volume); - if (player_ && player_->SetVolume(volume) == SUCCESS) { - ret = 0; - } - return ret; -} - -#ifndef SURFACE_DISABLED -int32_t HiPlayer::SetSurface(Surface* surface) -{ - return 0; -} -#endif - -bool HiPlayer::IsSingleLooping() -{ - return isSingleLoop_; -} - -int32_t HiPlayer::GetPlayerState(int32_t& state) -{ - if (!player_) { - return -1; - } - state = static_cast(curState_); - return 0; -} - -int32_t HiPlayer::GetCurrentPosition(int64_t& currentPosition) -{ - int ret = -1; - if (player_ && player_->GetCurrentTime(currentPosition) == SUCCESS) { - ret = 0; - } - return ret; -} - -int32_t HiPlayer::GetDuration(int64_t& duration) -{ - int ret = -1; - size_t durationTime = 0; - if (player_ && player_->GetDuration(durationTime) == SUCCESS) { - duration = static_cast(durationTime); - ret = 0; - } - return ret; -} - -int32_t HiPlayer::GetVideoWidth(int32_t& videoWidth) -{ - return -1; -} - -int32_t HiPlayer::GetVideoHeight(int32_t& videoHeight) -{ - return -1; -} - -int32_t HiPlayer::SetPlaybackSpeed(float speed) -{ - return 0; -} - -int32_t HiPlayer::GetPlaybackSpeed(float& speed) -{ - speed = 1.0; - return 0; -} - -int32_t HiPlayer::SetAudioStreamType(int32_t type) -{ - if (curState_ != Media::PlayerStates::PLAYER_IDLE && curState_ != Media::PlayerStates::PLAYER_INITIALIZED) { - return -1; - } - audioStreamType_ = type; - return 0; -} - -void HiPlayer::GetAudioStreamType(int32_t& type) -{ - type = audioStreamType_; -} - -int32_t HiPlayer::Reset() -{ - int ret = -1; - if (player_ && player_->Stop() == SUCCESS) { - ret = 0; - } - return ret; -} - -int32_t HiPlayer::Release() -{ - return Reset(); -} - -int32_t HiPlayer::SetLoop(bool loop) -{ - MEDIA_LOG_I("SetLoop entered."); - int ret = -1; - if (player_ && player_->SetSingleLoop(loop) == SUCCESS) { - isSingleLoop_ = loop; - ret = 0; - } - return ret; -} - -void HiPlayer::SetPlayerCallback(const std::shared_ptr& cb) -{ - if (player_ && player_->SetCallback(cb) == SUCCESS) { - MEDIA_LOG_I("SetPlayerCallback succ."); - } else { - MEDIA_LOG_E("SetPlayerCallback failed."); - } -} - -int32_t HiPlayer::Init() -{ - MEDIA_LOG_I("Init entered."); - if (isInited_) { - return 0; - } - if (player_) { - player_->Init(); - } - curState_ = Media::PlayerStates::PLAYER_INITIALIZED; - return 0; -} - -int32_t HiPlayer::DeInit() -{ - return 0; -} - -int32_t HiPlayer::SetParameter(const Media::Format& params) -{ - return 0; -} - std::shared_ptr CreateHiPlayer() { - return std::shared_ptr(new (std::nothrow) HiPlayer()); + return HiPlayerImpl::CreateHiPlayerImpl(); } } // namespace Media } // namespace OHOS diff --git a/engine/player/hiplayer_impl.cpp b/engine/player/hiplayer_impl.cpp index 88284b1911443179cb5d9dfbdc64a0f5aaf5bb4a..2eeabe212875972feb4d1e5ffea9e9a7cc76728e 100644 --- a/engine/player/hiplayer_impl.cpp +++ b/engine/player/hiplayer_impl.cpp @@ -16,33 +16,41 @@ #define LOG_TAG "HiPlayerImpl" #include "hiplayer_impl.h" -#include #include "foundation/log.h" -#include "utils/utils.h" -#include "plugin/core/plugin_meta.h" #include "pipeline/factory/filter_factory.h" +#include "plugin/core/plugin_meta.h" +#include "utils/utils.h" + +namespace { +const float MAX_MEDIA_VOLUME = 100.0f; +} namespace OHOS { namespace Media { using namespace Pipeline; -HiPlayer::HiPlayerImpl::HiPlayerImpl() : fsm_(*this) +HiPlayerImpl::HiPlayerImpl() + : fsm_(*this), + curFsmState_(StateId::INIT), + pipelineStates_(PlayerStates::PLAYER_IDLE), + volume_(-1.0f), + errorCode_(ErrorCode::SUCCESS) { MEDIA_LOG_I("hiPlayerImpl ctor"); FilterFactory::Instance().Init(); - audioSource = + audioSource_ = FilterFactory::Instance().CreateFilterWithType("builtin.player.mediasource", "mediaSource"); #ifdef UNIT_TEST - demuxer = FilterFactory::Instance().CreateFilterWithType("builtin.player.demuxer", "demuxer"); - audioDecoder = FilterFactory::Instance().CreateFilterWithType("builtin.player.audiodecoder", - "audiodecoder"); - audioSink = + demuxer_ = FilterFactory::Instance().CreateFilterWithType("builtin.player.demuxer", "demuxer"); + audioDecoder_ = FilterFactory::Instance().CreateFilterWithType("builtin.player.audiodecoder", + "audiodecoder"); + audioSink_ = FilterFactory::Instance().CreateFilterWithType("builtin.player.audiosink", "audiosink"); #else - demuxer = FilterFactory::Instance().CreateFilterWithType("builtin.player.demuxer", "demuxer"); - audioSink = + demuxer_ = FilterFactory::Instance().CreateFilterWithType("builtin.player.demuxer", "demuxer"); + audioSink_ = FilterFactory::Instance().CreateFilterWithType("builtin.player.audiosink", "audioSink"); #ifdef VIDEO_SUPPORT videoSink = @@ -50,101 +58,159 @@ HiPlayer::HiPlayerImpl::HiPlayerImpl() : fsm_(*this) FALSE_RETURN(videoSink != nullptr); #endif #endif - FALSE_RETURN(audioSource != nullptr); - FALSE_RETURN(demuxer != nullptr); - FALSE_RETURN(audioSink != nullptr); + FALSE_RETURN(audioSource_ != nullptr); + FALSE_RETURN(demuxer_ != nullptr); + FALSE_RETURN(audioSink_ != nullptr); - pipeline = std::make_shared(); + pipeline_ = std::make_shared(); } -HiPlayer::HiPlayerImpl::~HiPlayerImpl() +HiPlayerImpl::~HiPlayerImpl() { fsm_.Stop(); - MEDIA_LOG_W("dtor called."); + MEDIA_LOG_D("dtor called."); } -std::shared_ptr HiPlayer::HiPlayerImpl::CreateHiPlayerImpl() +std::shared_ptr HiPlayerImpl::CreateHiPlayerImpl() { - return std::shared_ptr(new (std::nothrow) HiPlayer::HiPlayerImpl()); + return std::shared_ptr(new (std::nothrow) HiPlayerImpl()); } -void HiPlayer::HiPlayerImpl::Init() +int32_t HiPlayerImpl::Init() { - if (initialized) { - return; + errorCode_ = ErrorCode::SUCCESS; + if (initialized_.load()) { + return to_underlying(ErrorCode::SUCCESS); + } + pipeline_->Init(this, this); + ErrorCode ret = pipeline_->AddFilters({audioSource_.get(), demuxer_.get()}); + if (ret == ErrorCode::SUCCESS) { + ret = pipeline_->LinkFilters({audioSource_.get(), demuxer_.get()}); } - initialized = true; - fsm_.SetStateCallback(this); - fsm_.Start(); - pipeline->Init(this, this); -#ifdef UNIT_TEST - pipeline->AddFilters({audioSource.get(), demuxer.get(), audioSink.get()}); - pipeline->LinkFilters({audioSource.get(), demuxer.get(), audioSink.get()}); -#else - pipeline->AddFilters({audioSource.get(), demuxer.get()}); - pipeline->LinkFilters({audioSource.get(), demuxer.get()}); -#endif + if (ret == ErrorCode::SUCCESS) { + pipelineStates_ = PlayerStates::PLAYER_INITIALIZED; + fsm_.SetStateCallback(this); + fsm_.Start(); + initialized_ = true; + } else { + pipeline_->UnlinkPrevFilters(); + pipeline_->RemoveFilterChain(audioSource_.get()); + pipelineStates_ = PLAYER_STATE_ERROR; + } + return to_underlying(ret); +} +int32_t HiPlayerImpl::SetSource(const Source& source) +{ + auto ret = Init(); + if (ret != to_underlying(ErrorCode::SUCCESS)) { + return ret; + } + return to_underlying(fsm_.SendEvent(Intent::SET_SOURCE, std::make_shared(source))); } -PFilter HiPlayer::HiPlayerImpl::CreateAudioDecoder(const std::string& desc) +int32_t HiPlayerImpl::Prepare() { - if (!audioDecoderMap[desc]) { - audioDecoderMap[desc] = FilterFactory::Instance().CreateFilterWithType( + MEDIA_LOG_D("Prepare entered, current fsm state: %s.", fsm_.GetCurrentState().c_str()); + OSAL::ScopedLock lock(stateMutex_); + if (curFsmState_ == StateId::PREPARING) { + errorCode_ = ErrorCode::SUCCESS; + cond_.Wait(lock, [this] { return curFsmState_ == StateId::READY || curFsmState_ == StateId::INIT; }); + } + MEDIA_LOG_D("Prepare finished, current fsm state: %s.", fsm_.GetCurrentState().c_str()); + if (curFsmState_ == StateId::READY) { + return to_underlying(ErrorCode::SUCCESS); + } else if (curFsmState_ == StateId::INIT) { + return to_underlying(errorCode_.load()); + } else { + return to_underlying(ErrorCode::ERROR_STATE); + } +} + +PFilter HiPlayerImpl::CreateAudioDecoder(const std::string& desc) +{ + if (!audioDecoderMap_[desc]) { + audioDecoderMap_[desc] = FilterFactory::Instance().CreateFilterWithType( "builtin.player.audiodecoder", "audiodecoder-" + desc); // set parameters to decoder. } - return audioDecoderMap[desc]; + return audioDecoderMap_[desc]; } -ErrorCode HiPlayer::HiPlayerImpl::Prepare() +int32_t HiPlayerImpl::Play() { - MEDIA_LOG_D("Prepare entered, current state: %s.", fsm_.GetCurrentState().c_str()); - OSAL::ScopedLock lock(mutex_); - cond_.Wait(lock, [this] { - auto state = fsm_.GetCurrentStateId(); - return state == StateId::READY || state == StateId::INIT; - }); - MEDIA_LOG_D("Prepare finished, current state: %s.", fsm_.GetCurrentState().c_str()); - return fsm_.GetCurrentStateId() == StateId::READY ? SUCCESS : UNKNOWN_ERROR; + ErrorCode ret; + if (pipelineStates_ == PlayerStates::PLAYER_PAUSED) { + ret = fsm_.SendEvent(Intent::RESUME); + } else { + ret = fsm_.SendEvent(Intent::PLAY); + } + return to_underlying(ret); } -ErrorCode HiPlayer::HiPlayerImpl::Play() +bool HiPlayerImpl::IsPlaying() { - return fsm_.SendEvent(Intent::PLAY); + return pipelineStates_ == PlayerStates::PLAYER_STARTED; } -ErrorCode HiPlayer::HiPlayerImpl::Pause() +int32_t HiPlayerImpl::Pause() { - return fsm_.SendEvent(Intent::PAUSE); + return to_underlying(fsm_.SendEvent(Intent::PAUSE)); } -ErrorCode HiPlayer::HiPlayerImpl::Resume() +ErrorCode HiPlayerImpl::Resume() { return fsm_.SendEvent(Intent::RESUME); } -ErrorCode HiPlayer::HiPlayerImpl::Stop() +int32_t HiPlayerImpl::Stop() { - return fsm_.SendEvent(Intent::STOP); + return to_underlying(fsm_.SendEvent(Intent::STOP)); } -ErrorCode HiPlayer::HiPlayerImpl::StopAsync() +ErrorCode HiPlayerImpl::StopAsync() { return fsm_.SendEventAsync(Intent::STOP); } -ErrorCode HiPlayer::HiPlayerImpl::SetSource(std::shared_ptr source) +int32_t HiPlayerImpl::Rewind(int64_t mSeconds, int32_t mode) { - return fsm_.SendEvent(Intent::SET_SOURCE, source); + return to_underlying(fsm_.SendEventAsync(Intent::SEEK, mSeconds)); } -ErrorCode HiPlayer::HiPlayerImpl::SetBufferSize(size_t size) +int32_t HiPlayerImpl::SetVolume(float leftVolume, float rightVolume) +{ + if (leftVolume < 0 || leftVolume > MAX_MEDIA_VOLUME || rightVolume < 0 || rightVolume > MAX_MEDIA_VOLUME) { + MEDIA_LOG_E("volume not valid, should be in range [0,100]"); + return to_underlying(ErrorCode::ERROR_INVALID_PARAM_VALUE); + } + if (leftVolume < 1e-6 && rightVolume >= 1e-6) { // 1e-6 + volume_ = rightVolume; + } else if (rightVolume < 1e-6 && leftVolume >= 1e-6) { // 1e-6 + volume_ = leftVolume; + } else { + volume_ = (leftVolume + rightVolume) / 2; // 2 + } + volume_ /= MAX_MEDIA_VOLUME; // normalize to 0~1 + PlayerStates states = pipelineStates_.load(); + if (states != Media::PlayerStates::PLAYER_STARTED) { + return to_underlying(ErrorCode::SUCCESS); + } + return to_underlying(SetVolume(volume_)); +} + +#ifndef SURFACE_DISABLED +int32_t HiPlayerImpl::SetSurface(Surface* surface) +{ + return to_underlying(ErrorCode::ERROR_UNIMPLEMENTED); +} +#endif +ErrorCode HiPlayerImpl::SetBufferSize(size_t size) { - return audioSource->SetBufferSize(size); + return audioSource_->SetBufferSize(size); } -void HiPlayer::HiPlayerImpl::OnEvent(Event event) +void HiPlayerImpl::OnEvent(Event event) { MEDIA_LOG_D("[HiStreamer] OnEvent (%d)", event.type); switch (event.type) { @@ -163,74 +229,87 @@ void HiPlayer::HiPlayerImpl::OnEvent(Event event) } } -ErrorCode HiPlayer::HiPlayerImpl::SetSingleLoop(bool loop) +ErrorCode HiPlayerImpl::DoSetSource(const std::shared_ptr& source) const { - singleLoop = loop; - return SUCCESS; + return audioSource_->SetSource(source); } -ErrorCode HiPlayer::HiPlayerImpl::Seek(size_t time, size_t& position) +ErrorCode HiPlayerImpl::PrepareFilters() { - auto rtv = fsm_.SendEvent(Intent::SEEK, static_cast(time)); - if (rtv == SUCCESS) { - int64_t pos = 0; - rtv = GetCurrentTime(pos); - position = static_cast(pos); + auto ret = pipeline_->Prepare(); + if (ret == ErrorCode::SUCCESS) { + pipelineStates_ = PlayerStates::PLAYER_PREPARED; } - return rtv; -} - -ErrorCode HiPlayer::HiPlayerImpl::DoSetSource(const std::shared_ptr& source) const -{ - return audioSource->SetSource(source); -} - -ErrorCode HiPlayer::HiPlayerImpl::PrepareFilters() -{ - return pipeline->Prepare(); + return ret; } -ErrorCode HiPlayer::HiPlayerImpl::DoPlay() +ErrorCode HiPlayerImpl::DoPlay() { - return pipeline->Start(); + (void)SetVolume(volume_); + auto ret = pipeline_->Start(); + if (ret == ErrorCode::SUCCESS) { + pipelineStates_ = PlayerStates::PLAYER_STARTED; + } + return ret; } -ErrorCode HiPlayer::HiPlayerImpl::DoPause() +ErrorCode HiPlayerImpl::DoPause() { - return pipeline->Pause(); + auto ret = pipeline_->Pause(); + if (ret == ErrorCode::SUCCESS) { + pipelineStates_ = PlayerStates::PLAYER_PAUSED; + } + return ret; } -ErrorCode HiPlayer::HiPlayerImpl::DoResume() +ErrorCode HiPlayerImpl::DoResume() { - return pipeline->Resume(); + (void)SetVolume(volume_); + auto ret = pipeline_->Resume(); + if (ret == ErrorCode::SUCCESS) { + pipelineStates_ = PlayerStates::PLAYER_STARTED; + } + return ret; } -ErrorCode HiPlayer::HiPlayerImpl::DoStop() +ErrorCode HiPlayerImpl::DoStop() { - return pipeline->Stop(); + auto ret = pipeline_->Stop(); + if (ret == ErrorCode::SUCCESS) { + pipelineStates_ = PlayerStates::PLAYER_STOPPED; + } + return ret; } -ErrorCode HiPlayer::HiPlayerImpl::DoSeek(int64_t msec) +ErrorCode HiPlayerImpl::DoSeek(int64_t msec) { - pipeline->FlushStart(); - pipeline->FlushEnd(); - return demuxer->SeekTo(msec); + { + pipeline_->FlushStart(); + pipeline_->FlushEnd(); + } + auto rtv = demuxer_->SeekTo(msec); + auto ptr = callback_.lock(); + if (ptr != nullptr) { + ptr->OnRewindToComplete(); + } + return rtv; } -ErrorCode HiPlayer::HiPlayerImpl::DoOnReady() +ErrorCode HiPlayerImpl::DoOnReady() { - sourceMeta_ = demuxer->GetGlobalMetaInfo(); + pipelineStates_ = PlayerStates::PLAYER_PREPARED; + sourceMeta_ = demuxer_->GetGlobalMetaInfo(); streamMeta_.clear(); - for (auto& streamMeta : demuxer->GetStreamMetaInfo()) { + for (auto& streamMeta : demuxer_->GetStreamMetaInfo()) { streamMeta_.push_back(streamMeta); } - return SUCCESS; + return ErrorCode::SUCCESS; } -ErrorCode HiPlayer::HiPlayerImpl::DoOnComplete() +ErrorCode HiPlayerImpl::DoOnComplete() { - MEDIA_LOG_W("OnComplete looping: %d.", singleLoop.load()); - if (!singleLoop) { + MEDIA_LOG_W("OnComplete looping: %d.", singleLoop_.load()); + if (!singleLoop_) { StopAsync(); } else { fsm_.SendEventAsync(Intent::SEEK, static_cast(0)); @@ -239,40 +318,76 @@ ErrorCode HiPlayer::HiPlayerImpl::DoOnComplete() if (ptr != nullptr) { ptr->OnPlaybackComplete(); } - return SUCCESS; + return ErrorCode::SUCCESS; } -ErrorCode HiPlayer::HiPlayerImpl::DoOnError(ErrorCode errorCode) +ErrorCode HiPlayerImpl::DoOnError(ErrorCode errorCode) { - // fixme do we need to callback here to notify registered callback + errorCode_ = errorCode; auto ptr = callback_.lock(); if (ptr != nullptr) { - ptr->OnError(PlayerCallback::PLAYER_ERROR_UNKNOWN, errorCode); + ptr->OnError(PlayerCallback::PLAYER_ERROR_UNKNOWN, static_cast(errorCode)); } - return SUCCESS; + pipelineStates_ = PlayerStates::PLAYER_STATE_ERROR; + return ErrorCode::SUCCESS; +} + +bool HiPlayerImpl::IsSingleLooping() +{ + return singleLoop_.load(); +} + +int32_t HiPlayerImpl::SetLoop(bool loop) +{ + singleLoop_ = loop; + return to_underlying(ErrorCode::SUCCESS); +} + +void HiPlayerImpl::SetPlayerCallback(const std::shared_ptr& cb) +{ + callback_ = cb; } -bool HiPlayer::HiPlayerImpl::IsSingleLooping() +int32_t HiPlayerImpl::Reset() { - return singleLoop; + Stop(); + pipelineStates_ = PlayerStates::PLAYER_IDLE; + singleLoop_ = false; + return to_underlying(ErrorCode::SUCCESS); } -ErrorCode HiPlayer::HiPlayerImpl::GetCurrentTime(int64_t& time) const +int32_t HiPlayerImpl::Release() { - return demuxer->GetCurrentTime(time); + return Reset(); } -ErrorCode HiPlayer::HiPlayerImpl::GetDuration(size_t& time) const +int32_t HiPlayerImpl::DeInit() +{ + return Reset(); +} + +int32_t HiPlayerImpl::GetPlayerState(int32_t& state) +{ + state = static_cast(pipelineStates_.load()); + return to_underlying(ErrorCode::SUCCESS); +} + +int32_t HiPlayerImpl::GetCurrentPosition(int64_t& currentPositionMs) +{ + return to_underlying(demuxer_->GetCurrentTime(currentPositionMs)); +} + +int32_t HiPlayerImpl::GetDuration(int64_t& outDurationMs) { uint64_t duration = 0; auto sourceMeta = sourceMeta_.lock(); if (sourceMeta == nullptr) { - time = 0; - return NOT_FOUND; + outDurationMs = 0; + return to_underlying(ErrorCode::ERROR_NOT_FOUND); } if (sourceMeta->GetUint64(Media::Plugin::MetaID::MEDIA_DURATION, duration)) { - time = duration; - return SUCCESS; + outDurationMs = duration; + return to_underlying(ErrorCode::SUCCESS); } // use max stream duration as whole source duration if source meta does not contains the duration meta uint64_t tmp = 0; @@ -285,34 +400,37 @@ ErrorCode HiPlayer::HiPlayerImpl::GetDuration(size_t& time) const } } if (found) { - time = duration; - return SUCCESS; + outDurationMs = duration; + return to_underlying(ErrorCode::SUCCESS); } - return NOT_FOUND; + return to_underlying(ErrorCode::ERROR_NOT_FOUND); } -ErrorCode HiPlayer::HiPlayerImpl::SetVolume(float volume) +ErrorCode HiPlayerImpl::SetVolume(float volume) { - if (audioSink != nullptr) { - return audioSink->SetVolume(volume); + if (audioSink_ == nullptr) { + MEDIA_LOG_W("cannot set volume while audio sink filter is null"); + return ErrorCode::ERROR_NULL_POINTER; } - MEDIA_LOG_W("cannot set volume while audio sink filter is null"); - return NULL_POINTER_ERROR; -} - -ErrorCode HiPlayer::HiPlayerImpl::SetCallback(const std::shared_ptr& callback) -{ - callback_ = callback; - return ErrorCode::SUCCESS; + ErrorCode ret = ErrorCode::SUCCESS; + if (volume > 0) { + MEDIA_LOG_I("set volume %.3f", volume); + ret = audioSink_->SetVolume(volume); + } + if (ret != ErrorCode::SUCCESS) { + MEDIA_LOG_E("SetVolume failed with error %d", static_cast(ret)); + } + return ret; } -void HiPlayer::HiPlayerImpl::OnStateChanged(StateId state) +void HiPlayerImpl::OnStateChanged(StateId state) { + OSAL::ScopedLock lock(stateMutex_); + curFsmState_ = state; cond_.NotifyOne(); } -ErrorCode HiPlayer::HiPlayerImpl::OnCallback(const FilterCallbackType& type, Filter* filter, - const Plugin::Any& parameter) +ErrorCode HiPlayerImpl::OnCallback(const FilterCallbackType& type, Filter* filter, const Plugin::Any& parameter) { ErrorCode ret = ErrorCode::SUCCESS; switch (type) { @@ -331,35 +449,35 @@ ErrorCode HiPlayer::HiPlayerImpl::OnCallback(const FilterCallbackType& type, Fil return ret; } -ErrorCode HiPlayer::HiPlayerImpl::GetStreamCnt(size_t& cnt) const +ErrorCode HiPlayerImpl::GetStreamCnt(size_t& cnt) const { cnt = streamMeta_.size(); - return SUCCESS; + return ErrorCode::SUCCESS; } -ErrorCode HiPlayer::HiPlayerImpl::GetSourceMeta(shared_ptr& meta) const +ErrorCode HiPlayerImpl::GetSourceMeta(shared_ptr& meta) const { meta = sourceMeta_.lock(); - return meta ? SUCCESS : NOT_FOUND; + return meta ? ErrorCode::SUCCESS : ErrorCode::ERROR_NOT_FOUND; } -ErrorCode HiPlayer::HiPlayerImpl::GetStreamMeta(size_t index, shared_ptr& meta) const +ErrorCode HiPlayerImpl::GetStreamMeta(size_t index, shared_ptr& meta) const { if (index > streamMeta_.size() || index < 0) { - return INVALID_PARAM_VALUE; + return ErrorCode::ERROR_INVALID_PARAM_VALUE; } meta = streamMeta_[index].lock(); if (meta == nullptr) { - return NOT_FOUND; + return ErrorCode::ERROR_NOT_FOUND; } - return SUCCESS; + return ErrorCode::SUCCESS; } -ErrorCode HiPlayer::HiPlayerImpl::NewAudioPortFound(Filter* filter, const Plugin::Any& parameter) +ErrorCode HiPlayerImpl::NewAudioPortFound(Filter* filter, const Plugin::Any& parameter) { - ErrorCode rtv = PORT_UNEXPECTED; + ErrorCode rtv = ErrorCode::ERROR_PORT_UNEXPECTED; auto param = Plugin::AnyCast(parameter); - if (filter == demuxer.get() && param.type == PortType::OUT) { + if (filter == demuxer_.get() && param.type == PortType::OUT) { MEDIA_LOG_I("new port found on demuxer %zu", param.ports.size()); for (const auto& portDesc : param.ports) { if (!StringStartsWith(portDesc.name, "audio")) { @@ -368,18 +486,18 @@ ErrorCode HiPlayer::HiPlayerImpl::NewAudioPortFound(Filter* filter, const Plugin MEDIA_LOG_I("port name %s", portDesc.name.c_str()); auto fromPort = filter->GetOutPort(portDesc.name); if (portDesc.isPcm) { - pipeline->AddFilters({audioSink.get()}); - FAIL_LOG(pipeline->LinkPorts(fromPort, audioSink->GetInPort(PORT_NAME_DEFAULT))); - ActiveFilters({audioSink.get()}); + pipeline_->AddFilters({audioSink_.get()}); + FAIL_LOG(pipeline_->LinkPorts(fromPort, audioSink_->GetInPort(PORT_NAME_DEFAULT))); + ActiveFilters({audioSink_.get()}); } else { auto newAudioDecoder = CreateAudioDecoder(portDesc.name); - pipeline->AddFilters({newAudioDecoder.get(), audioSink.get()}); - FAIL_LOG(pipeline->LinkPorts(fromPort, newAudioDecoder->GetInPort(PORT_NAME_DEFAULT))); - FAIL_LOG(pipeline->LinkPorts(newAudioDecoder->GetOutPort(PORT_NAME_DEFAULT), - audioSink->GetInPort(PORT_NAME_DEFAULT))); - ActiveFilters({newAudioDecoder.get(), audioSink.get()}); + pipeline_->AddFilters({newAudioDecoder.get(), audioSink_.get()}); + FAIL_LOG(pipeline_->LinkPorts(fromPort, newAudioDecoder->GetInPort(PORT_NAME_DEFAULT))); + FAIL_LOG(pipeline_->LinkPorts(newAudioDecoder->GetOutPort(PORT_NAME_DEFAULT), + audioSink_->GetInPort(PORT_NAME_DEFAULT))); + ActiveFilters({newAudioDecoder.get(), audioSink_.get()}); } - rtv = SUCCESS; + rtv = ErrorCode::SUCCESS; break; } } @@ -387,11 +505,11 @@ ErrorCode HiPlayer::HiPlayerImpl::NewAudioPortFound(Filter* filter, const Plugin } #ifdef VIDEO_SUPPORT -ErrorCode HiPlayer::HiPlayerImpl::NewVideoPortFound(Filter* filter, const Plugin::Any& parameter) +ErrorCode HiPlayerImpl::NewVideoPortFound(Filter* filter, const Plugin::Any& parameter) { auto param = Plugin::AnyCast(parameter); - if (filter != demuxer.get() || param.type != PortType::OUT) { - return PORT_UNEXPECTED; + if (filter != demuxer_.get() || param.type != PortType::OUT) { + return ErrorCode::ERROR_PORT_UNEXPECTED; } std::vector newFilters; for (const auto& portDesc : param.ports) { @@ -399,36 +517,36 @@ ErrorCode HiPlayer::HiPlayerImpl::NewVideoPortFound(Filter* filter, const Plugin MEDIA_LOG_I("port name %s", portDesc.name.c_str()); videoDecoder = FilterFactory::Instance().CreateFilterWithType( "builtin.player.videodecoder", "videodecoder-" + portDesc.name); - if (pipeline->AddFilters({videoDecoder.get()}) != ALREADY_EXISTS) { + if (pipeline_->AddFilters({videoDecoder.get()}) != ErrorCode::ERROR_ALREADY_EXISTS) { // link demuxer and video decoder auto fromPort = filter->GetOutPort(portDesc.name); auto toPort = videoDecoder->GetInPort(PORT_NAME_DEFAULT); - FAIL_LOG(pipeline->LinkPorts(fromPort, toPort)); // link ports + FAIL_LOG(pipeline_->LinkPorts(fromPort, toPort)); // link ports newFilters.emplace_back(videoDecoder.get()); // link video decoder and video sink - if (pipeline->AddFilters({videoSink.get()}) != ALREADY_EXISTS) { + if (pipeline_->AddFilters({videoSink.get()}) != ErrorCode::ERROR_ALREADY_EXISTS) { fromPort = videoDecoder->GetOutPort(PORT_NAME_DEFAULT); toPort = videoSink->GetInPort(PORT_NAME_DEFAULT); - FAIL_LOG(pipeline->LinkPorts(fromPort, toPort)); // link ports + FAIL_LOG(pipeline_->LinkPorts(fromPort, toPort)); // link ports newFilters.push_back(videoSink.get()); } } - break; } + break; } if (!newFilters.empty()) { ActiveFilters(newFilters); } - return SUCCESS; + return ErrorCode::SUCCESS; } #endif -ErrorCode HiPlayer::HiPlayerImpl::RemoveFilterChains(Filter* filter, const Plugin::Any& parameter) +ErrorCode HiPlayerImpl::RemoveFilterChains(Filter* filter, const Plugin::Any& parameter) { - ErrorCode ret = SUCCESS; + ErrorCode ret = ErrorCode::SUCCESS; auto param = Plugin::AnyCast(parameter); - if (filter != demuxer.get() || param.type != PortType::OUT) { + if (filter != demuxer_.get() || param.type != PortType::OUT) { return ret; } for (const auto& portDesc : param.ports) { @@ -437,14 +555,14 @@ ErrorCode HiPlayer::HiPlayerImpl::RemoveFilterChains(Filter* filter, const Plugi if (peerPort) { auto nextFilter = const_cast(dynamic_cast(peerPort->GetOwnerFilter())); if (nextFilter) { - pipeline->RemoveFilterChain(nextFilter); + pipeline_->RemoveFilterChain(nextFilter); } } } return ret; } -void HiPlayer::HiPlayerImpl::ActiveFilters(const std::vector& filters) +void HiPlayerImpl::ActiveFilters(const std::vector& filters) { for (auto it = filters.rbegin(); it != filters.rend(); ++it) { (*it)->Prepare(); diff --git a/engine/player/hiplayer_impl.h b/engine/player/hiplayer_impl.h index 9f404ce74d01da3d9764f7c5767c43b64fd6cc51..255a7a0098b5e0578ba558efcb3d7244a8651fa4 100644 --- a/engine/player/hiplayer_impl.h +++ b/engine/player/hiplayer_impl.h @@ -26,64 +26,97 @@ #endif #include "filters/demux/demuxer_filter.h" #include "filters/source/media_source_filter.h" -#include "osal/thread/condition_variable.h" -#include "osal/thread/mutex.h" #include "foundation/error_code.h" -#include "utils/utils.h" #include "histreamer/hiplayer.h" #include "internal/state_machine.h" +#include "osal/thread/condition_variable.h" +#include "osal/thread/mutex.h" #include "pipeline/core/filter_callback.h" #include "pipeline/core/pipeline.h" #include "pipeline/core/pipeline_core.h" #include "pipeline/filters/codec/audio_decoder/audio_decoder_filter.h" #include "pipeline/filters/sink/audio_sink/audio_sink_filter.h" #include "play_executor.h" +#include "utils/utils.h" namespace OHOS { namespace Media { -class HiPlayer::HiPlayerImpl : public Pipeline::EventReceiver, - public PlayExecutor, - public StateChangeCallback, - public Pipeline::FilterCallback { +class HiPlayerImpl : public Pipeline::EventReceiver, + public PlayExecutor, + public StateChangeCallback, + public Pipeline::FilterCallback, + public PlayerInterface { friend class StateMachine; public: ~HiPlayerImpl() override; - static std::shared_ptr CreateHiPlayerImpl(); + static std::shared_ptr CreateHiPlayerImpl(); + + // interface from PlayerInterface + int32_t Init() override; + int32_t DeInit() override; + int32_t SetSource(const Source& source) override; + int32_t Prepare() override; + int32_t Play() override; + bool IsPlaying() override; + int32_t Pause() override; + int32_t Stop() override; + int32_t Reset() override; + int32_t Release() override; + int32_t Rewind(int64_t mSeconds, int32_t mode) override; + int32_t SetVolume(float leftVolume, float rightVolume) override; +#ifndef SURFACE_DISABLED + int32_t SetSurface(Surface* surface) override; +#endif + bool IsSingleLooping() override; + int32_t SetLoop(bool loop) override; + void SetPlayerCallback(const std::shared_ptr& cb) override; + int32_t GetPlayerState(int32_t& state) override; + int32_t GetCurrentPosition(int64_t& currentPositionMs) override; + int32_t GetDuration(int64_t& outDurationMs) override; + int32_t GetVideoWidth(int32_t& videoWidth) override + { + return to_underlying(ErrorCode::ERROR_UNIMPLEMENTED); + } + int32_t GetVideoHeight(int32_t& videoHeight) override + { + return to_underlying(ErrorCode::ERROR_UNIMPLEMENTED); + } + int32_t SetPlaybackSpeed(float speed) override + { + return to_underlying(ErrorCode::ERROR_UNIMPLEMENTED); + } + int32_t GetPlaybackSpeed(float& speed) override + { + return to_underlying(ErrorCode::ERROR_UNIMPLEMENTED); + } + int32_t SetAudioStreamType(int32_t type) override + { + return to_underlying(ErrorCode::ERROR_UNIMPLEMENTED); + } + void GetAudioStreamType(int32_t& type) override + { + type = -1; + } + + int32_t SetParameter(const Format& params) override + { + return to_underlying(ErrorCode::ERROR_UNIMPLEMENTED); + } - void Init(); void OnEvent(Event event) override; - ErrorCode Prepare(); - ErrorCode Play(); - ErrorCode Pause(); ErrorCode Resume(); - ErrorCode Stop(); - // interface from MediaSource - ErrorCode SetSource(std::shared_ptr source); ErrorCode SetBufferSize(size_t size); - ErrorCode Seek(size_t time, size_t& position); - ErrorCode SetSingleLoop(bool loop); - bool IsSingleLooping(); - - /** - * get duration in milliseconds - * - * @param time milliseconds - * @return - */ - ErrorCode GetDuration(size_t& time) const; - ErrorCode GetCurrentTime(int64_t& time) const; + ErrorCode GetSourceMeta(std::shared_ptr& meta) const; ErrorCode GetStreamCnt(size_t& cnt) const; ErrorCode GetStreamMeta(size_t index, std::shared_ptr& meta) const; ErrorCode SetVolume(float volume); - ErrorCode SetCallback(const std::shared_ptr& callback); - void OnStateChanged(StateId state) override; ErrorCode OnCallback(const Pipeline::FilterCallbackType& type, Pipeline::Filter* filter, @@ -119,27 +152,34 @@ private: void ActiveFilters(const std::vector& filters); private: - OSAL::Mutex mutex_; + OSAL::Mutex stateMutex_; OSAL::ConditionVariable cond_; StateMachine fsm_; - std::shared_ptr pipeline; + std::atomic curFsmState_; - std::shared_ptr audioSource; - std::shared_ptr demuxer; - std::shared_ptr audioDecoder; - std::shared_ptr audioSink; + std::shared_ptr pipeline_; + std::atomic pipelineStates_; + std::atomic initialized_{false}; + + std::shared_ptr audioSource_; + + std::shared_ptr demuxer_; + std::shared_ptr audioDecoder_; + std::shared_ptr audioSink_; #ifdef VIDEO_SUPPORT std::shared_ptr videoDecoder; std::shared_ptr videoSink; #endif - std::unordered_map> audioDecoderMap; + std::unordered_map> audioDecoderMap_; std::weak_ptr sourceMeta_; std::vector> streamMeta_; - std::atomic singleLoop{false}; - bool initialized = false; + std::atomic singleLoop_{false}; + std::weak_ptr callback_; + float volume_; + std::atomic errorCode_; }; } // namespace Media } // namespace OHOS diff --git a/engine/player/internal/init_state.h b/engine/player/internal/init_state.h index faba745192e3f103aa26824bd4f40fea464319f3..28df357713b5036b5f44e7abb1c05ee8b3f8bcd5 100644 --- a/engine/player/internal/init_state.h +++ b/engine/player/internal/init_state.h @@ -39,7 +39,7 @@ public: std::shared_ptr source; if (param.Type() != typeid(std::shared_ptr) || !(source = Plugin::AnyCast>(param))) { - return {INVALID_SOURCE, Action::ACTION_BUTT}; + return {ErrorCode::ERROR_INVALID_SOURCE, Action::ACTION_BUTT}; } auto ret = executor_.DoSetSource(source); return {ret, Action::TRANS_TO_PREPARING}; @@ -47,7 +47,7 @@ public: std::tuple Stop() override { - return {SUCCESS, Action::TRANS_TO_INIT}; + return {ErrorCode::SUCCESS, Action::TRANS_TO_INIT}; } std::tuple Enter(Intent) override diff --git a/engine/player/internal/pause_state.h b/engine/player/internal/pause_state.h index ac0cc82d4412b373750776617ae422c40d3a3619..b1eb91358f3870c47d9d7c43a10e9e831b8a3530 100644 --- a/engine/player/internal/pause_state.h +++ b/engine/player/internal/pause_state.h @@ -42,14 +42,14 @@ public: std::tuple Play() override { MEDIA_LOG_D("Play in pause state."); - return {SUCCESS, Action::TRANS_TO_PLAYING}; + return {ErrorCode::SUCCESS, Action::TRANS_TO_PLAYING}; } std::tuple Seek(const Plugin::Any& param) override { MEDIA_LOG_D("Seek in pause state."); if (param.Type() != typeid(int64_t)) { - return {INVALID_PARAM_VALUE, Action::ACTION_BUTT}; + return {ErrorCode::ERROR_INVALID_PARAM_VALUE, Action::ACTION_BUTT}; } auto timeMs = Plugin::AnyCast(param); auto ret = executor_.DoSeek(timeMs); @@ -59,13 +59,13 @@ public: std::tuple Resume() override { MEDIA_LOG_D("Resume in pause state."); - return {SUCCESS, Action::TRANS_TO_PLAYING}; + return {ErrorCode::SUCCESS, Action::TRANS_TO_PLAYING}; } std::tuple Stop() override { MEDIA_LOG_D("Stop called in pause state."); - return {SUCCESS, Action::TRANS_TO_INIT}; + return {ErrorCode::SUCCESS, Action::TRANS_TO_INIT}; } }; } // namespace Media diff --git a/engine/player/internal/playing_state.h b/engine/player/internal/playing_state.h index 8e11f275d728894d446e718f54f52b8167553c10..6059df864f8402d47b9e90121a42d901f97e16ee 100644 --- a/engine/player/internal/playing_state.h +++ b/engine/player/internal/playing_state.h @@ -46,14 +46,14 @@ public: std::tuple Play() override { - return {SUCCESS, Action::ACTION_BUTT}; + return {ErrorCode::SUCCESS, Action::ACTION_BUTT}; } std::tuple Seek(const Plugin::Any& param) override { MEDIA_LOG_D("Seek in playing state."); if (param.Type() != typeid(int64_t)) { - return {INVALID_PARAM_VALUE, Action::ACTION_BUTT}; + return {ErrorCode::ERROR_INVALID_PARAM_VALUE, Action::ACTION_BUTT}; } auto timeMs = Plugin::AnyCast(param); auto ret = executor_.DoSeek(timeMs); @@ -62,12 +62,12 @@ public: std::tuple Pause() override { - return {SUCCESS, Action::TRANS_TO_PAUSE}; + return {ErrorCode::SUCCESS, Action::TRANS_TO_PAUSE}; } std::tuple Stop() override { - return {SUCCESS, Action::TRANS_TO_INIT}; + return {ErrorCode::SUCCESS, Action::TRANS_TO_INIT}; } std::tuple OnComplete() override diff --git a/engine/player/internal/preparing_state.h b/engine/player/internal/preparing_state.h index e60992dddc00828a48a2c90b3d36df34c0fb3bec..0fc36546ad3cf1454485d636cff7fff4e7607a95 100644 --- a/engine/player/internal/preparing_state.h +++ b/engine/player/internal/preparing_state.h @@ -38,7 +38,7 @@ public: (void)intent; Action nextAction = Action::ACTION_BUTT; auto rtv = executor_.PrepareFilters(); - if (rtv != SUCCESS) { + if (rtv != ErrorCode::SUCCESS) { nextAction = Action::TRANS_TO_INIT; } return {rtv, nextAction}; @@ -47,14 +47,14 @@ public: std::tuple Play() override { MEDIA_LOG_W("Play received in preparing state."); - return {SUCCESS, Action::ACTION_PENDING}; + return {ErrorCode::SUCCESS, Action::ACTION_PENDING}; } std::tuple Seek(const Plugin::Any& param) override { MEDIA_LOG_D("Seek in preparing state."); if (param.Type() != typeid(int64_t)) { - return {INVALID_PARAM_VALUE, Action::ACTION_BUTT}; + return {ErrorCode::ERROR_INVALID_PARAM_VALUE, Action::ACTION_BUTT}; } auto timeMs = Plugin::AnyCast(param); auto ret = executor_.DoSeek(timeMs); @@ -63,12 +63,12 @@ public: std::tuple Stop() override { - return {SUCCESS, Action::TRANS_TO_INIT}; + return {ErrorCode::SUCCESS, Action::TRANS_TO_INIT}; } std::tuple OnReady() override { - return {SUCCESS, Action::TRANS_TO_READY}; + return {ErrorCode::SUCCESS, Action::TRANS_TO_READY}; } }; } // namespace Media diff --git a/engine/player/internal/ready_state.h b/engine/player/internal/ready_state.h index fefa5ffefab9675da9f1acc9c90262309a938cd3..22260fe64203f84388e07cff5550cd5d466114dc 100644 --- a/engine/player/internal/ready_state.h +++ b/engine/player/internal/ready_state.h @@ -36,14 +36,18 @@ public: { (void)intent; auto rtv = executor_.DoOnReady(); - return {rtv, Action::ACTION_BUTT}; + if (rtv == ErrorCode::SUCCESS) { + return {rtv, Action::ACTION_BUTT}; + } else { + return {rtv, Action::TRANS_TO_INIT}; + } } std::tuple Seek(const Plugin::Any& param) override { MEDIA_LOG_D("Seek in ready state."); if (param.Type() != typeid(int64_t)) { - return {INVALID_PARAM_VALUE, Action::ACTION_BUTT}; + return {ErrorCode::ERROR_INVALID_PARAM_VALUE, Action::ACTION_BUTT}; } auto timeMs = Plugin::AnyCast(param); auto ret = executor_.DoSeek(timeMs); @@ -53,13 +57,13 @@ public: std::tuple Play() override { MEDIA_LOG_D("Play in ready state."); - return {SUCCESS, Action::TRANS_TO_PLAYING}; + return {ErrorCode::SUCCESS, Action::TRANS_TO_PLAYING}; } std::tuple Stop() override { MEDIA_LOG_D("Stop in ready state."); - return {SUCCESS, Action::TRANS_TO_INIT}; + return {ErrorCode::SUCCESS, Action::TRANS_TO_INIT}; } }; } // namespace Media diff --git a/engine/player/internal/state.cpp b/engine/player/internal/state.cpp index 0e38cc0a475cb2e14c20e27ab54b2f839ed45bc1..a6e6eb480632bf216fb4396b747ce74b6af01d4b 100644 --- a/engine/player/internal/state.cpp +++ b/engine/player/internal/state.cpp @@ -28,7 +28,7 @@ std::tuple State::Enter(Intent intent) { (void)intent; MEDIA_LOG_D("Enter state: %s", name_.c_str()); - return {SUCCESS, Action::ACTION_BUTT}; + return {ErrorCode::SUCCESS, Action::ACTION_BUTT}; } void State::Exit() { @@ -49,53 +49,53 @@ StateId State::GetStateId() std::tuple State::SetSource(const Plugin::Any& source) { (void)source; - return {INVALID_OPERATION, Action::ACTION_BUTT}; + return {ErrorCode::ERROR_INVALID_OPERATION, Action::ACTION_BUTT}; } std::tuple State::Play() { - return {INVALID_OPERATION, Action::ACTION_BUTT}; + return {ErrorCode::ERROR_INVALID_OPERATION, Action::ACTION_BUTT}; } std::tuple State::Stop() { - return {INVALID_OPERATION, Action::ACTION_BUTT}; + return {ErrorCode::ERROR_INVALID_OPERATION, Action::ACTION_BUTT}; } std::tuple State::Pause() { - return {INVALID_OPERATION, Action::ACTION_BUTT}; + return {ErrorCode::ERROR_INVALID_OPERATION, Action::ACTION_BUTT}; } std::tuple State::Resume() { - return {INVALID_OPERATION, Action::ACTION_BUTT}; + return {ErrorCode::ERROR_INVALID_OPERATION, Action::ACTION_BUTT}; } std::tuple State::Seek(const Plugin::Any& param) { (void)param; - return {INVALID_OPERATION, Action::ACTION_BUTT}; + return {ErrorCode::ERROR_INVALID_OPERATION, Action::ACTION_BUTT}; } std::tuple State::SetAttribute() { - return {INVALID_OPERATION, Action::ACTION_BUTT}; + return {ErrorCode::ERROR_INVALID_OPERATION, Action::ACTION_BUTT}; } std::tuple State::OnReady() { - return {INVALID_OPERATION, Action::ACTION_BUTT}; + return {ErrorCode::ERROR_INVALID_OPERATION, Action::ACTION_BUTT}; } std::tuple State::OnError(const Plugin::Any& param) { - ErrorCode errorCode = UNKNOWN_ERROR; + ErrorCode errorCode = ErrorCode::ERROR_UNKNOWN; if (param.Type() == typeid(ErrorCode)) { errorCode = Plugin::AnyCast(param); } executor_.DoOnError(errorCode); - return {SUCCESS, Action::TRANS_TO_INIT}; + return {ErrorCode::SUCCESS, Action::TRANS_TO_INIT}; } std::tuple State::OnComplete() { - return {SUCCESS, Action::ACTION_BUTT}; + return {ErrorCode::SUCCESS, Action::ACTION_BUTT}; } std::tuple State::DispatchIntent(Intent intent, const Plugin::Any& param) { - ErrorCode rtv = SUCCESS; + ErrorCode rtv = ErrorCode::SUCCESS; Action nextAction = Action::ACTION_BUTT; switch (intent) { case Intent::SET_SOURCE: diff --git a/engine/player/internal/state_machine.cpp b/engine/player/internal/state_machine.cpp index 870e81f84cd7c8a58c5eb7971276e2aff7d4361d..0268bd11f3c460320266c343bc8e2d3a54278ef8 100644 --- a/engine/player/internal/state_machine.cpp +++ b/engine/player/internal/state_machine.cpp @@ -61,10 +61,10 @@ ErrorCode StateMachine::SendEvent(Intent intent, const Plugin::Any& param) const ErrorCode StateMachine::SendEvent(Intent intent, const Plugin::Any& param) { - SendEventAsync(intent, param); constexpr int timeoutMs = 5000; - ErrorCode errorCode = ERROR_TIMEOUT; - if (!intentSync_.WaitFor(intent, timeoutMs, errorCode)) { + ErrorCode errorCode = ErrorCode::ERROR_TIMEOUT; + if (!intentSync_.WaitFor( + intent, [this, intent, param] { SendEventAsync(intent, param); }, timeoutMs, errorCode)) { MEDIA_LOG_E("SendEvent timeout, intent: %d", static_cast(intent)); } return errorCode; @@ -79,7 +79,7 @@ ErrorCode StateMachine::SendEventAsync(Intent intent, const Plugin::Any& param) { MEDIA_LOG_D("SendEventAsync, intent: %d", static_cast(intent)); jobs_.Push([this, intent, param]() -> Action { return ProcessIntent(intent, param); }); - return SUCCESS; + return ErrorCode::SUCCESS; } Action StateMachine::ProcessIntent(Intent intent, const Plugin::Any& param) @@ -87,19 +87,19 @@ Action StateMachine::ProcessIntent(Intent intent, const Plugin::Any& param) MEDIA_LOG_D("ProcessIntent, curState: %s, intent: %d.", curState_->GetName().c_str(), intent); OSAL::ScopedLock lock(mutex_); lastIntent = intent; - ErrorCode rtv = SUCCESS; + ErrorCode rtv = ErrorCode::SUCCESS; Action nextAction = Action::ACTION_BUTT; std::tie(rtv, nextAction) = curState_->Execute(intent, param); - if (rtv == SUCCESS) { + if (rtv == ErrorCode::SUCCESS) { rtv = ProcAction(nextAction); } OnIntentExecuted(intent, nextAction, rtv); - return (rtv == SUCCESS) ? nextAction : Action::ACTION_BUTT; + return (rtv == ErrorCode::SUCCESS) ? nextAction : Action::ACTION_BUTT; } void StateMachine::DoTask() { - constexpr int timeoutMs = 100; + constexpr int timeoutMs = 500; auto job = jobs_.Pop(timeoutMs); if (!job) { return; @@ -158,7 +158,7 @@ ErrorCode StateMachine::ProcAction(Action nextAction) default: break; } - ErrorCode ret = SUCCESS; + ErrorCode ret = ErrorCode::SUCCESS; if (nextState) { ret = TransitionTo(nextState); } @@ -169,15 +169,15 @@ ErrorCode StateMachine::TransitionTo(const std::shared_ptr& state) { if (state == nullptr) { MEDIA_LOG_E("TransitionTo, nullptr for state"); - return NULL_POINTER_ERROR; + return ErrorCode::ERROR_NULL_POINTER; } - ErrorCode rtv = SUCCESS; + ErrorCode rtv = ErrorCode::SUCCESS; if (state != curState_) { curState_->Exit(); curState_ = state; Action nextAction; std::tie(rtv, nextAction) = curState_->Enter(lastIntent); - if (rtv == SUCCESS) { + if (rtv == ErrorCode::SUCCESS) { rtv = ProcAction(nextAction); } if (callback_) { diff --git a/engine/player/play_executor.h b/engine/player/play_executor.h index bef1a01a062acafb6d7e7bcd26f03e1f12a83976..6930a06e9a5587f186c976359177c793440f10ad 100644 --- a/engine/player/play_executor.h +++ b/engine/player/play_executor.h @@ -32,55 +32,55 @@ public: virtual ErrorCode PrepareFilters() { - return SUCCESS; + return ErrorCode::SUCCESS; } virtual ErrorCode DoSetSource(const std::shared_ptr& source) const { (void)source; - return SUCCESS; + return ErrorCode::SUCCESS; } virtual ErrorCode DoPlay() { - return SUCCESS; + return ErrorCode::SUCCESS; } virtual ErrorCode DoPause() { - return SUCCESS; + return ErrorCode::SUCCESS; } virtual ErrorCode DoResume() { - return SUCCESS; + return ErrorCode::SUCCESS; } virtual ErrorCode DoStop() { - return SUCCESS; + return ErrorCode::SUCCESS; } virtual ErrorCode DoSeek(int64_t msec) { (void)msec; - return SUCCESS; + return ErrorCode::SUCCESS; } virtual ErrorCode DoOnReady() { - return SUCCESS; + return ErrorCode::SUCCESS; } virtual ErrorCode DoOnComplete() { - return SUCCESS; + return ErrorCode::SUCCESS; } virtual ErrorCode DoOnError(ErrorCode errorCode) { (void)errorCode; - return SUCCESS; + return ErrorCode::SUCCESS; } }; } // namespace Media diff --git a/engine/plugin/BUILD.gn b/engine/plugin/BUILD.gn index ad4f82b9f9cac82875ff760c38aee7b12ef2589b..a439cb8f3f5f6aaed01aab8c46ae926ff66cfde2 100644 --- a/engine/plugin/BUILD.gn +++ b/engine/plugin/BUILD.gn @@ -27,7 +27,6 @@ if (defined(ohos_lite)) { deps = [ ":histreamer_plugin_core", ":histreamer_plugin_intf", - "plugins:gen_plungin_static_header", "plugins:histreamer_plugin_store", ] } @@ -47,7 +46,11 @@ if (defined(ohos_lite)) { } sources = hst_plugin_intf_src public_configs = [ ":hst_plugin_intf_config" ] - public_deps = [ "//third_party/bounds_checking_function:libsec_shared" ] + if (ohos_kernel_type == "liteos_m") { + public_deps = [ "//third_party/bounds_checking_function:libsec_static" ] + } else { + public_deps = [ "//third_party/bounds_checking_function:libsec_shared" ] + } cflags = [ "-Wall" ] cflags_cc = cflags } @@ -73,7 +76,6 @@ if (defined(ohos_lite)) { "//foundation/multimedia/histreamer/engine/foundation", "//foundation/multimedia/histreamer/engine/utils", "//foundation/multimedia/utils/lite/interfaces/kits", - "${target_gen_dir}/plugins/include/", ] } @@ -94,8 +96,13 @@ if (defined(ohos_lite)) { ":histreamer_plugin_intf", "//foundation/multimedia/histreamer/engine/foundation:histreamer_foundation", "//foundation/multimedia/histreamer/engine/utils:histreamer_utils", - "//third_party/bounds_checking_function:libsec_shared", ] + if (ohos_kernel_type == "liteos_m") { + public_deps += [ "//third_party/bounds_checking_function:libsec_static" ] + } else { + public_deps += [ "//third_party/bounds_checking_function:libsec_shared" ] + } + public_deps += [ "plugins:gen_plugin_static_header" ] cflags = [ "-Wall" ] cflags_cc = cflags } diff --git a/engine/plugin/common/plugin_tags.h b/engine/plugin/common/plugin_tags.h index 580755fe9ee606b7aa95e1a9cacb7984ff2df2a2..4a08ae7e6ee62c53061b776dfed0ca91164310e5 100644 --- a/engine/plugin/common/plugin_tags.h +++ b/engine/plugin/common/plugin_tags.h @@ -79,6 +79,7 @@ enum struct Tag : uint32_t { MIME = SECTION_REGULAR_START + 1, // string STREAM_INDEX, // uint32_t REQUIRED_OUT_BUFFER_CNT, // uint32_t required buffer count of plugin; read only tag + PARAMETER_STRUCT, // ParameterStruct /* -------------------- media tag -------------------- */ MEDIA_TITLE = SECTION_MEDIA_START + 1, // string @@ -105,7 +106,7 @@ enum struct Tag : uint32_t { AUDIO_CHANNEL_LAYOUT, // AudioChannelLayout AUDIO_SAMPLE_RATE, // uint32_t AUDIO_SAMPLE_FORMAT, // AudioSampleFormat - AUDIO_SAMPLE_PRE_FRAME, // uint32_t + AUDIO_SAMPLE_PER_FRAME, // uint32_t /* -------------------- audio specific tag -------------------- */ AUDIO_SPECIFIC_MPEG_START = MAKE_AUDIO_SPECIFIC_START(AudioFormat::MPEG), @@ -129,6 +130,32 @@ using ValueType = Any; * The tag content is stored in key-value format. */ using TagMap = std::map; + +/** + * @enum Direction + * + * @since 1.0 + * @version 1.0 + */ +enum struct Direction : uint8_t { + IN = 1<<0U, ///< in direction + OUT = 1<<1U, ///< out direction +}; + +/** + * @brief parameter struct, which can be used in PluginBase.SetParameter for complex parameter setting. + * + * @since 1.0 + * @version 1.0 + */ +struct ParameterStruct { + uint32_t direction {static_cast(Direction::IN) | + static_cast(Direction::OUT)}; ///< direction of parameter, default is in and out + int32_t streamIndex { + -1}; ///< indicates stream that will be effected by this parameter, -1 means that all stream will be effected + Tag tagId; ///< parameter tag id + ValueType value; ///< value of the parameter +}; } // namespace Plugin } // namespace Media } // namespace OHOS diff --git a/engine/plugin/core/plugin_manager.cpp b/engine/plugin/core/plugin_manager.cpp index 46e99ba7de4afa327e10a8a10ddf72947db470cf..c05ac095e3f129df18dfcc4f8be6f4b41ddbf580 100644 --- a/engine/plugin/core/plugin_manager.cpp +++ b/engine/plugin/core/plugin_manager.cpp @@ -51,6 +51,9 @@ std::shared_ptr PluginManager::GetPluginInfo(PluginType type, const int32_t PluginManager::Sniffer(const std::string& name, std::shared_ptr source) { + if (source == nullptr) { + return 0; + } std::shared_ptr regInfo = pluginRegister->GetPluginRegInfo(PluginType::DEMUXER, name); if (!regInfo) { return 0; diff --git a/engine/plugin/core/plugin_meta.h b/engine/plugin/core/plugin_meta.h index 4daeb7d57208bade1e704d3ab0dc92888fc08350..76258bc832d11b14d5706af5fc2c848f32bb53f0 100644 --- a/engine/plugin/core/plugin_meta.h +++ b/engine/plugin/core/plugin_meta.h @@ -42,7 +42,7 @@ enum struct MetaID : uint32_t { AUDIO_CHANNELS = to_underlying(Tag::AUDIO_CHANNELS), AUDIO_SAMPLE_RATE = to_underlying(Tag::AUDIO_SAMPLE_RATE), AUDIO_SAMPLE_FORMAT = to_underlying(Tag::AUDIO_SAMPLE_FORMAT), - AUDIO_SAMPLE_PRE_FRAME = to_underlying(Tag::AUDIO_SAMPLE_PRE_FRAME), + AUDIO_SAMPLE_PER_FRAME = to_underlying(Tag::AUDIO_SAMPLE_PER_FRAME), AUDIO_CHANNEL_LAYOUT = to_underlying(Tag::AUDIO_CHANNEL_LAYOUT), MEDIA_TITLE = to_underlying(Tag::MEDIA_TITLE), diff --git a/engine/plugin/core/plugin_wrapper.cpp b/engine/plugin/core/plugin_wrapper.cpp index a426f5c040339bf1e45acb99db1119634ffa7d30..1a10c55c1b33e40d43f9d3ab52866f2b6260d46c 100644 --- a/engine/plugin/core/plugin_wrapper.cpp +++ b/engine/plugin/core/plugin_wrapper.cpp @@ -25,7 +25,7 @@ std::set g_metaIdSet = { OHOS::Media::Plugin::MetaID::AUDIO_CHANNELS, OHOS::Media::Plugin::MetaID::AUDIO_SAMPLE_RATE, OHOS::Media::Plugin::MetaID::AUDIO_SAMPLE_FORMAT, - OHOS::Media::Plugin::MetaID::AUDIO_SAMPLE_PRE_FRAME, + OHOS::Media::Plugin::MetaID::AUDIO_SAMPLE_PER_FRAME, OHOS::Media::Plugin::MetaID::AUDIO_CHANNEL_LAYOUT, OHOS::Media::Plugin::MetaID::MEDIA_TITLE, OHOS::Media::Plugin::MetaID::MEDIA_ARTIST, diff --git a/engine/plugin/plugins/BUILD.gn b/engine/plugin/plugins/BUILD.gn index ebadb5388315a5a776b8181926a615025d6a0159..8216b7729a0167bd7162c2eb01489584c0064c22 100644 --- a/engine/plugin/plugins/BUILD.gn +++ b/engine/plugin/plugins/BUILD.gn @@ -14,17 +14,41 @@ if (defined(ohos_lite)) { import("//build/lite/config/component/lite_component.gni") + import("//build/lite/config/subsystem/multimedia/config.gni") + + print("histreamer plugin config:enable_histreamer_plugin_ffmpeg_adapter =", + enable_histreamer_plugin_ffmpeg_adapter) + print("histreamer plugin config:enable_histreamer_plugin_hdi_adapter =", + enable_histreamer_plugin_hdi_adapter) + print("histreamer plugin config:enable_histreamer_plugin_file_source =", + enable_histreamer_plugin_file_source) + print("histreamer plugin config:enable_histreamer_plugin_stream_source =", + enable_histreamer_plugin_stream_source) group("histreamer_plugin_store") { - deps = [ - "ffmpeg_adapter:plugin_ffmpeg_adapter", - "hdi_adapter:plugin_hdi_adapter", - "source/file_source:plugin_file_source", - "source/stream_source:plugin_stream_source", - ] + deps = [] + if (enable_histreamer_plugin_ffmpeg_adapter) { + deps += [ "ffmpeg_adapter:plugin_ffmpeg_adapter" ] + } + + if (enable_histreamer_plugin_file_source) { + deps += [ "source/file_source:plugin_file_source" ] + } + + if (enable_histreamer_plugin_hdi_adapter) { + deps += [ "hdi_adapter:plugin_hdi_adapter" ] + } + + if (enable_histreamer_plugin_stream_source) { + deps += [ "source/stream_source:plugin_stream_source" ] + } + } + + config("gen_plugin_static_header_config") { + include_dirs = [ "${target_gen_dir}/include/" ] } - action("gen_plungin_static_header") { + action("gen_plugin_static_header") { script = "//foundation/multimedia/histreamer/engine/plugin/plugins/plugin_config.py" args = [ @@ -34,15 +58,28 @@ if (defined(ohos_lite)) { ] if (ohos_kernel_type == "liteos_m") { - args += [ - "FileSource", - "StreamSource", - "FFmpegDemuxer", - "FFmpegAudioDecoders", - "HdiAuSink", - ] + if (enable_histreamer_plugin_ffmpeg_adapter) { + args += [ + "FFmpegDemuxer", + "FFmpegAudioDecoders", + ] + } + + if (enable_histreamer_plugin_file_source) { + args += [ "FileSource" ] + } + + if (enable_histreamer_plugin_hdi_adapter) { + args += [ "HdiAuSink" ] + } + + if (enable_histreamer_plugin_stream_source) { + args += [ "StreamSource" ] + } } outputs = [ "${target_gen_dir}/include/all_plugin_static.h" ] + + public_configs = [ ":gen_plugin_static_header_config" ] } } diff --git a/engine/plugin/plugins/ffmpeg_adapter/BUILD.gn b/engine/plugin/plugins/ffmpeg_adapter/BUILD.gn index 766209a2594c6e45efde1213eefd32241228acac..f67e768dc83dd6125b84846255a052e0e88a645e 100644 --- a/engine/plugin/plugins/ffmpeg_adapter/BUILD.gn +++ b/engine/plugin/plugins/ffmpeg_adapter/BUILD.gn @@ -14,11 +14,12 @@ if (defined(ohos_lite)) { import("//build/lite/config/component/lite_component.gni") + import("//build/lite/config/subsystem/multimedia/config.gni") group("plugin_ffmpeg_adapter") { deps = [] } if (ohos_kernel_type == "liteos_m") { - print("unsupport static library") + # make static build if needed. current is not supported } else { config("plugin_ffmpeg_adapter_config") { include_dirs = [ "//third_party/ffmpeg" ] diff --git a/engine/plugin/plugins/ffmpeg_adapter/demuxer/ffmpeg_track_meta.cpp b/engine/plugin/plugins/ffmpeg_adapter/demuxer/ffmpeg_track_meta.cpp index 5e494a7bb1c25466b082dc83cdd0504240e352de..6f3db290f70c9ce832c214e936657457bf095ddf 100644 --- a/engine/plugin/plugins/ffmpeg_adapter/demuxer/ffmpeg_track_meta.cpp +++ b/engine/plugin/plugins/ffmpeg_adapter/demuxer/ffmpeg_track_meta.cpp @@ -71,7 +71,7 @@ void ConvertCommonAudioStreamToMetaInfo(const AVStream& avStream, const std::sha if (!IsPcmStream(avStream)) { samplesPerFrame = static_cast(context->frame_size); } - meta.insert({Tag::AUDIO_SAMPLE_PRE_FRAME, samplesPerFrame}); + meta.insert({Tag::AUDIO_SAMPLE_PER_FRAME, samplesPerFrame}); meta.insert({Tag::AUDIO_SAMPLE_FORMAT, Trans2Format(context->sample_fmt)}); meta.insert({Tag::MEDIA_BITRATE, static_cast(context->bit_rate)}); } @@ -144,7 +144,7 @@ void ConvertAACLatmStreamToMetaInfo(const AVStream& avStream, const std::shared_ meta.insert({Tag::AUDIO_SAMPLE_FORMAT, Trans2Format(context->sample_fmt)}); meta.insert( {Tag::AUDIO_CHANNEL_LAYOUT, ConvertChannelLayoutFromFFmpeg(context->channels, context->channel_layout)}); - meta.insert({Tag::AUDIO_SAMPLE_PRE_FRAME, static_cast(context->frame_size)}); + meta.insert({Tag::AUDIO_SAMPLE_PER_FRAME, static_cast(context->frame_size)}); meta.insert({Tag::MEDIA_BITRATE, static_cast(context->bit_rate)}); } meta.insert({Tag::AUDIO_MPEG_VERSION, static_cast(4)}); // 4 diff --git a/engine/plugin/plugins/ffmpeg_adapter/utils/ffmpeg_utils.cpp b/engine/plugin/plugins/ffmpeg_adapter/utils/ffmpeg_utils.cpp index bd1711aa6f8d6bd69101c34c27313e0145d6c878..c7beced2f3b0adfc91fe28fae16887fbcf619c80 100644 --- a/engine/plugin/plugins/ffmpeg_adapter/utils/ffmpeg_utils.cpp +++ b/engine/plugin/plugins/ffmpeg_adapter/utils/ffmpeg_utils.cpp @@ -236,7 +236,7 @@ AudioSampleFormat Trans2Format(AVSampleFormat sampleFormat) case AV_SAMPLE_FMT_DBLP: return AudioSampleFormat::F64P; default: - return AudioSampleFormat::U8; + return AudioSampleFormat::S16; } } diff --git a/engine/plugin/plugins/hdi_adapter/sink/hos_au_sink.cpp b/engine/plugin/plugins/hdi_adapter/sink/hos_au_sink.cpp index 7b4afbd91bb0c2c28a1c8ec35299c762d4e0f338..d894e807b7bd107e961ef5df8d973d4c8d27bb6d 100644 --- a/engine/plugin/plugins/hdi_adapter/sink/hos_au_sink.cpp +++ b/engine/plugin/plugins/hdi_adapter/sink/hos_au_sink.cpp @@ -18,17 +18,17 @@ #include "hos_au_sink.h" #include #include -#include "securec.h" -#include "audio_proxy_manager.h" #include "audio_adapter.h" +#include "audio_proxy_manager.h" #include "foundation/log.h" #include "foundation/osal/thread/scoped_lock.h" -#include "utils/constants.h" -#include "utils/utils.h" #include "foundation/osal/utils/util.h" #include "plugin/common/plugin_audio_tags.h" #include "plugins/hdi_adapter/utils/hdi_au_utils.h" #include "ring_buffer.h" +#include "securec.h" +#include "utils/constants.h" +#include "utils/utils.h" namespace { using namespace OHOS::Media::Plugin; @@ -39,10 +39,9 @@ constexpr int32_t HI_ERR_VI_BUF_FULL = 0xA016800F; constexpr int32_t RANK100 = 100; constexpr int32_t HALF = 2; constexpr int32_t SEC_TO_MILLS = 1000; -constexpr float MAX_VOLUME = 300.f; +constexpr int32_t PCM_CHAN_CNT = 2; - -Status LoadAndInitAdapter(AudioManager *proxyManager, AudioAdapterDescriptor *descriptor, AudioAdapter **adapter) +Status LoadAndInitAdapter(AudioManager* proxyManager, AudioAdapterDescriptor* descriptor, AudioAdapter** adapter) { if (proxyManager == nullptr) { MEDIA_LOG_E("no audio manager when load adapter"); @@ -80,7 +79,7 @@ Status LoadAndInitAdapter(AudioManager *proxyManager, AudioAdapterDescriptor *de return Status::OK; } -std::shared_ptr AudioSinkPluginCreator(const std::string &name) +std::shared_ptr AudioSinkPluginCreator(const std::string& name) { return std::make_shared(name); } @@ -93,15 +92,15 @@ Status RegisterHdiSinkPlugins(const std::shared_ptr& reg) return Status::ERROR_UNKNOWN; } int32_t adapterSize = 0; - AudioAdapterDescriptor *descriptors = nullptr; + AudioAdapterDescriptor* descriptors = nullptr; int32_t ret = proxyManager->GetAllAdapters(proxyManager, &descriptors, &adapterSize); if (ret != 0 || adapterSize == 0) { MEDIA_LOG_E("cannot find available audio adapter"); return Status::OK; } for (int32_t index = 0; index < adapterSize; index++) { - AudioAdapter *adapter = nullptr; - const auto &desc = descriptors[index]; + AudioAdapter* adapter = nullptr; + const auto& desc = descriptors[index]; if (LoadAndInitAdapter(proxyManager, &descriptors[index], &adapter) != Status::OK) { continue; } @@ -132,11 +131,11 @@ Status RegisterHdiSinkPlugins(const std::shared_ptr& reg) return Status::OK; } -template -inline Status AssignIfCastSuccess(T &lvalue, const Any& anyValue, const char* tagName) +template +inline Status AssignIfCastSuccess(T& lvalue, const Any& anyValue, const char* tagName) { if (typeid(T) == anyValue.Type()) { - lvalue = AnyCast(anyValue); + lvalue = AnyCast(anyValue); MEDIA_LOG_I("AssignIfCastSuccess found %s", tagName); return Status::OK; } else { @@ -145,20 +144,19 @@ inline Status AssignIfCastSuccess(T &lvalue, const Any& anyValue, const char* ta } } - -int32_t CalculateBufferSize(const AudioSampleAttributes &attributes) +int32_t CalculateBufferSize(const AudioSampleAttributes& attributes) { return attributes.frameSize * attributes.period; } PLUGIN_DEFINITION(HdiAuSink, LicenseType::APACHE_V2, RegisterHdiSinkPlugins, []() {}); -} +} // namespace namespace OHOS { namespace Media { namespace HosLitePlugin { using namespace OHOS::Media::Plugin; -HdiSink::HdiSink(std::string name) : Plugin::AudioSinkPlugin(std::move(name)), audioManager_(nullptr) +HdiSink::HdiSink(std::string name) : Plugin::AudioSinkPlugin(std::move(name)), audioManager_(nullptr), cacheData_() { // default is media sampleAttributes_.type = AUDIO_IN_MEDIA; @@ -167,28 +165,20 @@ HdiSink::HdiSink(std::string name) : Plugin::AudioSinkPlugin(std::move(name)), a Status HdiSink::Init() { MEDIA_LOG_D("Init entered."); - if (pluginState_ == State::DESTROYED) { - MEDIA_LOG_E("plugin has been already destroyed, cannot init any more"); - return Status::ERROR_WRONG_STATE; - } - if (pluginState_ != State::CREATED) { - MEDIA_LOG_I("plugin has been already inited"); - return Status::OK; - } audioManager_ = GetAudioManagerFuncs(); if (audioManager_ == nullptr) { MEDIA_LOG_E("Init error due to audioManager nullptr"); return Status::ERROR_UNKNOWN; } int32_t adapterSize = 0; - AudioAdapterDescriptor *descriptors = nullptr; + AudioAdapterDescriptor* descriptors = nullptr; int32_t ret = audioManager_->GetAllAdapters(audioManager_, &descriptors, &adapterSize); if (ret != 0 || adapterSize == 0) { MEDIA_LOG_E("cannot find available audio adapter"); return Status::ERROR_UNKNOWN; } for (int32_t index = 0; index < adapterSize; index++) { - const auto &desc = descriptors[index]; + const auto& desc = descriptors[index]; if (pluginName_ != desc.adapterName) { continue; } @@ -203,10 +193,9 @@ Status HdiSink::Init() return Status::ERROR_UNKNOWN; } if (!renderThread_) { - renderThread_ = std::make_shared("auRenderThread"); + renderThread_ = std::make_shared("auRenderThread", OSAL::ThreadPriority::HIGH); renderThread_->RegisterHandler([this] { DoRender(); }); } - pluginState_ = State::INITIALIZED; return Status::OK; } @@ -225,10 +214,7 @@ Media::Plugin::Status HdiSink::ReleaseRender() Status HdiSink::Deinit() { MEDIA_LOG_E("Deinit entered."); - if (pluginState_ == State::DESTROYED || pluginState_ == State::CREATED) { - MEDIA_LOG_I("no need to destroy"); - return Status::OK; - } + Stop(); if (renderThread_ != nullptr) { renderThread_->Stop(); } @@ -241,16 +227,11 @@ Status HdiSink::Deinit() } audioManager_ = nullptr; } - pluginState_ = State::DESTROYED; return Status::OK; } -Status HdiSink::SetParameter(Tag tag, const ValueType &value) +Status HdiSink::SetParameter(Tag tag, const ValueType& value) { - if (pluginState_ == State::DESTROYED || pluginState_ == State::CREATED) { - MEDIA_LOG_E("cannot set parameter in state %d", pluginState_.load()); - return Status::ERROR_WRONG_STATE; - } switch (tag) { case Tag::AUDIO_CHANNELS: return AssignIfCastSuccess(sampleAttributes_.channelCount, value, "channel"); @@ -263,14 +244,20 @@ Status HdiSink::SetParameter(Tag tag, const ValueType &value) return ret; } if (PluginAuFormat2HdiAttrs(format, sampleAttributes_)) { + // always configure hdi with non-interleaved + if (sampleAttributes_.interleaved) { + isInputInterleaved_ = true; + sampleAttributes_.interleaved = false; + } else { + isInputInterleaved_ = false; + } return Status::OK; } else { MEDIA_LOG_E("audioSampleFormat mismatch"); - ret = Status::ERROR_MISMATCHED_TYPE; - break; + return Status::ERROR_MISMATCHED_TYPE; } } - case Tag::AUDIO_SAMPLE_PRE_FRAME: + case Tag::AUDIO_SAMPLE_PER_FRAME: return AssignIfCastSuccess(sampleAttributes_.period, value, "samples per frame"); case Tag::AUDIO_CHANNEL_LAYOUT: { AudioChannelLayout layout; @@ -291,7 +278,7 @@ Status HdiSink::SetParameter(Tag tag, const ValueType &value) return Status::OK; } -Status HdiSink::GetParameter(Tag tag, ValueType &value) +Status HdiSink::GetParameter(Tag tag, ValueType& value) { UNUSED_VARIABLE(tag); UNUSED_VARIABLE(value); @@ -300,14 +287,6 @@ Status HdiSink::GetParameter(Tag tag, ValueType &value) Status HdiSink::Prepare() { - if (pluginState_ != State::PREPARED && pluginState_ != State::INITIALIZED) { - MEDIA_LOG_E("cannot prepare in state %d", pluginState_.load()); - return Status::ERROR_WRONG_STATE; - } - if (pluginState_ == State::PREPARED) { - return Status::OK; - } - sampleAttributes_.frameSize = GetPcmBytes(sampleAttributes_.format) * sampleAttributes_.channelCount; sampleAttributes_.startThreshold = sampleAttributes_.period / sampleAttributes_.frameSize; sampleAttributes_.stopThreshold = INT32_MAX; @@ -328,12 +307,12 @@ Status HdiSink::Prepare() deviceDescriptor_.pins = PIN_OUT_SPEAKER; deviceDescriptor_.desc = nullptr; - MEDIA_LOG_I("create render on adapter: %s, port: %d, with parameters: category %s, channels %d, sampleRate %d," - " audioChannelMask %x, format %d, isSignedData %d, interleaved %d, period %u, frameSize %u", - adapterDescriptor_.adapterName, deviceDescriptor_.portId, - (sampleAttributes_.type == AUDIO_IN_MEDIA) ? "media" : "communication", sampleAttributes_.channelCount, - sampleAttributes_.sampleRate, channelMask_, sampleAttributes_.format, sampleAttributes_.isSignedData, - sampleAttributes_.interleaved, sampleAttributes_.period, sampleAttributes_.frameSize); + MEDIA_LOG_I("create render: %s, port: %d:\ncategory %s,\nchannels %d, sampleRate %d,\n" + " audioChannelMask %x, format %d,\nisSignedData %d, interleaved %d,\nperiod %u, frameSize %u", + adapterDescriptor_.adapterName, deviceDescriptor_.portId, + (sampleAttributes_.type == AUDIO_IN_MEDIA) ? "media" : "communication", sampleAttributes_.channelCount, + sampleAttributes_.sampleRate, channelMask_, sampleAttributes_.format, sampleAttributes_.isSignedData, + sampleAttributes_.interleaved, sampleAttributes_.period, sampleAttributes_.frameSize); { OHOS::Media::OSAL::ScopedLock lock(renderMutex_); @@ -345,27 +324,26 @@ Status HdiSink::Prepare() } } MEDIA_LOG_I("create audio render successfully"); - ringBuffer_ = std::make_shared(DEFAULT_BUFFER_POOL_SIZE * CalculateBufferSize(sampleAttributes_)); + auto bufferSize = DEFAULT_BUFFER_POOL_SIZE * CalculateBufferSize(sampleAttributes_); + ringBuffer_ = std::make_shared(bufferSize); if (!ringBuffer_->Init()) { MEDIA_LOG_E("cannot allocate enough buffer for ring buffer cache"); return Status::ERROR_NO_MEMORY; } - - pluginState_ = State::PREPARED; + if ((sampleAttributes_.channelCount == PCM_CHAN_CNT) && isInputInterleaved_) { + cacheData_.resize(CalculateBufferSize(sampleAttributes_)); + } return Status::OK; } Status HdiSink::Reset() { MEDIA_LOG_D("Reset entered."); - if (pluginState_ != State::PREPARED && pluginState_ != State::RUNNING && pluginState_ != State::PAUSED) { - MEDIA_LOG_I("cannot reset in state %d", pluginState_.load()); - return Status::ERROR_WRONG_STATE; - } ReleaseRender(); (void)memset_s(&audioPort_, sizeof(audioPort_), 0, sizeof(audioPort_)); (void)memset_s(&sampleAttributes_, sizeof(sampleAttributes_), 0, sizeof(sampleAttributes_)); (void)memset_s(&deviceDescriptor_, sizeof(deviceDescriptor_), 0, sizeof(deviceDescriptor_)); + isInputInterleaved_ = false; channelMask_ = AUDIO_CHANNEL_MONO; return Status::OK; @@ -374,14 +352,6 @@ Status HdiSink::Reset() Status HdiSink::Start() { MEDIA_LOG_D("Start entered."); - if (pluginState_ != State::PREPARED && pluginState_ != State::RUNNING && pluginState_ != State::PAUSED) { - MEDIA_LOG_E("cannot Start in state %d", pluginState_.load()); - return Status::ERROR_WRONG_STATE; - } - if (pluginState_ == State::RUNNING) { - MEDIA_LOG_I("already in running state, ignore start"); - return Status::OK; - } { OHOS::Media::OSAL::ScopedLock lock(renderMutex_); if (audioRender_ == nullptr) { @@ -395,27 +365,26 @@ Status HdiSink::Start() } } ringBuffer_->SetActive(true); + shouldRenderFrame_ = true; renderThread_->Start(); - pluginState_ = State::RUNNING; return Status::OK; } Status HdiSink::Stop() { MEDIA_LOG_D("Stop Entered"); - if (pluginState_ != State::RUNNING && pluginState_ != State::PAUSED) { - MEDIA_LOG_W("Stop is called when not running or paused, ignore it"); - return Status::OK; - } + shouldRenderFrame_ = false; ringBuffer_->SetActive(false); renderThread_->Pause(); - pluginState_ = State::PREPARED; { OHOS::Media::OSAL::ScopedLock lock(renderMutex_); if (audioRender_ == nullptr) { MEDIA_LOG_E("no available render"); return Status::OK; } + if (audioRender_->control.Flush(audioRender_) != 0) { + MEDIA_LOG_E("audio render flush error"); + } if (audioRender_->control.Stop(audioRender_) != 0) { MEDIA_LOG_E("audio render stop error"); return Status::ERROR_UNKNOWN; @@ -436,13 +405,13 @@ std::shared_ptr HdiSink::GetAllocator() return nullptr; } -Status HdiSink::SetCallback(const std::shared_ptr &cb) +Status HdiSink::SetCallback(const std::shared_ptr& cb) { eventCallback_ = cb; return Status::OK; } -Status HdiSink::GetMute(bool &mute) +Status HdiSink::GetMute(bool& mute) { OHOS::Media::OSAL::ScopedLock lock(renderMutex_); if (audioRender_ == nullptr) { @@ -471,7 +440,7 @@ Status HdiSink::SetMute(bool mute) return Status::OK; } -Status HdiSink::GetVolume(float &volume) +Status HdiSink::GetVolume(float& volume) { OHOS::Media::OSAL::ScopedLock lock(renderMutex_); if (audioRender_ == nullptr) { @@ -482,7 +451,6 @@ Status HdiSink::GetVolume(float &volume) MEDIA_LOG_E("get volume failed"); return Status::ERROR_UNKNOWN; } - volume /= MAX_VOLUME; return Status::OK; } @@ -493,16 +461,17 @@ Status HdiSink::SetVolume(float volume) MEDIA_LOG_W("no render available, set volume must be called after prepare"); return Status::ERROR_WRONG_STATE; } - auto relVolume = volume * MAX_VOLUME; + constexpr float maxVolume = 100.0f; + auto relVolume = volume * maxVolume; if (audioRender_->volume.SetVolume(audioRender_, relVolume) != 0) { MEDIA_LOG_E("set volume failed"); return Status::ERROR_UNKNOWN; } - MEDIA_LOG_W("set volume to %.3f", volume); + MEDIA_LOG_W("set volume to %.3f", relVolume); return Status::OK; } -Status HdiSink::GetSpeed(float &speed) +Status HdiSink::GetSpeed(float& speed) { OHOS::Media::OSAL::ScopedLock lock(renderMutex_); if (audioRender_ == nullptr) { @@ -533,12 +502,8 @@ Status HdiSink::SetSpeed(float speed) Status HdiSink::Pause() { MEDIA_LOG_D("Pause Entered"); - if (pluginState_ != State::RUNNING) { - MEDIA_LOG_I("pause in status %d, ignore pause", pluginState_.load()); - return Status::OK; - } + shouldRenderFrame_ = false; renderThread_->Pause(); - { OHOS::Media::OSAL::ScopedLock lock(renderMutex_); if (audioRender_ != nullptr && audioRender_->control.Pause(audioRender_) != 0) { @@ -546,17 +511,12 @@ Status HdiSink::Pause() return Status::ERROR_UNKNOWN; } } - pluginState_ = State::PAUSED; return Status::OK; } Status HdiSink::Resume() { MEDIA_LOG_D("Resume Entered"); - if (pluginState_ != State::PAUSED) { - MEDIA_LOG_I("resume in status %d, ignore pause", pluginState_.load()); - return Status::OK; - } { OHOS::Media::OSAL::ScopedLock lock(renderMutex_); if (audioRender_ != nullptr && audioRender_->control.Resume(audioRender_) != 0) { @@ -564,12 +524,12 @@ Status HdiSink::Resume() return Status::ERROR_UNKNOWN; } } + shouldRenderFrame_ = true; renderThread_->Start(); - pluginState_ = State::RUNNING; return Status::OK; } -Status HdiSink::GetLatency(uint64_t &ms) +Status HdiSink::GetLatency(uint64_t& ms) { OHOS::Media::OSAL::ScopedLock lock(renderMutex_); if (audioRender_ == nullptr) { @@ -585,25 +545,21 @@ Status HdiSink::GetLatency(uint64_t &ms) return Status::OK; } -Status HdiSink::GetFrameSize(size_t &size) +Status HdiSink::GetFrameSize(size_t& size) { UNUSED_VARIABLE(size); return Status::ERROR_UNIMPLEMENTED; } -Status HdiSink::GetFrameCount(uint32_t &count) +Status HdiSink::GetFrameCount(uint32_t& count) { UNUSED_VARIABLE(count); return Status::ERROR_UNIMPLEMENTED; } -Status HdiSink::Write(const std::shared_ptr &input) +Status HdiSink::Write(const std::shared_ptr& input) { MEDIA_LOG_D("Write begin."); - if (pluginState_ != State::RUNNING) { - MEDIA_LOG_E("cannot write buffer until enter running state"); - return Status::ERROR_WRONG_STATE; - } if (input != nullptr && !input->IsEmpty()) { ringBuffer_->WriteBuffer(input); MEDIA_LOG_D("write to ring buffer"); @@ -632,13 +588,67 @@ Status HdiSink::Flush() return Status::OK; } +template +static void Deinterleave(T inData, T outData, int32_t frameCnt) +{ + int32_t frameSize = frameCnt / PCM_CHAN_CNT; + for (int i = 0; i < PCM_CHAN_CNT; i++) { + for (int j = 0; j < frameSize; j++) { + outData[i * frameSize + j] = inData[j * PCM_CHAN_CNT + i]; + } + } +} + +void HdiSink::Deinterleave16(uint8_t* inData, uint8_t* outData, int32_t frameCnt) +{ + if (sampleAttributes_.isSignedData == true) { + Deinterleave(reinterpret_cast(inData), reinterpret_cast(outData), frameCnt); + } else { + Deinterleave(reinterpret_cast(inData), reinterpret_cast(outData), frameCnt); + } +} + +void HdiSink::Deinterleave8(uint8_t* inData, uint8_t* outData, int32_t frameCnt) +{ + if (sampleAttributes_.isSignedData == true) { + Deinterleave(reinterpret_cast(inData), reinterpret_cast(outData), frameCnt); + } else { + Deinterleave(inData, outData, frameCnt); + } +} + +void HdiSink::Deinterleave32(uint8_t* inData, uint8_t* outData, int32_t frameCnt) +{ + if (sampleAttributes_.isSignedData == true) { + Deinterleave(reinterpret_cast(inData), reinterpret_cast(outData), frameCnt); + } else { + Deinterleave(reinterpret_cast(inData), reinterpret_cast(outData), frameCnt); + } +} + +bool HdiSink::HandleInterleaveData(uint8_t* origData, int32_t frameCnt) +{ + if ((sampleAttributes_.channelCount != PCM_CHAN_CNT) || !isInputInterleaved_) { + return false; + } + bool isHandled = true; + switch (sampleAttributes_.format) { + case AUDIO_FORMAT_PCM_16_BIT: + Deinterleave16(origData, cacheData_.data(), frameCnt); + break; + default: + isHandled = false; + break; + } + return isHandled; +} + void HdiSink::DoRender() { MEDIA_LOG_D("DoRender started"); - if (pluginState_ != State::RUNNING) { + if (!shouldRenderFrame_.load()) { return; } - size_t outSize = 0; auto outFramePtr = ringBuffer_->ReadBufferWithoutAdvance(CalculateBufferSize(sampleAttributes_), outSize); if (outFramePtr == nullptr || outSize == 0) { @@ -649,15 +659,18 @@ void HdiSink::DoRender() { OHOS::Media::OSAL::ScopedLock lock(renderMutex_); if (audioRender_ != nullptr) { - ret = audioRender_->RenderFrame(audioRender_, outFramePtr.get(), outSize, &renderSize); + uint8_t* frame = outFramePtr.get(); + if (HandleInterleaveData(frame, outSize / PCM_CHAN_CNT)) { + frame = cacheData_.data(); + } + ret = audioRender_->RenderFrame(audioRender_, frame, outSize, &renderSize); } } if (ret != 0) { if (ret == HI_ERR_VI_BUF_FULL) { MEDIA_LOG_I("renderFrame buffer full"); - uint32_t latency = sampleAttributes_.period * SEC_TO_MILLS / sampleAttributes_.sampleRate; - MEDIA_LOG_D("latency origin %" PRIu32 "ms", latency); - OHOS::Media::OSAL::SleepFor(latency / HALF); + constexpr int intervalMs = 5; + OHOS::Media::OSAL::SleepFor(intervalMs); } else { MEDIA_LOG_E("renderFrame error with code %" PRIu64 "x", static_cast(ret)); } @@ -670,6 +683,6 @@ void HdiSink::DoRender() ringBuffer_->Advance(renderSize); } } -} -} -} +} // namespace HosLitePlugin +} // namespace Media +} // namespace OHOS diff --git a/engine/plugin/plugins/hdi_adapter/sink/hos_au_sink.h b/engine/plugin/plugins/hdi_adapter/sink/hos_au_sink.h index 9e6a4abd23e41078635b06c8cff514ea185210d0..b465a1af417e19e4628eb843caf44df5009addac 100644 --- a/engine/plugin/plugins/hdi_adapter/sink/hos_au_sink.h +++ b/engine/plugin/plugins/hdi_adapter/sink/hos_au_sink.h @@ -17,6 +17,7 @@ #define HISTREAMER_HDI_SINK_H #include +#include #include "audio_types.h" #include "foundation/osal/thread/mutex.h" #include "foundation/osal/thread/condition_variable.h" @@ -90,13 +91,21 @@ public: private: Media::Plugin::Status ReleaseRender(); + void Deinterleave8(uint8_t* inData, uint8_t* outData, int32_t frameCnt); + + void Deinterleave16(uint8_t* inData, uint8_t* outData, int32_t frameCnt); + + void Deinterleave32(uint8_t* inData, uint8_t* outData, int32_t frameCnt); + + bool HandleInterleaveData(uint8_t* origData, int32_t frameCnt); + void DoRender(); private: - std::atomic pluginState_ {OHOS::Media::Plugin::State::CREATED}; - OHOS::Media::OSAL::Mutex renderMutex_ {}; + std::atomic shouldRenderFrame_ {false}; + AudioManager* audioManager_ {nullptr}; AudioAdapterDescriptor adapterDescriptor_ {}; AudioAdapter* audioAdapter_ {nullptr}; @@ -104,12 +113,14 @@ private: AudioPort audioPort_ {}; AudioDeviceDescriptor deviceDescriptor_ {}; AudioSampleAttributes sampleAttributes_ {}; + bool isInputInterleaved_{false}; AudioChannelMask channelMask_ {AUDIO_CHANNEL_MONO}; std::weak_ptr eventCallback_ {}; std::shared_ptr ringBuffer_ {}; std::shared_ptr renderThread_ {}; + std::vector cacheData_; }; } } diff --git a/engine/plugin/plugins/hdi_adapter/utils/hdi_au_utils.cpp b/engine/plugin/plugins/hdi_adapter/utils/hdi_au_utils.cpp index e4ecbdd2408cc5f0e9c19cbe7cef3194642ba17e..b0f511cc86f0791af80fb2b69b4e62b135d2053d 100644 --- a/engine/plugin/plugins/hdi_adapter/utils/hdi_au_utils.cpp +++ b/engine/plugin/plugins/hdi_adapter/utils/hdi_au_utils.cpp @@ -32,18 +32,18 @@ struct PluginHdiAudioFormatTable { }; PluginHdiAudioFormatTable g_phft[] = { - {AUDIO_FORMAT_PCM_8_BIT, false, false, false, OHOS::Media::Plugin::AudioSampleFormat::U8}, - {AUDIO_FORMAT_PCM_8_BIT, false, true, false, OHOS::Media::Plugin::AudioSampleFormat::U8P}, - {AUDIO_FORMAT_PCM_8_BIT, true, false, false, OHOS::Media::Plugin::AudioSampleFormat::S8}, - {AUDIO_FORMAT_PCM_8_BIT, true, true, false, OHOS::Media::Plugin::AudioSampleFormat::S8P}, - {AUDIO_FORMAT_PCM_16_BIT, false, false, false, OHOS::Media::Plugin::AudioSampleFormat::U16}, - {AUDIO_FORMAT_PCM_16_BIT, false, true, false, OHOS::Media::Plugin::AudioSampleFormat::U16P}, - {AUDIO_FORMAT_PCM_16_BIT, true, false, false, OHOS::Media::Plugin::AudioSampleFormat::S16}, - {AUDIO_FORMAT_PCM_16_BIT, true, true, false, OHOS::Media::Plugin::AudioSampleFormat::S16P}, - {AUDIO_FORMAT_PCM_32_BIT, false, false, false, OHOS::Media::Plugin::AudioSampleFormat::U32}, - {AUDIO_FORMAT_PCM_32_BIT, false, true, false, OHOS::Media::Plugin::AudioSampleFormat::U32P}, - {AUDIO_FORMAT_PCM_32_BIT, true, false, false, OHOS::Media::Plugin::AudioSampleFormat::S32}, - {AUDIO_FORMAT_PCM_32_BIT, true, true, false, OHOS::Media::Plugin::AudioSampleFormat::S32P}, + {AUDIO_FORMAT_PCM_8_BIT, false, true, false, OHOS::Media::Plugin::AudioSampleFormat::U8}, + {AUDIO_FORMAT_PCM_8_BIT, false, false, false, OHOS::Media::Plugin::AudioSampleFormat::U8P}, + {AUDIO_FORMAT_PCM_8_BIT, true, true, false, OHOS::Media::Plugin::AudioSampleFormat::S8}, + {AUDIO_FORMAT_PCM_8_BIT, true, false, false, OHOS::Media::Plugin::AudioSampleFormat::S8P}, + {AUDIO_FORMAT_PCM_16_BIT, false, true, false, OHOS::Media::Plugin::AudioSampleFormat::U16}, + {AUDIO_FORMAT_PCM_16_BIT, false, false, false, OHOS::Media::Plugin::AudioSampleFormat::U16P}, + {AUDIO_FORMAT_PCM_16_BIT, true, true, false, OHOS::Media::Plugin::AudioSampleFormat::S16}, + {AUDIO_FORMAT_PCM_16_BIT, true, false, false, OHOS::Media::Plugin::AudioSampleFormat::S16P}, + {AUDIO_FORMAT_PCM_32_BIT, false, true, false, OHOS::Media::Plugin::AudioSampleFormat::U32}, + {AUDIO_FORMAT_PCM_32_BIT, false, false, false, OHOS::Media::Plugin::AudioSampleFormat::U32P}, + {AUDIO_FORMAT_PCM_32_BIT, true, true, false, OHOS::Media::Plugin::AudioSampleFormat::S32}, + {AUDIO_FORMAT_PCM_32_BIT, true, false, false, OHOS::Media::Plugin::AudioSampleFormat::S32P}, }; std::pair g_phst[] = { diff --git a/engine/plugin/plugins/sink/sdl/audio_sink/sdl_audio_sink_plugin.cpp b/engine/plugin/plugins/sink/sdl/audio_sink/sdl_audio_sink_plugin.cpp index d0f06efd686cfff1f871a10396b675a38ea07a19..07c946ea195ef33e03c6c4c3b6d502373e649ffc 100644 --- a/engine/plugin/plugins/sink/sdl/audio_sink/sdl_audio_sink_plugin.cpp +++ b/engine/plugin/plugins/sink/sdl/audio_sink/sdl_audio_sink_plugin.cpp @@ -222,7 +222,7 @@ Status SdlAudioSinkPlugin::SetParameter(Tag tag, const ValueType& value) sampleRate_ = Plugin::AnyCast(value); break; } - case Tag::AUDIO_SAMPLE_PRE_FRAME: { + case Tag::AUDIO_SAMPLE_PER_FRAME: { RETURN_ERROR_IF_CHECK_ERROR(uint32_t); samplesPerFrame_ = Plugin::AnyCast(value); break; diff --git a/engine/plugin/plugins/source/file_source/file_source_plugin.cpp b/engine/plugin/plugins/source/file_source/file_source_plugin.cpp index 4a48a3231d20b1542ba9928c07e26dc7bae25618..655567a39543166ad8b8e83686511cec6a289dad 100644 --- a/engine/plugin/plugins/source/file_source/file_source_plugin.cpp +++ b/engine/plugin/plugins/source/file_source/file_source_plugin.cpp @@ -16,15 +16,17 @@ #define LOG_TAG "FileSourcePlugin" #include "file_source_plugin.h" +#include #include "foundation/log.h" +#include "plugin/common/plugin_buffer.h" #include "plugin/common/plugin_types.h" #include "plugin/core/plugin_manager.h" -#include "plugin/common/plugin_buffer.h" +#include "utils/utils.h" namespace OHOS { namespace Media { namespace Plugin { -std::shared_ptr FileSourcePluginCreater(const std::string &name) +std::shared_ptr FileSourcePluginCreater(const std::string& name) { return std::make_shared(name); } @@ -40,41 +42,42 @@ const Status FileSourceRegister(const std::shared_ptr& reg) return reg->AddPlugin(definition); } -PLUGIN_DEFINITION(FileSource, LicenseType::APACHE_V2, FileSourceRegister, []{}); +PLUGIN_DEFINITION(FileSource, LicenseType::APACHE_V2, FileSourceRegister, [] {}); void* FileSourceAllocator::Alloc(size_t size) { if (size == 0) { return nullptr; } - return reinterpret_cast(new (std::nothrow) uint8_t[size]); // NOLINT: cast + return reinterpret_cast(new (std::nothrow) uint8_t[size]); // NOLINT: cast } void FileSourceAllocator::Free(void* ptr) // NOLINT: void* { if (ptr != nullptr) { - delete[] (uint8_t *)ptr; + delete[](uint8_t*) ptr; } } FileSourcePlugin::FileSourcePlugin(std::string name) - : SourcePlugin(std::move(name)), state_(State::CREATED), fileSize_(0), isSeekable_(true), position_(0) + : SourcePlugin(std::move(name)), fp_(nullptr), fileSize_(0), isSeekable_(true), position_(0) { MEDIA_LOG_D("IN"); - state_ = State::CREATED; } FileSourcePlugin::~FileSourcePlugin() { MEDIA_LOG_D("IN"); - state_ = State::DESTROYED; + if (fp_) { + std::fclose(fp_); + fp_ = nullptr; + } } Status FileSourcePlugin::Init() { MEDIA_LOG_D("IN"); mAllocator_ = std::make_shared(); - state_ = State::INITIALIZED; return Status::OK; } @@ -82,14 +85,12 @@ Status FileSourcePlugin::Deinit() { MEDIA_LOG_D("IN"); CloseFile(); - state_ = State::DESTROYED; return Status::OK; } Status FileSourcePlugin::Prepare() { MEDIA_LOG_D("IN"); - state_ = State::PREPARED; return Status::OK; } @@ -97,40 +98,37 @@ Status FileSourcePlugin::Reset() { MEDIA_LOG_D("IN"); CloseFile(); - state_ = State::INITIALIZED; return Status::OK; } Status FileSourcePlugin::Start() { MEDIA_LOG_D("IN"); - state_ = State::RUNNING; return Status::OK; } Status FileSourcePlugin::Stop() { MEDIA_LOG_D("IN"); - state_ = State::PREPARED; return Status::OK; } bool FileSourcePlugin::IsParameterSupported(Tag tag) { MEDIA_LOG_D("IN"); - return true; + return false; } -Status FileSourcePlugin::GetParameter(Tag tag, ValueType &value) +Status FileSourcePlugin::GetParameter(Tag tag, ValueType& value) { MEDIA_LOG_D("IN"); - return Status::OK; + return Status::ERROR_UNIMPLEMENTED; } -Status FileSourcePlugin::SetParameter(Tag tag, const ValueType &value) +Status FileSourcePlugin::SetParameter(Tag tag, const ValueType& value) { MEDIA_LOG_D("IN"); - return Status::OK; + return Status::ERROR_UNIMPLEMENTED; } std::shared_ptr FileSourcePlugin::GetAllocator() @@ -139,19 +137,15 @@ std::shared_ptr FileSourcePlugin::GetAllocator() return mAllocator_; } -Status FileSourcePlugin::SetCallback(const std::shared_ptr &cb) +Status FileSourcePlugin::SetCallback(const std::shared_ptr& cb) { MEDIA_LOG_D("IN"); - return Status::OK; + return Status::ERROR_UNIMPLEMENTED; } Status FileSourcePlugin::SetSource(std::string& uri, std::shared_ptr> params) { MEDIA_LOG_D("IN"); - if (state_ != State::INITIALIZED) { - MEDIA_LOG_W("Wrong state: %d", state_); - return Status::ERROR_WRONG_STATE; - } auto err = ParseFileName(uri); if (err != Status::OK) { MEDIA_LOG_E("Parse file name from uri fail, uri: %s", uri.c_str()); @@ -160,9 +154,9 @@ Status FileSourcePlugin::SetSource(std::string& uri, std::shared_ptr &buffer, size_t expectedLen) +Status FileSourcePlugin::Read(std::shared_ptr& buffer, size_t expectedLen) { - if (fin_.eof() == true) { + if (std::feof(fp_)) { MEDIA_LOG_W("It is the end of file!"); return Status::END_OF_STREAM; } @@ -178,11 +172,9 @@ Status FileSourcePlugin::Read(std::shared_ptr &buffer, size_t expectedLe expectedLen = std::min(static_cast(fileSize_ - position_), expectedLen); expectedLen = std::min(bufData->GetCapacity(), expectedLen); - auto ptr = bufData->GetWritableData(expectedLen); - size_t offset = 0; - MEDIA_LOG_I("buffer addr %p offset %zu", ptr, offset); - fin_.read((char *)(ptr + offset), expectedLen); - bufData->GetWritableData(fin_.gcount()); + MEDIA_LOG_I("buffer position %zu, expectedLen %zu", position_, expectedLen); + auto size = std::fread(bufData->GetWritableData(expectedLen), sizeof(char), expectedLen, fp_); + bufData->GetWritableData(size); position_ += bufData->GetSize(); MEDIA_LOG_D("position_: %" PRIu64 ", readSize: %zu", position_, bufData->GetSize()); return Status::OK; @@ -191,7 +183,7 @@ Status FileSourcePlugin::Read(std::shared_ptr &buffer, size_t expectedLe Status FileSourcePlugin::GetSize(size_t& size) { MEDIA_LOG_D("IN"); - if (!fin_.is_open()) { + if (!fp_) { MEDIA_LOG_E("Need call SetSource() to open file first"); return Status::ERROR_WRONG_STATE; } @@ -208,20 +200,19 @@ bool FileSourcePlugin::IsSeekable() Status FileSourcePlugin::SeekTo(uint64_t offset) { - if (!fin_.is_open() || (offset > fileSize_) || (position_ == offset)) { + if (!fp_ || (offset > fileSize_) || (position_ == offset)) { MEDIA_LOG_E("Invalid operation"); return Status::ERROR_WRONG_STATE; } - fin_.clear(); - fin_.seekg(offset, std::ios::beg); - if (!fin_.good() || (fin_.tellg() != offset)) { - fin_.clear(); - fin_.seekg(position_, std::ios::beg); + std::clearerr(fp_); + if (std::fseek(fp_, static_cast(offset), SEEK_SET) != 0) { + std::clearerr(fp_); + (void)std::fseek(fp_, static_cast(position_), SEEK_SET); MEDIA_LOG_E("Seek to %" PRIu64, offset); return Status::ERROR_UNKNOWN; } position_ = offset; - if (fin_.eof()) { + if (std::feof(fp_)) { MEDIA_LOG_I("It is the end of file!"); } MEDIA_LOG_D("seek to position_: %" PRIu64 " success", position_); @@ -249,7 +240,7 @@ Status FileSourcePlugin::ParseFileName(std::string& uri) if (uri.find("///", pos) != std::string::npos) { pos += 3; // 3: offset } else if (uri.find("//", pos) != std::string::npos) { - pos += 2; // 2: offset + pos += 2; // 2: offset pos = uri.find('/', pos); // skip host name if (pos == std::string::npos) { MEDIA_LOG_E("Invalid file uri format: %s", uri.c_str()); @@ -265,37 +256,51 @@ Status FileSourcePlugin::ParseFileName(std::string& uri) return Status::OK; } +Status FileSourcePlugin::CheckFileStat() +{ + struct stat fileStat; + if (stat(fileName_.c_str(), &fileStat) < 0) { + MEDIA_LOG_E("Cannot get info from %s", fileName_.c_str()); + return Status::ERROR_UNKNOWN; + } + if (S_ISDIR(fileStat.st_mode)) { + MEDIA_LOG_E("%s is directory", fileName_.c_str()); + return Status::ERROR_UNSUPPORTED_FORMAT; + } + if (S_ISSOCK(fileStat.st_mode)){ + MEDIA_LOG_E("%s is a socket", fileName_.c_str()); + return Status::ERROR_UNSUPPORTED_FORMAT; + } + return Status::OK; +} + Status FileSourcePlugin::OpenFile() { MEDIA_LOG_D("IN"); + auto ret = CheckFileStat(); + if (ret != Status::OK) { + CloseFile(); + return ret; + } CloseFile(); - fin_.open(fileName_.c_str(), std::ios::in | std::ios::binary); - if (!fin_.is_open()) { + fp_ = std::fopen(fileName_.c_str(), "rb"); + if (fp_ == nullptr) { MEDIA_LOG_E("Fail to load file from %s", fileName_.c_str()); return Status::ERROR_UNKNOWN; } - fin_.seekg(0, fin_.end); - if (!fin_.good()) { - isSeekable_ = false; - MEDIA_LOG_E("Seek to end fail"); - return Status::ERROR_UNKNOWN; - } - fileSize_ = fin_.tellg(); - if (fileSize_ <= 0) { - isSeekable_ = false; - } + fileSize_ = GetFileSize(fileName_.c_str()); MEDIA_LOG_D("fileName_: %s, fileSize_: %zu", fileName_.c_str(), fileSize_); - fin_.seekg(0, fin_.beg); return Status::OK; } void FileSourcePlugin::CloseFile() { - if (fin_.is_open()) { + if (fp_) { MEDIA_LOG_I("close file"); - fin_.close(); + std::fclose(fp_); + fp_ = nullptr; } } -} -} -} +} // namespace Plugin +} // namespace Media +} // namespace OHOS diff --git a/engine/plugin/plugins/source/file_source/file_source_plugin.h b/engine/plugin/plugins/source/file_source/file_source_plugin.h index d21cfc932ddd6d2d71af858a4c7b52fc72744110..608cab2bc15c8aec3e11fa3556d8d263e7668826 100644 --- a/engine/plugin/plugins/source/file_source/file_source_plugin.h +++ b/engine/plugin/plugins/source/file_source/file_source_plugin.h @@ -16,7 +16,7 @@ #ifndef MEDIA_PIPELINE_FILE_SOURCE_PLUGIN_H #define MEDIA_PIPELINE_FILE_SOURCE_PLUGIN_H -#include +#include #include "plugin/common/plugin_types.h" #include "plugin/interface/source_plugin.h" @@ -26,7 +26,7 @@ namespace Plugin { class FileSourceAllocator : public Allocator { public: FileSourceAllocator() = default; - ~FileSourceAllocator() override= default; + ~FileSourceAllocator() override = default; void* Alloc(size_t size) override; void Free(void* ptr) override; // NOLINT: void* @@ -44,31 +44,31 @@ public: Status Start() override; Status Stop() override; bool IsParameterSupported(Tag tag) override; - Status GetParameter(Tag tag, ValueType &value) override; - Status SetParameter(Tag tag, const ValueType &value) override; + Status GetParameter(Tag tag, ValueType& value) override; + Status SetParameter(Tag tag, const ValueType& value) override; std::shared_ptr GetAllocator() override; - Status SetCallback(const std::shared_ptr &cb) override; + Status SetCallback(const std::shared_ptr& cb) override; Status SetSource(std::string& uri, std::shared_ptr> params = nullptr) override; - Status Read(std::shared_ptr &buffer, size_t expectedLen) override; + Status Read(std::shared_ptr& buffer, size_t expectedLen) override; Status GetSize(size_t& size) override; bool IsSeekable() override; Status SeekTo(uint64_t offset) override; private: - State state_; - std::string fileName_ {}; - std::ifstream fin_; + std::string fileName_{}; + std::FILE* fp_; size_t fileSize_; bool isSeekable_; uint64_t position_; - std::shared_ptr mAllocator_ {nullptr}; + std::shared_ptr mAllocator_{nullptr}; Status ParseFileName(std::string& uri); + Status CheckFileStat(); Status OpenFile(); void CloseFile(); }; -} -} -} +} // namespace Plugin +} // namespace Media +} // namespace OHOS #endif // MEDIA_PIPELINE_FILE_SOURCE_PLUGIN_H diff --git a/engine/utils/BUILD.gn b/engine/utils/BUILD.gn index 870fed0f841f5d4159b24b086e5d9ede97a41636..96c55c3fde804e13821419c987b77fe968a689cb 100644 --- a/engine/utils/BUILD.gn +++ b/engine/utils/BUILD.gn @@ -14,7 +14,10 @@ import("//build/lite/config/component/lite_component.gni") -histreamer_utils_src = [ "constants.cpp" ] +histreamer_utils_src = [ + "constants.cpp", + "utils.cpp", +] config("histreamer_utils_config") { include_dirs = [ @@ -34,10 +37,6 @@ lite_library("histreamer_utils") { sources = histreamer_utils_src public_configs = [ ":histreamer_utils_config" ] public_deps = [ "//foundation/multimedia/histreamer/engine/foundation:histreamer_foundation" ] - cflags = [ - "-O2", - "-fPIC", - "-Wall", - ] + cflags = [ "-O2" ] cflags_cc = cflags } diff --git a/engine/utils/blocking_queue.h b/engine/utils/blocking_queue.h index 104d36121c65eaa41ebb51d8b331f633e2f905df..5c97e511ace2bc4a0d60bff791335c6a4c091ae5 100644 --- a/engine/utils/blocking_queue.h +++ b/engine/utils/blocking_queue.h @@ -118,7 +118,6 @@ public: return {}; } if (que_.empty()) { - MEDIA_LOG_D("blocking queue %s is empty, waiting for push", name_.c_str()); cvEmpty_.WaitFor(lock, timeoutMs, [this] { return !isActive || !que_.empty(); }); } if (!isActive || que_.empty()) { diff --git a/engine/utils/utils.cpp b/engine/utils/utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8343cf3d9b17540aa9c74b3a4d33dec3e6c72c26 --- /dev/null +++ b/engine/utils/utils.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "utils.h" +#include + +namespace OHOS { +namespace Media { +size_t GetFileSize(const char* fileName) +{ + size_t fileSize = 0; + if (fileName != nullptr) { + struct stat fileStatus {}; + if (stat(fileName, &fileStatus) == 0) { + fileSize = static_cast(fileStatus.st_size); + } + } + return fileSize; +} +} // namespace Media +} // namespace OHOS \ No newline at end of file diff --git a/engine/utils/utils.h b/engine/utils/utils.h index 778f645ed3d416c58c77ec0514d761dd8e95f427..738c8e31d8fbad0433214c2715378f962f605e9b 100644 --- a/engine/utils/utils.h +++ b/engine/utils/utils.h @@ -16,14 +16,15 @@ #ifndef HISTREAMER_FOUNDATION_UTILS_H #define HISTREAMER_FOUNDATION_UTILS_H +#include #include -#define CALL_PTR_FUNC(ptr, func, param) \ - if ((ptr)) { \ - (ptr)->func(param); \ - } else { \ - MEDIA_LOG_E("Call weakPtr " #func " error." ); \ - } +#define CALL_PTR_FUNC(ptr, func, param) \ + if ((ptr)) { \ + (ptr)->func(param); \ + } else { \ + MEDIA_LOG_E("Call weakPtr " #func " error."); \ + } #define UNUSED_VARIABLE(v) ((void)(v)) @@ -45,6 +46,8 @@ constexpr typename std::underlying_type::type to_underlying(E e) noexcept { return static_cast::type>(e); } -} -} + +size_t GetFileSize(const char* fileName); +} // namespace Media +} // namespace OHOS #endif // HISTREAMER_FOUNDATION_UTILS_H diff --git a/interface/histreamer/hiplayer.h b/interface/histreamer/hiplayer.h index af68925c924de71bb7a5c59efffe5c0ef116a0ca..fabcbc764c18aded0458bd84eaaa3ef189f30ee4 100644 --- a/interface/histreamer/hiplayer.h +++ b/interface/histreamer/hiplayer.h @@ -21,48 +21,6 @@ namespace OHOS { namespace Media { -class HiPlayer : public Media::PlayerInterface { -public: - HiPlayer(); - ~HiPlayer() override; - int32_t SetSource(const Media::Source& source) override; - int32_t Prepare() override; - int32_t Play() override; - bool IsPlaying() override; - int32_t Pause() override; - int32_t Stop() override; - int32_t Rewind(int64_t mSeconds, int32_t mode) override; - int32_t SetVolume(float leftVolume, float rightVolume) override; -#ifndef SURFACE_DISABLED - int32_t SetSurface(Surface* surface) override; -#endif - bool IsSingleLooping() override; - int32_t GetPlayerState(int32_t& state) override; - int32_t GetCurrentPosition(int64_t& currentPosition) override; - int32_t GetDuration(int64_t& duration) override; - int32_t GetVideoWidth(int32_t& videoWidth) override; - int32_t GetVideoHeight(int32_t& videoHeight) override; - int32_t SetPlaybackSpeed(float speed) override; - int32_t GetPlaybackSpeed(float& speed) override; - int32_t SetAudioStreamType(int32_t type) override; - void GetAudioStreamType(int32_t& type) override; - int32_t Reset() override; - int32_t Release() override; - int32_t SetLoop(bool loop) override; - void SetPlayerCallback(const std::shared_ptr& cb) override; - int32_t Init() override; - int32_t DeInit() override; - int32_t SetParameter(const Media::Format& params) override; - - class HiPlayerImpl; -private: - std::shared_ptr player_; - Media::PlayerStates curState_; - bool isInited_; - bool isSingleLoop_; - int audioStreamType_; -}; - #if defined(WIN32) __declspec(dllexport) #endif diff --git a/tests/ut/CMakeLists.txt b/tests/ut/CMakeLists.txt index 6dd9a5fdb7eeea330183be9182c057e9581ced08..0638d9ddbf2a84e079aed9059f42d29779bb3963 100644 --- a/tests/ut/CMakeLists.txt +++ b/tests/ut/CMakeLists.txt @@ -37,9 +37,12 @@ link_directories( file(GLOB UT_TEST_SRCS ./*.cpp) +file(GLOB UT_TEST_PLUGINS ./plugins/*.cpp) + set(SRC ${HISTREAMER_SRCS} ${UT_TEST_SRCS} + ${UT_TEST_PLUGINS} ${3RDPARTY_SRCS} ../main.cpp ) diff --git a/tests/ut/TestHiPlayer.cpp b/tests/ut/TestHiPlayer.cpp index 1204d250a940c73c71b6433eae2402d4a6f51540..f84825de1f6efb90df552626fb2439e92f1939e4 100644 --- a/tests/ut/TestHiPlayer.cpp +++ b/tests/ut/TestHiPlayer.cpp @@ -34,8 +34,8 @@ public: MockObject audioDecoder {}; MockObject audioSink {}; - std::shared_ptr player = HiPlayer::HiPlayerImpl::CreateHiPlayerImpl(); - std::shared_ptr source = std::make_shared("./test.mp3"); + std::shared_ptr player = HiPlayerImpl::CreateHiPlayerImpl(); + static OHOS::Media::Source source; PInPort emptyInPort = EmptyInPort::GetInstance(); POutPort emptyOutPort = EmptyOutPort::GetInstance(); @@ -46,20 +46,20 @@ public: MOCK_METHOD(audioDecoder, Init).defaults(); MOCK_METHOD(audioSink, Init).defaults(); - MOCK_METHOD(audioSource, Prepare).defaults().will(returnValue(SUCCESS)); - MOCK_METHOD(demuxer, Prepare).defaults().will(returnValue(SUCCESS)); - MOCK_METHOD(audioDecoder, Prepare).defaults().will(returnValue(SUCCESS)); - MOCK_METHOD(audioSink, Prepare).defaults().will(returnValue(SUCCESS)); + MOCK_METHOD(audioSource, Prepare).defaults().will(returnValue(ErrorCode::SUCCESS)); + MOCK_METHOD(demuxer, Prepare).defaults().will(returnValue(ErrorCode::SUCCESS)); + MOCK_METHOD(audioDecoder, Prepare).defaults().will(returnValue(ErrorCode::SUCCESS)); + MOCK_METHOD(audioSink, Prepare).defaults().will(returnValue(ErrorCode::SUCCESS)); - MOCK_METHOD(audioSource, Start).defaults().will(returnValue(SUCCESS)); - MOCK_METHOD(demuxer, Start).defaults().will(returnValue(SUCCESS)); - MOCK_METHOD(audioDecoder, Start).defaults().will(returnValue(SUCCESS)); - MOCK_METHOD(audioSink, Start).defaults().will(returnValue(SUCCESS)); + MOCK_METHOD(audioSource, Start).defaults().will(returnValue(ErrorCode::SUCCESS)); + MOCK_METHOD(demuxer, Start).defaults().will(returnValue(ErrorCode::SUCCESS)); + MOCK_METHOD(audioDecoder, Start).defaults().will(returnValue(ErrorCode::SUCCESS)); + MOCK_METHOD(audioSink, Start).defaults().will(returnValue(ErrorCode::SUCCESS)); - MOCK_METHOD(audioSource, Stop).defaults().will(returnValue(SUCCESS)); - MOCK_METHOD(demuxer, Stop).defaults().will(returnValue(SUCCESS)); - MOCK_METHOD(audioDecoder, Stop).defaults().will(returnValue(SUCCESS)); - MOCK_METHOD(audioSink, Stop).defaults().will(returnValue(SUCCESS)); + MOCK_METHOD(audioSource, Stop).defaults().will(returnValue(ErrorCode::SUCCESS)); + MOCK_METHOD(demuxer, Stop).defaults().will(returnValue(ErrorCode::SUCCESS)); + MOCK_METHOD(audioDecoder, Stop).defaults().will(returnValue(ErrorCode::SUCCESS)); + MOCK_METHOD(audioSink, Stop).defaults().will(returnValue(ErrorCode::SUCCESS)); MOCK_METHOD(audioSource, GetInPort).defaults().will(returnValue(emptyInPort)); MOCK_METHOD(demuxer, GetInPort).defaults().will(returnValue(emptyInPort)); @@ -71,13 +71,13 @@ public: MOCK_METHOD(audioDecoder, GetOutPort).defaults().will(returnValue(emptyOutPort)); MOCK_METHOD(audioSink, GetOutPort).defaults().will(returnValue(emptyOutPort)); - player->audioSource.reset(audioSource); - player->demuxer.reset(demuxer); - player->audioDecoder.reset(audioDecoder); - player->audioSink.reset(audioSink); + player->audioSource_.reset(audioSource); + player->demuxer_.reset(demuxer); + player->audioDecoder_.reset(audioDecoder); + player->audioSink_.reset(audioSink); - MOCK_METHOD(audioSource, SetSource).defaults().will(returnValue(SUCCESS)); - MOCK_METHOD(audioSource, SetBufferSize).defaults().will(returnValue(SUCCESS)); + MOCK_METHOD(audioSource, SetSource).defaults().will(returnValue(ErrorCode::SUCCESS)); + MOCK_METHOD(audioSource, SetBufferSize).defaults().will(returnValue(ErrorCode::SUCCESS)); player->Init(); } @@ -95,13 +95,16 @@ public: } }; +OHOS::Media::Source UtTestHiPlayer::source("./test.mp3"); + TEST_F(UtTestHiPlayer, Can_SetSource) { + // 因为player内部根据source参数创建shared_ptr,最终调用 audioSource.SetSource. 这里没法检查该指针参数了。 MOCK_METHOD(audioSource, SetSource) .expects(once()) - .with(source) - .will(returnValue(SUCCESS)); - ASSERT_EQ(SUCCESS, player->SetSource(source)); + .with(any()) + .will(returnValue(ErrorCode::SUCCESS)); + ASSERT_EQ(static_cast(ErrorCode::SUCCESS), player->SetSource(source)); player->fsm_.DoTask(); ASSERT_EQ("PreparingState", player->fsm_.curState_->GetName()); } @@ -112,8 +115,8 @@ TEST_F(UtTestHiPlayer, Can_SetBufferSize) MOCK_METHOD(audioSource, SetBufferSize) .expects(once()) .with(eq(size)) - .will(returnValue(SUCCESS)); - ASSERT_EQ(SUCCESS, player->SetBufferSize(size)); + .will(returnValue(ErrorCode::SUCCESS)); + ASSERT_EQ(ErrorCode::SUCCESS, player->SetBufferSize(size)); } } diff --git a/tests/ut/TestMetaBundle.cpp b/tests/ut/TestMetaBundle.cpp index af0653edf5ca8d3962102d10ea23ac217fe9e6a9..58f8b91f33b1a406a2a64657f86bc7b3a20b0376 100644 --- a/tests/ut/TestMetaBundle.cpp +++ b/tests/ut/TestMetaBundle.cpp @@ -35,7 +35,7 @@ TEST(Test_meta_bundle, GetNull_before_Update) TEST(Test_meta_bundle, GetGlobalMeta_after_Update) { - Meta meta; + Plugin::Meta meta; std::string title("title"); std::string album("album"); int32_t channels = 64; @@ -61,7 +61,7 @@ TEST(Test_meta_bundle, GetGlobalMeta_after_Update) TEST(Test_meta_bundle, GetStreamMeta_after_Update) { - Meta meta; + Plugin::Meta meta; std::string mime("audio/mpeg"); std::string language("zh"); meta.SetString(Media::Plugin::MetaID::MIME, mime); diff --git a/tests/ut/TestMimeDefs.cpp b/tests/ut/TestMimeDefs.cpp index 72fdd9cbcd1cef7fdb7c949737bcd3b7bb2bfba2..5fc056c684f7e3318ccbe7c170b965e4e42ee54b 100644 --- a/tests/ut/TestMimeDefs.cpp +++ b/tests/ut/TestMimeDefs.cpp @@ -26,7 +26,7 @@ namespace Media { namespace Test { TEST(TestDefs, check_mime_defs) { - ASSERT_STREQ(MEDIA_MIME_AUDIO_MP3, "audio/mp3"); + ASSERT_STREQ(MEDIA_MIME_AUDIO_MPEG, "audio/mpeg"); ASSERT_STREQ(MEDIA_MIME_AUDIO_FLAC, "audio/flac"); ASSERT_STREQ(MEDIA_MIME_AUDIO_RAW, "audio/raw"); ASSERT_STREQ(MEDIA_MIME_AUDIO_APE, "audio/ape"); diff --git a/tests/ut/TestPluginManager.cpp b/tests/ut/TestPluginManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..70c79ab98b280a60280e43916746369f814d0aae --- /dev/null +++ b/tests/ut/TestPluginManager.cpp @@ -0,0 +1,225 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#define private public +#define protected public + +#include "utils/utils.h" +#include "plugin/core/plugin_manager.h" + +#include "plugins/UtSourceTest1.h" +#include "plugins/UtSourceTest2.h" + +namespace OHOS { +namespace Media { +namespace Test { +using namespace OHOS::Media::Plugin; + +TEST(TestPluginManager, ListPlugins_case3) +{ + UtSourceTest1::available = true; + UtSourceTest2::available = true; + std::set plugins = PluginManager::Instance().ListPlugins(PluginType::SOURCE); + ASSERT_TRUE(plugins.size() > 1); + for (const auto & plugin : plugins) { + ASSERT_NE(plugin, ""); + } +} + +TEST(TestPluginManager, ListPlugins_case4) +{ + std::set plugins = PluginManager::Instance().ListPlugins(PluginType::DEMUXER); + ASSERT_TRUE(plugins.size() > 1); + for (const auto & plugin : plugins) { + ASSERT_NE(plugin, ""); + } +} + +TEST(TestPluginManager, ListPlugins_case5) +{ + std::set plugins = PluginManager::Instance().ListPlugins(PluginType::CODEC); + ASSERT_TRUE(plugins.size() > 1); + for (const auto & plugin : plugins) { + ASSERT_NE(plugin, ""); + } +} + +TEST(TestPluginManager, ListPlugins_case6) +{ + std::set plugins = PluginManager::Instance().ListPlugins(PluginType::AUDIO_SINK); + ASSERT_TRUE(plugins.size() > 1); + for (const auto & plugin : plugins) { + ASSERT_NE(plugin, ""); + } +} + +TEST(TestPluginManager, ListPlugins_case7) +{ + ASSERT_TRUE(PluginManager::Instance().ListPlugins(PluginType::INVALID_TYPE).empty()); +} + +TEST(TestPluginManager, ListPlugins_case8) +{ + ASSERT_TRUE(PluginManager::Instance().ListPlugins(PluginType(256)).empty()); +} + +TEST(TestPluginManager, GetPluginInfo_case1) +{ + std::shared_ptr info = PluginManager::Instance().GetPluginInfo( + PluginType::SOURCE, "UtSourceTest1"); + ASSERT_TRUE(info != nullptr); + ASSERT_EQ(info->name, "UtSourceTest1"); +} + +TEST(TestPluginManager, GetPluginInfo_case2) +{ + ASSERT_TRUE(PluginManager::Instance().GetPluginInfo(PluginType::SOURCE, "UtSourceTest3") == nullptr); +} + +TEST(TestPluginManager, GetPluginInfo_case3) +{ + ASSERT_TRUE(PluginManager::Instance().GetPluginInfo(PluginType::SOURCE, "") == nullptr); +} + +TEST(TestPluginManager, GetPluginInfo_case4) +{ + ASSERT_TRUE(PluginManager::Instance().GetPluginInfo(PluginType::INVALID_TYPE, "") == nullptr); +} + +TEST(TestPluginManager, GetPluginInfo_case5) +{ + ASSERT_TRUE(PluginManager::Instance().GetPluginInfo(PluginType(256), "") == nullptr); +} + +TEST(TestPluginManager, CreateSourcePlugin_case1) +{ + ASSERT_TRUE(PluginManager::Instance().CreateSourcePlugin("UtSourceTest1") != nullptr); +} + +TEST(TestPluginManager, CreateSourcePlugin_case2) +{ + ASSERT_TRUE(PluginManager::Instance().CreateSourcePlugin("UtSourceTest3") == nullptr); +} + +TEST(TestPluginManager, CreateSourcePlugin_case3) +{ + ASSERT_TRUE(PluginManager::Instance().CreateSourcePlugin("") == nullptr); +} + +TEST(TestPluginManager, CreateDemuxerPlugin_case1) +{ + ASSERT_TRUE(PluginManager::Instance().CreateDemuxerPlugin("UtDemuxerTest1") != nullptr); +} + +TEST(TestPluginManager, CreateDemuxerPlugin_case2) +{ + ASSERT_TRUE(PluginManager::Instance().CreateDemuxerPlugin("UtDemuxerTest3") == nullptr); +} + +TEST(TestPluginManager, CreateDemuxerPlugin_case3) +{ + ASSERT_TRUE(PluginManager::Instance().CreateDemuxerPlugin("") == nullptr); +} + +TEST(TestPluginManager, CreateCodecPlugin_case1) +{ + ASSERT_TRUE(PluginManager::Instance().CreateCodecPlugin("UtCodecTest1") != nullptr); +} + +TEST(TestPluginManager, CreateCodecPlugin_case2) +{ + ASSERT_TRUE(PluginManager::Instance().CreateCodecPlugin("UtCodecTest3") == nullptr); +} + +TEST(TestPluginManager, CreateCodecPlugin_case3) +{ + ASSERT_TRUE(PluginManager::Instance().CreateCodecPlugin("") == nullptr); +} + +TEST(TestPluginManager, CreateAudioSinkPlugin_case1) +{ + ASSERT_TRUE(PluginManager::Instance().CreateAudioSinkPlugin("UtAudioSinkTest1") != nullptr); +} + +TEST(TestPluginManager, CreateAudioSinkPlugin_case2) +{ + ASSERT_TRUE(PluginManager::Instance().CreateAudioSinkPlugin("UtAudioSinkTest3") == nullptr); +} + +TEST(TestPluginManager, CreateAudioSinkPlugin_case3) +{ + ASSERT_TRUE(PluginManager::Instance().CreateAudioSinkPlugin("") == nullptr); +} + +class UtDataSourceHelperTest1 : public DataSourceHelper { +public: + ~UtDataSourceHelperTest1() override = default; + + Status ReadAt(int64_t offset, std::shared_ptr &buffer, size_t expectedLen) override + { + buffer->GetMemory()->Write(reinterpret_cast("UtPlugin"), 8); + return Status::OK; + } + + Status GetSize(size_t &size) override + { + return Status::OK; + } +}; + +class UtDataSourceHelperTest2 : public DataSourceHelper { +public: + ~UtDataSourceHelperTest2() override = default; + + Status ReadAt(int64_t offset, std::shared_ptr &buffer, size_t expectedLen) override + { + buffer->GetMemory()->Write(reinterpret_cast("12345678"), 8); + return Status::OK; + } + + Status GetSize(size_t &size) override + { + return Status::OK; + } +}; + + +TEST(TestPluginManager, Sniffer_case1) +{ + ASSERT_TRUE(PluginManager::Instance().Sniffer("UtDemuxerTest1", + std::make_shared()) > 0); +} + +TEST(TestPluginManager, Sniffer_case2) +{ + ASSERT_TRUE(PluginManager::Instance().Sniffer("UtDemuxerTest1", + std::make_shared()) == 0); +} + +TEST(TestPluginManager, Sniffer_case3) +{ + ASSERT_TRUE(PluginManager::Instance().Sniffer("UtDemuxerTest3", + std::make_shared()) == 0); +} + +TEST(TestPluginManager, Sniffer_case4) +{ + ASSERT_TRUE(PluginManager::Instance().Sniffer("UtDemuxerTest1", nullptr) == 0); +} +} // namespace Test +} // namespace Media +} // namespace OHOS diff --git a/tests/ut/TestPluginManagerNoPlugin.cpp b/tests/ut/TestPluginManagerNoPlugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c29ac284c2efb71b13f1fff4facaa721d040ca8b --- /dev/null +++ b/tests/ut/TestPluginManagerNoPlugin.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#define private public +#define protected public + +#include "utils/utils.h" +#include "plugin/core/plugin_manager.h" + +#include "plugins/UtSourceTest1.h" +#include "plugins/UtSourceTest2.h" + +namespace OHOS { +namespace Media { +namespace Test { +using namespace OHOS::Media::Plugin; + +TEST(TestPluginManagerNoPlugin, ListPlugins_case1) +{ + UtSourceTest1::available = false; + UtSourceTest2::available = false; + std::set plugins = PluginManager::Instance().ListPlugins(PluginType::SOURCE); + ASSERT_TRUE(plugins.empty()); +} +} // namespace Test +} // namespace Media +} // namespace OHOS diff --git a/tests/ut/TestPluginManagerOnePlugin.cpp b/tests/ut/TestPluginManagerOnePlugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d23584e113f2064e9d3a32194fc9dab8e7a5589e --- /dev/null +++ b/tests/ut/TestPluginManagerOnePlugin.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#define private public +#define protected public + +#include "utils/utils.h" +#include "plugin/core/plugin_manager.h" + +#include "plugins/UtSourceTest1.h" +#include "plugins/UtSourceTest2.h" + +namespace OHOS { +namespace Media { +namespace Test { +using namespace OHOS::Media::Plugin; + +TEST(TestPluginManagerOnePlugin, ListPlugins_case2) +{ + UtSourceTest1::available = true; + UtSourceTest2::available = false; + std::set plugins = PluginManager::Instance().ListPlugins(PluginType::SOURCE); + ASSERT_TRUE(plugins.size() == 1); +} +} // namespace Test +} // namespace Media +} // namespace OHOS diff --git a/tests/ut/TestStateMachine.cpp b/tests/ut/TestStateMachine.cpp index a2828462ffbd011c79e4524f24bed8de60ec31aa..b905162142fc3d0effcf89d5d567f2f34367231f 100644 --- a/tests/ut/TestStateMachine.cpp +++ b/tests/ut/TestStateMachine.cpp @@ -39,22 +39,22 @@ public: } ErrorCode DoSetSource(const std::shared_ptr& source) const override { - return source ? SUCCESS : INVALID_SOURCE; + return source ? ErrorCode::SUCCESS : ErrorCode::ERROR_INVALID_SOURCE; } ErrorCode DoOnReady() override { - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode DoOnComplete() override { if (!isLooping_ && stateMachine_) { stateMachine_->SendEventAsync(Intent::STOP); } - return SUCCESS; + return ErrorCode::SUCCESS; } ErrorCode DoOnError(ErrorCode) override { - return SUCCESS; + return ErrorCode::SUCCESS; } private: @@ -89,7 +89,7 @@ TEST_F(TestStateMachine, test_init_state) TEST_F(TestStateMachine, test_set_invalid_source) { EXPECT_TRUE(stateMachine.GetCurrentState() == "InitState"); - EXPECT_EQ(INVALID_SOURCE, stateMachine.SendEvent(Intent::SET_SOURCE)); + EXPECT_EQ(ErrorCode::ERROR_INVALID_SOURCE, stateMachine.SendEvent(Intent::SET_SOURCE)); EXPECT_TRUE(stateMachine.GetCurrentState() == "InitState"); } @@ -97,14 +97,14 @@ TEST_F(TestStateMachine, test_set_valid_source) { EXPECT_TRUE(stateMachine.GetCurrentState() == "InitState"); auto source = std::make_shared("FakeUri"); - EXPECT_EQ(SUCCESS, stateMachine.SendEvent(Intent::SET_SOURCE, source)); + EXPECT_EQ(ErrorCode::SUCCESS, stateMachine.SendEvent(Intent::SET_SOURCE, source)); EXPECT_TRUE(stateMachine.GetCurrentState() == "PreparingState"); } TEST_F(TestStateMachine, test_set_notify_error_in_preparing) { EXPECT_TRUE(stateMachine.GetCurrentState() == "PreparingState"); - EXPECT_EQ(SUCCESS, stateMachine.SendEvent(Intent::NOTIFY_ERROR)); + EXPECT_EQ(ErrorCode::SUCCESS, stateMachine.SendEvent(Intent::NOTIFY_ERROR)); EXPECT_TRUE(stateMachine.GetCurrentState() == "InitState"); } @@ -112,30 +112,30 @@ TEST_F(TestStateMachine, test_notify_ready) { EXPECT_TRUE(stateMachine.GetCurrentState() == "InitState"); auto source = std::make_shared("FakeUri"); - EXPECT_EQ(SUCCESS, stateMachine.SendEvent(Intent::SET_SOURCE, source)); + EXPECT_EQ(ErrorCode::SUCCESS, stateMachine.SendEvent(Intent::SET_SOURCE, source)); EXPECT_TRUE(stateMachine.GetCurrentState() == "PreparingState"); - EXPECT_EQ(SUCCESS, stateMachine.SendEvent(Intent::NOTIFY_READY)); + EXPECT_EQ(ErrorCode::SUCCESS, stateMachine.SendEvent(Intent::NOTIFY_READY)); EXPECT_TRUE(stateMachine.GetCurrentState() == "ReadyState"); } TEST_F(TestStateMachine, test_play_after_ready) { EXPECT_TRUE(stateMachine.GetCurrentState() == "ReadyState"); - EXPECT_EQ(SUCCESS, stateMachine.SendEvent(Intent::PLAY)); + EXPECT_EQ(ErrorCode::SUCCESS, stateMachine.SendEvent(Intent::PLAY)); EXPECT_TRUE(stateMachine.GetCurrentState() == "PlayingState"); } TEST_F(TestStateMachine, test_pause) { EXPECT_TRUE(stateMachine.GetCurrentState() == "PlayingState"); - EXPECT_EQ(SUCCESS, stateMachine.SendEvent(Intent::PAUSE)); + EXPECT_EQ(ErrorCode::SUCCESS, stateMachine.SendEvent(Intent::PAUSE)); EXPECT_TRUE(stateMachine.GetCurrentState() == "PauseState"); } TEST_F(TestStateMachine, test_play_after_pause) { EXPECT_TRUE(stateMachine.GetCurrentState() == "PauseState"); - EXPECT_EQ(SUCCESS, stateMachine.SendEvent(Intent::PLAY)); + EXPECT_EQ(ErrorCode::SUCCESS, stateMachine.SendEvent(Intent::PLAY)); EXPECT_TRUE(stateMachine.GetCurrentState() == "PlayingState"); } @@ -143,7 +143,7 @@ TEST_F(TestStateMachine, test_play_complete_looping) { g_playExecutorStub.SetLooping(true); EXPECT_TRUE(stateMachine.GetCurrentState() == "PlayingState"); - EXPECT_EQ(SUCCESS, stateMachine.SendEvent(Intent::NOTIFY_COMPLETE)); + EXPECT_EQ(ErrorCode::SUCCESS, stateMachine.SendEvent(Intent::NOTIFY_COMPLETE)); EXPECT_TRUE(stateMachine.GetCurrentState() == "PlayingState"); } @@ -151,7 +151,7 @@ TEST_F(TestStateMachine, test_play_complete_nolooping) { g_playExecutorStub.SetLooping(false); EXPECT_TRUE(stateMachine.GetCurrentState() == "PlayingState"); - EXPECT_EQ(SUCCESS, stateMachine.SendEvent(Intent::NOTIFY_COMPLETE)); + EXPECT_EQ(ErrorCode::SUCCESS, stateMachine.SendEvent(Intent::NOTIFY_COMPLETE)); OSAL::SleepFor(100); EXPECT_TRUE(stateMachine.GetCurrentState() == "InitState"); } diff --git a/tests/ut/TestSynchronizer.cpp b/tests/ut/TestSynchronizer.cpp index 3db4ce4fdeec1a75c1d1661eee159541b2b2ec1b..85a585c4a9700e00c74f99e11ad0e083781b911b 100644 --- a/tests/ut/TestSynchronizer.cpp +++ b/tests/ut/TestSynchronizer.cpp @@ -19,10 +19,10 @@ #undef UNIT_TEST -#include // NOLINT -#include // NOLINT +#include // NOLINT +#include // NOLINT #include // NOLINT -#include // NOLINT +#include // NOLINT #include "osal/base/synchronizer.h" #include "osal/thread/task.h" @@ -62,7 +62,8 @@ TEST_F(TestSynchronizer, test_waitfor_fail) task1->RegisterHandler([this, syncId] { synchronizer.Notify(syncId, 1234); }); int timeoutMs = 100; auto start = std::chrono::high_resolution_clock::now(); - auto rtv = synchronizer.WaitFor(syncId, timeoutMs); + auto rtv = synchronizer.WaitFor( + syncId, [] {}, timeoutMs); auto end = std::chrono::high_resolution_clock::now(); auto diff = static_cast>(end - start).count() * 1000; EXPECT_EQ(false, rtv); @@ -76,7 +77,8 @@ TEST_F(TestSynchronizer, test_waitfor_succ) task1->RegisterHandler([this, syncId] { synchronizer.Notify(syncId, 1234); }); task1->Start(); int timeoutMs = 1000; - auto rtv = synchronizer.WaitFor(syncId, timeoutMs); + auto rtv = synchronizer.WaitFor( + syncId, [] {}, timeoutMs); EXPECT_EQ(true, rtv); } @@ -88,7 +90,8 @@ TEST_F(TestSynchronizer, test_waitfor_with_result_succ) task1->Start(); int timeoutMs = 1000; int result = 0; - auto rtv = synchronizer.WaitFor(syncId, timeoutMs, result); + auto rtv = synchronizer.WaitFor( + syncId, [] {}, timeoutMs, result); EXPECT_EQ(true, rtv); EXPECT_EQ(expect, result); } @@ -100,7 +103,8 @@ TEST_F(TestSynchronizer, test_wait_succ) int expect = 1234; task1->RegisterHandler([this, syncId, &result] { if (!isDataRcved.load()) { - synchronizer.Wait(syncId, result); + synchronizer.Wait( + syncId, [] {}, result); isDataRcved = true; } }); diff --git a/tests/ut/plugins/UtAudioSinkTest1.cpp b/tests/ut/plugins/UtAudioSinkTest1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00225a0d9de86c3cf664ff646b1dbdf55fee69a8 --- /dev/null +++ b/tests/ut/plugins/UtAudioSinkTest1.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UtAudioSinkTest1.h" + +using namespace OHOS::Media::Plugin; + +static std::shared_ptr PluginCreator(const std::string &name) +{ + return std::make_shared(name); +} + +static Status AudioSinkRegister(const std::shared_ptr ®) +{ + AudioSinkPluginDef definition; + definition.name = "UtAudioSinkTest1"; + definition.description = "unit test audio sink test1"; + definition.rank = 100; // 100 + definition.creator = PluginCreator; + return reg->AddPlugin(definition); +} + +PLUGIN_DEFINITION(UtAudioSinkTest1, LicenseType::APACHE_V2, AudioSinkRegister, [] {}); + +Status UtAudioSinkTest1::GetMute(bool &mute) +{ + return Status::OK; +} + +Status UtAudioSinkTest1::SetMute(bool mute) +{ + return Status::OK; +} + +Status UtAudioSinkTest1::GetVolume(float &volume) +{ + return Status::OK; +} + +Status UtAudioSinkTest1::SetVolume(float volume) +{ + return Status::OK; +} + +Status UtAudioSinkTest1::GetSpeed(float &speed) +{ + return Status::OK; +} + +Status UtAudioSinkTest1::SetSpeed(float speed) +{ + return Status::OK; +} + +Status UtAudioSinkTest1::Pause() +{ + return Status::OK; +} + +Status UtAudioSinkTest1::Resume() +{ + return Status::OK; +} + +Status UtAudioSinkTest1::GetLatency(uint64_t &ms) +{ + return Status::OK; +} + +Status UtAudioSinkTest1::GetFrameSize(size_t &size) +{ + return Status::OK; +} + +Status UtAudioSinkTest1::GetFrameCount(uint32_t &count) +{ + return Status::OK; +} + +Status UtAudioSinkTest1::Write(const std::shared_ptr &input) +{ + return Status::OK; +} + +Status UtAudioSinkTest1::Flush() +{ + return Status::OK; +} + +std::shared_ptr UtAudioSinkTest1::GetAllocator() +{ + return std::shared_ptr(); +} + +Status UtAudioSinkTest1::SetCallback(const std::shared_ptr &cb) +{ + return Status::OK; +} diff --git a/tests/ut/plugins/UtAudioSinkTest1.h b/tests/ut/plugins/UtAudioSinkTest1.h new file mode 100644 index 0000000000000000000000000000000000000000..50bfe38cf648a98d693b4edaae573f327748db4d --- /dev/null +++ b/tests/ut/plugins/UtAudioSinkTest1.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HISTREAMER_UTAUDIOSINKTEST1_H +#define HISTREAMER_UTAUDIOSINKTEST1_H + +#include "plugin/interface/audio_sink_plugin.h" + +namespace OHOS { +namespace Media { +namespace Plugin { +class UtAudioSinkTest1 : public AudioSinkPlugin { +public: + explicit UtAudioSinkTest1(std::string name) : AudioSinkPlugin(std::move(name)) + { + } + + ~UtAudioSinkTest1() override = default; + + Status GetMute(bool &mute) override; + + Status SetMute(bool mute) override; + + Status GetVolume(float &volume) override; + + Status SetVolume(float volume) override; + + Status GetSpeed(float &speed) override; + + Status SetSpeed(float speed) override; + + Status Pause() override; + + Status Resume() override; + + Status GetLatency(uint64_t &ms) override; + + Status GetFrameSize(size_t &size) override; + + Status GetFrameCount(uint32_t &count) override; + + Status Write(const std::shared_ptr &input) override; + + Status Flush() override; + + std::shared_ptr GetAllocator() override; + + Status SetCallback(const std::shared_ptr &cb) override; +}; +} // namespace Plugin +} // namespace Media +} // namespace OHOS +#endif // HISTREAMER_UTAUDIOSINKTEST1_H diff --git a/tests/ut/plugins/UtAudioSinkTest2.cpp b/tests/ut/plugins/UtAudioSinkTest2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05b9f1d78544b59f7ea9298087e660ebbf475005 --- /dev/null +++ b/tests/ut/plugins/UtAudioSinkTest2.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UtAudioSinkTest2.h" + +using namespace OHOS::Media::Plugin; + +static std::shared_ptr PluginCreator(const std::string &name) +{ + return std::make_shared(name); +} + +static Status AudioSinkRegister(const std::shared_ptr ®) +{ + AudioSinkPluginDef definition; + definition.name = "UtAudioSinkTest2"; + definition.description = "unit test audio sink test2"; + definition.rank = 100; // 100 + definition.creator = PluginCreator; + return reg->AddPlugin(definition); +} + +PLUGIN_DEFINITION(UtAudioSinkTest2, LicenseType::APACHE_V2, AudioSinkRegister, [] {}); + +Status UtAudioSinkTest2::GetMute(bool &mute) +{ + return Status::OK; +} + +Status UtAudioSinkTest2::SetMute(bool mute) +{ + return Status::OK; +} + +Status UtAudioSinkTest2::GetVolume(float &volume) +{ + return Status::OK; +} + +Status UtAudioSinkTest2::SetVolume(float volume) +{ + return Status::OK; +} + +Status UtAudioSinkTest2::GetSpeed(float &speed) +{ + return Status::OK; +} + +Status UtAudioSinkTest2::SetSpeed(float speed) +{ + return Status::OK; +} + +Status UtAudioSinkTest2::Pause() +{ + return Status::OK; +} + +Status UtAudioSinkTest2::Resume() +{ + return Status::OK; +} + +Status UtAudioSinkTest2::GetLatency(uint64_t &ms) +{ + return Status::OK; +} + +Status UtAudioSinkTest2::GetFrameSize(size_t &size) +{ + return Status::OK; +} + +Status UtAudioSinkTest2::GetFrameCount(uint32_t &count) +{ + return Status::OK; +} + +Status UtAudioSinkTest2::Write(const std::shared_ptr &input) +{ + return Status::OK; +} + +Status UtAudioSinkTest2::Flush() +{ + return Status::OK; +} + +std::shared_ptr UtAudioSinkTest2::GetAllocator() +{ + return std::shared_ptr(); +} + +Status UtAudioSinkTest2::SetCallback(const std::shared_ptr &cb) +{ + return Status::OK; +} diff --git a/tests/ut/plugins/UtAudioSinkTest2.h b/tests/ut/plugins/UtAudioSinkTest2.h new file mode 100644 index 0000000000000000000000000000000000000000..04bb61cf1194d6d47356352529afc5df83ef560a --- /dev/null +++ b/tests/ut/plugins/UtAudioSinkTest2.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HISTREAMER_UTAUDIOSINKTEST2_H +#define HISTREAMER_UTAUDIOSINKTEST2_H + +#include "plugin/interface/audio_sink_plugin.h" + +namespace OHOS { +namespace Media { +namespace Plugin { +class UtAudioSinkTest2 : public AudioSinkPlugin { +public: + explicit UtAudioSinkTest2(std::string name) : AudioSinkPlugin(std::move(name)) + { + } + + ~UtAudioSinkTest2() override = default; + + Status GetMute(bool &mute) override; + + Status SetMute(bool mute) override; + + Status GetVolume(float &volume) override; + + Status SetVolume(float volume) override; + + Status GetSpeed(float &speed) override; + + Status SetSpeed(float speed) override; + + Status Pause() override; + + Status Resume() override; + + Status GetLatency(uint64_t &ms) override; + + Status GetFrameSize(size_t &size) override; + + Status GetFrameCount(uint32_t &count) override; + + Status Write(const std::shared_ptr &input) override; + + Status Flush() override; + + std::shared_ptr GetAllocator() override; + + Status SetCallback(const std::shared_ptr &cb) override; +}; +} // namespace Plugin +} // namespace Media +} // namespace OHOS +#endif // HISTREAMER_UTAUDIOSINKTEST2_H diff --git a/tests/ut/plugins/UtCodecTest1.cpp b/tests/ut/plugins/UtCodecTest1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5866669679f3eb9efe3dc5c7900dcbb62e007199 --- /dev/null +++ b/tests/ut/plugins/UtCodecTest1.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UtCodecTest1.h" + +using namespace OHOS::Media::Plugin; + +static std::shared_ptr PluginCreator(const std::string &name) +{ + return std::make_shared(name); +} + +static Status CodecRegister(const std::shared_ptr ®) +{ + CodecPluginDef definition; + definition.name = "UtCodecTest1"; + definition.description = "unit test codec test1"; + definition.rank = 100; // 100 + definition.creator = PluginCreator; + return reg->AddPlugin(definition); +} + +PLUGIN_DEFINITION(UtCodecTest1, LicenseType::APACHE_V2, CodecRegister, [] {}); + +Status UtCodecTest1::QueueInputBuffer(const std::shared_ptr &inputBuffer, int32_t timeoutMs) +{ + return Status::OK; +} + +Status UtCodecTest1::QueueOutputBuffer(const std::shared_ptr &outputBuffers, int32_t timeoutMs) +{ + return Status::OK; +} + +Status UtCodecTest1::Flush() +{ + return Status::OK; +} + +Status UtCodecTest1::SetDataCallback(const std::weak_ptr &dataCallback) +{ + return Status::OK; +} + +std::shared_ptr UtCodecTest1::GetAllocator() +{ + return std::shared_ptr(); +} + +Status UtCodecTest1::SetCallback(const std::shared_ptr &cb) +{ + return Status::OK; +} diff --git a/tests/ut/plugins/UtCodecTest1.h b/tests/ut/plugins/UtCodecTest1.h new file mode 100644 index 0000000000000000000000000000000000000000..c0bebd8630a2ead85d0cfda4278a4921f9c81ac5 --- /dev/null +++ b/tests/ut/plugins/UtCodecTest1.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HISTREAMER_UTCODECTEST1_H +#define HISTREAMER_UTCODECTEST1_H + +#include "plugin/interface/codec_plugin.h" + +namespace OHOS { +namespace Media { +namespace Plugin { +class UtCodecTest1 : public CodecPlugin { +public: + explicit UtCodecTest1(std::string name) : CodecPlugin(std::move(name)) + { + } + + ~UtCodecTest1() override = default; + + Status QueueInputBuffer(const std::shared_ptr &inputBuffer, int32_t timeoutMs) override; + + Status QueueOutputBuffer(const std::shared_ptr &outputBuffers, int32_t timeoutMs) override; + + Status Flush() override; + + Status SetDataCallback(const std::weak_ptr &dataCallback) override; + + std::shared_ptr GetAllocator() override; + + Status SetCallback(const std::shared_ptr &cb) override; +}; +} // namespace Plugin +} // namespace Media +} // namespace OHOS +#endif // HISTREAMER_UTCODECTEST1_H diff --git a/tests/ut/plugins/UtCodecTest2.cpp b/tests/ut/plugins/UtCodecTest2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fb78d2ceac84ae4cccd6d9cc761966dd8afe63bb --- /dev/null +++ b/tests/ut/plugins/UtCodecTest2.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UtCodecTest2.h" + +using namespace OHOS::Media::Plugin; + +static std::shared_ptr PluginCreator(const std::string &name) +{ + return std::make_shared(name); +} + +static Status CodecRegister(const std::shared_ptr ®) +{ + CodecPluginDef definition; + definition.name = "UtCodecTest2"; + definition.description = "unit test codec test2"; + definition.rank = 100; // 100 + definition.creator = PluginCreator; + return reg->AddPlugin(definition); +} + +PLUGIN_DEFINITION(UtCodecTest2, LicenseType::APACHE_V2, CodecRegister, [] {}); + +Status UtCodecTest2::QueueInputBuffer(const std::shared_ptr &inputBuffer, int32_t timeoutMs) +{ + return Status::OK; +} + +Status UtCodecTest2::QueueOutputBuffer(const std::shared_ptr &outputBuffers, int32_t timeoutMs) +{ + return Status::OK; +} + +Status UtCodecTest2::Flush() +{ + return Status::OK; +} + +Status UtCodecTest2::SetDataCallback(const std::weak_ptr &dataCallback) +{ + return Status::OK; +} + +std::shared_ptr UtCodecTest2::GetAllocator() +{ + return std::shared_ptr(); +} + +Status UtCodecTest2::SetCallback(const std::shared_ptr &cb) +{ + return Status::OK; +} diff --git a/tests/ut/plugins/UtCodecTest2.h b/tests/ut/plugins/UtCodecTest2.h new file mode 100644 index 0000000000000000000000000000000000000000..eaea7904f748539ae019f1c36d4e9c012f51b554 --- /dev/null +++ b/tests/ut/plugins/UtCodecTest2.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HISTREAMER_UTCODECTEST2_H +#define HISTREAMER_UTCODECTEST2_H + +#include "plugin/interface/codec_plugin.h" + +namespace OHOS { +namespace Media { +namespace Plugin { +class UtCodecTest2 : public CodecPlugin { +public: + explicit UtCodecTest2(std::string name) : CodecPlugin(std::move(name)) + { + } + + ~UtCodecTest2() override = default; + + Status QueueInputBuffer(const std::shared_ptr &inputBuffer, int32_t timeoutMs) override; + + Status QueueOutputBuffer(const std::shared_ptr &outputBuffers, int32_t timeoutMs) override; + + Status Flush() override; + + Status SetDataCallback(const std::weak_ptr &dataCallback) override; + + std::shared_ptr GetAllocator() override; + + Status SetCallback(const std::shared_ptr &cb) override; +}; +} // namespace Plugin +} // namespace Media +} // namespace OHOS +#endif // HISTREAMER_UTCODECTEST2_H diff --git a/tests/ut/plugins/UtDemuxerTest1.cpp b/tests/ut/plugins/UtDemuxerTest1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7401d96f691311c55e341cbb7ee3e15bc5bf6bd2 --- /dev/null +++ b/tests/ut/plugins/UtDemuxerTest1.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UtDemuxerTest1.h" + +using namespace OHOS::Media::Plugin; + +static int Sniff(const std::string& name, std::shared_ptr dataSource) +{ + int bufferSize = 16; + auto bufData = Buffer::CreateDefaultBuffer(BufferMetaType::AUDIO, bufferSize); + if (dataSource->ReadAt(0, bufData, bufferSize) == Status::OK) { + const uint8_t* data = bufData->GetMemory()->GetReadOnlyData(); + if (data[0] == 'U' && data[1] == 't') { + return 100; // 100 + } + } + return 0; +} + +static Status RegisterPlugins(const std::shared_ptr& reg) +{ + DemuxerPluginDef regInfo; + regInfo.name = "UtDemuxerTest1"; + regInfo.description = "unit test demuxer test1"; + regInfo.rank = 100; // 100 + regInfo.creator = [](const std::string& name) -> std::shared_ptr { + return std::make_shared(name); + }; + regInfo.sniffer = Sniff; + return reg->AddPlugin(regInfo); +} + +PLUGIN_DEFINITION(UtDemuxerTest1, LicenseType::LGPL, RegisterPlugins, [] {}); + +Status UtDemuxerTest1::SetDataSource(const std::shared_ptr &source) +{ + return Status::OK; +} + +Status UtDemuxerTest1::GetMediaInfo(MediaInfo &mediaInfo) +{ + return Status::OK; +} + +size_t UtDemuxerTest1::GetTrackCount() +{ + return 0; +} + +Status UtDemuxerTest1::SelectTrack(int32_t trackId) +{ + return Status::OK; +} + +Status UtDemuxerTest1::UnselectTrack(int32_t trackId) +{ + return Status::OK; +} + +Status UtDemuxerTest1::GetSelectedTracks(std::vector &trackIds) +{ + return Status::OK; +} + +Status UtDemuxerTest1::ReadFrame(Buffer &buffer, int32_t timeOutMs) +{ + return Status::OK; +} + +Status UtDemuxerTest1::SeekTo(int32_t trackId, int64_t timeStampUs, SeekMode mode) +{ + return Status::OK; +} + +std::shared_ptr UtDemuxerTest1::GetAllocator() +{ + return std::shared_ptr(); +} + +Status UtDemuxerTest1::SetCallback(const std::shared_ptr &cb) +{ + return Status::OK; +} diff --git a/tests/ut/plugins/UtDemuxerTest1.h b/tests/ut/plugins/UtDemuxerTest1.h new file mode 100644 index 0000000000000000000000000000000000000000..721cf286984548c77d32488816d2baf5df5b81da --- /dev/null +++ b/tests/ut/plugins/UtDemuxerTest1.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HISTREAMER_UTDEMUXERTEST1_H +#define HISTREAMER_UTDEMUXERTEST1_H + +#include "plugin/interface/demuxer_plugin.h" + +namespace OHOS { +namespace Media { +namespace Plugin { +class UtDemuxerTest1 : public DemuxerPlugin { +public: + explicit UtDemuxerTest1(std::string name) : DemuxerPlugin(std::move(name)) + { + } + + ~UtDemuxerTest1() override = default; + + Status SetDataSource(const std::shared_ptr &source) override; + + Status GetMediaInfo(MediaInfo &mediaInfo) override; + + size_t GetTrackCount() override; + + Status SelectTrack(int32_t trackId) override; + + Status UnselectTrack(int32_t trackId) override; + + Status GetSelectedTracks(std::vector &trackIds) override; + + Status ReadFrame(Buffer &buffer, int32_t timeOutMs) override; + + Status SeekTo(int32_t trackId, int64_t timeStampUs, SeekMode mode) override; + + std::shared_ptr GetAllocator() override; + + Status SetCallback(const std::shared_ptr &cb) override; +}; +} // namespace Plugin +} // namespace Media +} // namespace OHOS +#endif // HISTREAMER_UTDEMUXERTEST1_H diff --git a/tests/ut/plugins/UtDemuxerTest2.cpp b/tests/ut/plugins/UtDemuxerTest2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5553b80af40ec66a8a3deda58ea84eec7c72babd --- /dev/null +++ b/tests/ut/plugins/UtDemuxerTest2.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UtDemuxerTest2.h" + +using namespace OHOS::Media::Plugin; + +static int Sniff(const std::string& name, std::shared_ptr dataSource) +{ + return 0; +} + +static Status RegisterPlugins(const std::shared_ptr& reg) +{ + DemuxerPluginDef regInfo; + regInfo.name = "UtDemuxerTest2"; + regInfo.description = "unit test demuxer test2"; + regInfo.rank = 100; // 100 + regInfo.creator = [](const std::string& name) -> std::shared_ptr { + return std::make_shared(name); + }; + regInfo.sniffer = Sniff; + return reg->AddPlugin(regInfo); +} + +PLUGIN_DEFINITION(UtDemuxerTest2, LicenseType::LGPL, RegisterPlugins, [] {}); + +Status UtDemuxerTest2::SetDataSource(const std::shared_ptr &source) +{ + return Status::OK; +} + +Status UtDemuxerTest2::GetMediaInfo(MediaInfo &mediaInfo) +{ + return Status::OK; +} + +size_t UtDemuxerTest2::GetTrackCount() +{ + return 0; +} + +Status UtDemuxerTest2::SelectTrack(int32_t trackId) +{ + return Status::OK; +} + +Status UtDemuxerTest2::UnselectTrack(int32_t trackId) +{ + return Status::OK; +} + +Status UtDemuxerTest2::GetSelectedTracks(std::vector &trackIds) +{ + return Status::OK; +} + +Status UtDemuxerTest2::ReadFrame(Buffer &buffer, int32_t timeOutMs) +{ + return Status::OK; +} + +Status UtDemuxerTest2::SeekTo(int32_t trackId, int64_t timeStampUs, SeekMode mode) +{ + return Status::OK; +} + +std::shared_ptr UtDemuxerTest2::GetAllocator() +{ + return std::shared_ptr(); +} + +Status UtDemuxerTest2::SetCallback(const std::shared_ptr &cb) +{ + return Status::OK; +} diff --git a/tests/ut/plugins/UtDemuxerTest2.h b/tests/ut/plugins/UtDemuxerTest2.h new file mode 100644 index 0000000000000000000000000000000000000000..f8be89c07c4e7c18aea0437fbb77da3243c4d96f --- /dev/null +++ b/tests/ut/plugins/UtDemuxerTest2.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HISTREAMER_UTDEMUXERTEST2_H +#define HISTREAMER_UTDEMUXERTEST2_H + + +#include "plugin/interface/demuxer_plugin.h" + +namespace OHOS { +namespace Media { +namespace Plugin { +class UtDemuxerTest2 : public DemuxerPlugin { +public: + explicit UtDemuxerTest2(std::string name) : DemuxerPlugin(std::move(name)) + { + } + + ~UtDemuxerTest2() override = default; + + Status SetDataSource(const std::shared_ptr &source) override; + + Status GetMediaInfo(MediaInfo &mediaInfo) override; + + size_t GetTrackCount() override; + + Status SelectTrack(int32_t trackId) override; + + Status UnselectTrack(int32_t trackId) override; + + Status GetSelectedTracks(std::vector &trackIds) override; + + Status ReadFrame(Buffer &buffer, int32_t timeOutMs) override; + + Status SeekTo(int32_t trackId, int64_t timeStampUs, SeekMode mode) override; + + std::shared_ptr GetAllocator() override; + + Status SetCallback(const std::shared_ptr &cb) override; +}; +} // namespace Plugin +} // namespace Media +} // namespace OHOS +#endif // HISTREAMER_UTDEMUXERTEST2_H diff --git a/tests/ut/plugins/UtSourceTest1.cpp b/tests/ut/plugins/UtSourceTest1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bab0930a01ec870adc595d0618b963e59366c618 --- /dev/null +++ b/tests/ut/plugins/UtSourceTest1.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UtSourceTest1.h" + +namespace OHOS { +namespace Media { +namespace Plugin { +bool UtSourceTest1::available = true; + +static std::shared_ptr PluginCreator(const std::string &name) +{ + return std::make_shared(name); +} + +static Status SourceRegister(const std::shared_ptr ®) +{ + if (UtSourceTest1::available) { + SourcePluginDef definition; + definition.name = "UtSourceTest1"; + definition.description = "unit test source test1"; + definition.rank = 100; // 100 + definition.protocol = "file"; + definition.creator = PluginCreator; + return reg->AddPlugin(definition); + } else { + return Status::ERROR_UNIMPLEMENTED; + } +} + +PLUGIN_DEFINITION(UtSourceTest1, LicenseType::APACHE_V2, SourceRegister, [] {}); + +Status OHOS::Media::Plugin::UtSourceTest1::SetSource(std::string &uri, + std::shared_ptr> params) +{ + return Status::OK; +} + +Status UtSourceTest1::Read(std::shared_ptr &buffer, size_t expectedLen) +{ + return Status::OK; +} + +Status UtSourceTest1::GetSize(size_t &size) +{ + return Status::OK; +} + +bool UtSourceTest1::IsSeekable() +{ + return false; +} + +Status UtSourceTest1::SeekTo(uint64_t offset) +{ + return Status::OK; +} + +std::shared_ptr UtSourceTest1::GetAllocator() +{ + return std::shared_ptr(); +} + +Status UtSourceTest1::SetCallback(const std::shared_ptr &cb) +{ + return Status::OK; +} +} +} +} diff --git a/tests/ut/plugins/UtSourceTest1.h b/tests/ut/plugins/UtSourceTest1.h new file mode 100644 index 0000000000000000000000000000000000000000..9b2fdd5d97a5ab76ab7bf8a014ec37f2f0ca868c --- /dev/null +++ b/tests/ut/plugins/UtSourceTest1.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HISTREAMER_UTSOURCETEST1_H +#define HISTREAMER_UTSOURCETEST1_H + +#include "plugin/interface/source_plugin.h" + +namespace OHOS { +namespace Media { +namespace Plugin { +class UtSourceTest1 : public SourcePlugin { +public: + explicit UtSourceTest1(std::string name) : SourcePlugin(std::move(name)) + { + } + + ~UtSourceTest1() override = default; + + Status SetSource(std::string &uri, std::shared_ptr> params) override; + + Status Read(std::shared_ptr &buffer, size_t expectedLen) override; + + Status GetSize(size_t &size) override; + + bool IsSeekable() override; + + Status SeekTo(uint64_t offset) override; + + std::shared_ptr GetAllocator() override; + + Status SetCallback(const std::shared_ptr &cb) override; + + static bool available; +}; +} // namespace Plugin +} // namespace Media +} // namespace OHOS +#endif // HISTREAMER_UTSOURCETEST1_H diff --git a/tests/ut/plugins/UtSourceTest2.cpp b/tests/ut/plugins/UtSourceTest2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..879de2b005df0458d76f699255f7410807278179 --- /dev/null +++ b/tests/ut/plugins/UtSourceTest2.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UtSourceTest2.h" + +using namespace OHOS::Media::Plugin; + +bool UtSourceTest2::available = true; + +static std::shared_ptr PluginCreator(const std::string &name) +{ + return std::make_shared(name); +} + +static Status SourceRegister(const std::shared_ptr ®) +{ + if (UtSourceTest2::available) { + SourcePluginDef definition; + definition.name = "UtSourceTest2"; + definition.description = "unit test source test2"; + definition.rank = 100; // 100 + definition.protocol = "file"; + definition.creator = PluginCreator; + return reg->AddPlugin(definition); + } else { + return Status::ERROR_UNIMPLEMENTED; + } +} + +PLUGIN_DEFINITION(UtSourceTest2, LicenseType::APACHE_V2, SourceRegister, [] {}); + +Status UtSourceTest2::SetSource(std::string &uri, std::shared_ptr> params) +{ + return Status::OK; +} + +Status UtSourceTest2::Read(std::shared_ptr &buffer, size_t expectedLen) +{ + return Status::OK; +} + +Status UtSourceTest2::GetSize(size_t &size) +{ + return Status::OK; +} + +bool UtSourceTest2::IsSeekable() +{ + return false; +} + +Status UtSourceTest2::SeekTo(uint64_t offset) +{ + return Status::OK; +} + +std::shared_ptr UtSourceTest2::GetAllocator() +{ + return std::shared_ptr(); +} + +Status UtSourceTest2::SetCallback(const std::shared_ptr &cb) +{ + return Status::OK; +} diff --git a/tests/ut/plugins/UtSourceTest2.h b/tests/ut/plugins/UtSourceTest2.h new file mode 100644 index 0000000000000000000000000000000000000000..5379f007c58e3e443da3144933c015c90cd555e8 --- /dev/null +++ b/tests/ut/plugins/UtSourceTest2.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HISTREAMER_UTSOURCETEST2_H +#define HISTREAMER_UTSOURCETEST2_H + +#include "plugin/interface/source_plugin.h" + +namespace OHOS { +namespace Media { +namespace Plugin { +class UtSourceTest2 : public SourcePlugin { +public: + explicit UtSourceTest2(std::string name) : SourcePlugin(std::move(name)) + { + } + + ~UtSourceTest2() override = default; + + Status SetSource(std::string &uri, std::shared_ptr> params) override; + + Status Read(std::shared_ptr &buffer, size_t expectedLen) override; + + Status GetSize(size_t &size) override; + + bool IsSeekable() override; + + Status SeekTo(uint64_t offset) override; + + std::shared_ptr GetAllocator() override; + + Status SetCallback(const std::shared_ptr &cb) override; + + static bool available; +}; +} // namespace Plugin +} // namespace Media +} // namespace OHOS +#endif // HISTREAMER_UTSOURCETEST2_H