Search is not available for this dataset
repo
stringlengths 2
152
⌀ | file
stringlengths 15
239
| code
stringlengths 0
58.4M
| file_length
int64 0
58.4M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 364
values |
---|---|---|---|---|---|---|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/repo-command-parameter.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014, Regents of the University of California.
*
* This file is part of NDN repo-ng (Next generation of NDN repository).
* See AUTHORS.md for complete list of repo-ng authors and contributors.
*
* repo-ng is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* repo-ng is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* repo-ng, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef REPO_REPO_COMMAND_PARAMETER_HPP
#define REPO_REPO_COMMAND_PARAMETER_HPP
#include <ndn-cxx/encoding/encoding-buffer.hpp>
#include <ndn-cxx/encoding/block-helpers.hpp>
#include <ndn-cxx/name.hpp>
#include <ndn-cxx/selectors.hpp>
#include "repo-tlv.hpp"
namespace repo {
using ndn::Name;
using ndn::Block;
using ndn::EncodingImpl;
using ndn::Selectors;
using ndn::EncodingEstimator;
using ndn::EncodingBuffer;
using namespace ndn::time;
/**
* @brief Class defining abstraction of parameter of command for NDN Repo Protocol
* @sa link http://redmine.named-data.net/projects/repo-ng/wiki/Repo_Protocol_Specification#RepoCommandParameter
**/
class RepoCommandParameter
{
public:
class Error : public ndn::tlv::Error
{
public:
explicit
Error(const std::string& what)
: ndn::tlv::Error(what)
{
}
};
RepoCommandParameter()
: m_hasName(false)
, m_hasStartBlockId(false)
, m_hasEndBlockId(false)
, m_hasProcessId(false)
, m_hasMaxInterestNum(false)
, m_hasWatchTimeout(false)
, m_hasInterestLifetime(false)
{
}
explicit
RepoCommandParameter(const Block& block)
{
wireDecode(block);
}
const Name&
getName() const
{
return m_name;
}
RepoCommandParameter&
setName(const Name& name)
{
m_name = name;
m_hasName = true;
m_wire.reset();
return *this;
}
bool
hasName() const
{
return m_hasName;
}
const Selectors&
getSelectors() const
{
return m_selectors;
}
RepoCommandParameter&
setSelectors(const Selectors& selectors)
{
m_selectors = selectors;
m_wire.reset();
return *this;
}
bool
hasSelectors() const
{
return !m_selectors.empty();
}
uint64_t
getStartBlockId() const
{
assert(hasStartBlockId());
return m_startBlockId;
}
RepoCommandParameter&
setStartBlockId(uint64_t startBlockId)
{
m_startBlockId = startBlockId;
m_hasStartBlockId = true;
m_wire.reset();
return *this;
}
bool
hasStartBlockId() const
{
return m_hasStartBlockId;
}
uint64_t
getEndBlockId() const
{
assert(hasEndBlockId());
return m_endBlockId;
}
RepoCommandParameter&
setEndBlockId(uint64_t endBlockId)
{
m_endBlockId = endBlockId;
m_hasEndBlockId = true;
m_wire.reset();
return *this;
}
bool
hasEndBlockId() const
{
return m_hasEndBlockId;
}
uint64_t
getProcessId() const
{
assert(hasProcessId());
return m_processId;
}
RepoCommandParameter&
setProcessId(uint64_t processId)
{
m_processId = processId;
m_hasProcessId = true;
m_wire.reset();
return *this;
}
bool
hasProcessId() const
{
return m_hasProcessId;
}
uint64_t
getMaxInterestNum() const
{
assert(hasMaxInterestNum());
return m_maxInterestNum;
}
RepoCommandParameter&
setMaxInterestNum(uint64_t maxInterestNum)
{
m_maxInterestNum = maxInterestNum;
m_hasMaxInterestNum = true;
m_wire.reset();
return *this;
}
bool
hasMaxInterestNum() const
{
return m_hasMaxInterestNum;
}
milliseconds
getWatchTimeout() const
{
assert(hasWatchTimeout());
return m_watchTimeout;
}
RepoCommandParameter&
setWatchTimeout(milliseconds watchTimeout)
{
m_watchTimeout = watchTimeout;
m_hasWatchTimeout = true;
m_wire.reset();
return *this;
}
bool
hasWatchTimeout() const
{
return m_hasWatchTimeout;
}
milliseconds
getInterestLifetime() const
{
assert(hasInterestLifetime());
return m_interestLifetime;
}
RepoCommandParameter&
setInterestLifetime(milliseconds interestLifetime)
{
m_interestLifetime = interestLifetime;
m_hasInterestLifetime = true;
m_wire.reset();
return *this;
}
bool
hasInterestLifetime() const
{
return m_hasInterestLifetime;
}
template<bool T>
size_t
wireEncode(EncodingImpl<T>& block) const;
const Block&
wireEncode() const;
void
wireDecode(const Block& wire);
private:
Name m_name;
Selectors m_selectors;
uint64_t m_startBlockId;
uint64_t m_endBlockId;
uint64_t m_processId;
uint64_t m_maxInterestNum;
milliseconds m_watchTimeout;
milliseconds m_interestLifetime;
bool m_hasName;
bool m_hasStartBlockId;
bool m_hasEndBlockId;
bool m_hasProcessId;
bool m_hasMaxInterestNum;
bool m_hasWatchTimeout;
bool m_hasInterestLifetime;
mutable Block m_wire;
};
template<bool T>
inline size_t
RepoCommandParameter::wireEncode(EncodingImpl<T>& encoder) const
{
size_t totalLength = 0;
size_t variableLength = 0;
if (m_hasProcessId) {
variableLength = encoder.prependNonNegativeInteger(m_processId);
totalLength += variableLength;
totalLength += encoder.prependVarNumber(variableLength);
totalLength += encoder.prependVarNumber(tlv::ProcessId);
}
if (m_hasEndBlockId) {
variableLength = encoder.prependNonNegativeInteger(m_endBlockId);
totalLength += variableLength;
totalLength += encoder.prependVarNumber(variableLength);
totalLength += encoder.prependVarNumber(tlv::EndBlockId);
}
if (m_hasStartBlockId) {
variableLength = encoder.prependNonNegativeInteger(m_startBlockId);
totalLength += variableLength;
totalLength += encoder.prependVarNumber(variableLength);
totalLength += encoder.prependVarNumber(tlv::StartBlockId);
}
if (m_hasMaxInterestNum) {
variableLength = encoder.prependNonNegativeInteger(m_maxInterestNum);
totalLength += variableLength;
totalLength += encoder.prependVarNumber(variableLength);
totalLength += encoder.prependVarNumber(tlv::MaxInterestNum);
}
if (m_hasWatchTimeout) {
variableLength = encoder.prependNonNegativeInteger(m_watchTimeout.count());
totalLength += variableLength;
totalLength += encoder.prependVarNumber(variableLength);
totalLength += encoder.prependVarNumber(tlv::WatchTimeout);
}
if (m_hasInterestLifetime) {
variableLength = encoder.prependNonNegativeInteger(m_interestLifetime.count());
totalLength += variableLength;
totalLength += encoder.prependVarNumber(variableLength);
totalLength += encoder.prependVarNumber(tlv::InterestLifetime);
}
if (!getSelectors().empty()) {
totalLength += getSelectors().wireEncode(encoder);
}
if (m_hasName) {
totalLength += getName().wireEncode(encoder);
}
totalLength += encoder.prependVarNumber(totalLength);
totalLength += encoder.prependVarNumber(tlv::RepoCommandParameter);
return totalLength;
}
inline const Block&
RepoCommandParameter::wireEncode() const
{
if (m_wire.hasWire())
return m_wire;
EncodingEstimator estimator;
size_t estimatedSize = wireEncode(estimator);
EncodingBuffer buffer(estimatedSize, 0);
wireEncode(buffer);
m_wire = buffer.block();
return m_wire;
}
inline void
RepoCommandParameter::wireDecode(const Block& wire)
{
m_hasName = false;
m_hasStartBlockId = false;
m_hasEndBlockId = false;
m_hasProcessId = false;
m_hasMaxInterestNum = false;
m_hasWatchTimeout = false;
m_hasInterestLifetime = false;
m_wire = wire;
m_wire.parse();
if (m_wire.type() != tlv::RepoCommandParameter)
throw Error("Requested decoding of RepoCommandParameter, but Block is of different type");
// Name
Block::element_const_iterator val = m_wire.find(tlv::Name);
if (val != m_wire.elements_end())
{
m_hasName = true;
m_name.wireDecode(m_wire.get(tlv::Name));
}
// Selectors
val = m_wire.find(tlv::Selectors);
if (val != m_wire.elements_end())
{
m_selectors.wireDecode(*val);
}
else
m_selectors = Selectors();
// StartBlockId
val = m_wire.find(tlv::StartBlockId);
if (val != m_wire.elements_end())
{
m_hasStartBlockId = true;
m_startBlockId = readNonNegativeInteger(*val);
}
// EndBlockId
val = m_wire.find(tlv::EndBlockId);
if (val != m_wire.elements_end())
{
m_hasEndBlockId = true;
m_endBlockId = readNonNegativeInteger(*val);
}
// ProcessId
val = m_wire.find(tlv::ProcessId);
if (val != m_wire.elements_end())
{
m_hasProcessId = true;
m_processId = readNonNegativeInteger(*val);
}
// MaxInterestNum
val = m_wire.find(tlv::MaxInterestNum);
if (val != m_wire.elements_end())
{
m_hasMaxInterestNum = true;
m_maxInterestNum = readNonNegativeInteger(*val);
}
// WatchTimeout
val = m_wire.find(tlv::WatchTimeout);
if (val != m_wire.elements_end())
{
m_hasWatchTimeout = true;
m_watchTimeout = milliseconds(readNonNegativeInteger(*val));
}
// InterestLiftTime
val = m_wire.find(tlv::InterestLifetime);
if (val != m_wire.elements_end())
{
m_hasInterestLifetime = true;
m_interestLifetime = milliseconds(readNonNegativeInteger(*val));
}
}
inline std::ostream&
operator<<(std::ostream& os, const RepoCommandParameter& repoCommandParameter)
{
os << "RepoCommandParameter(";
// Name
if (repoCommandParameter.hasName()) {
os << " Name: " << repoCommandParameter.getName();
}
if (repoCommandParameter.hasStartBlockId()) {
// StartBlockId
os << " StartBlockId: " << repoCommandParameter.getStartBlockId();
}
// EndBlockId
if (repoCommandParameter.hasEndBlockId()) {
os << " EndBlockId: " << repoCommandParameter.getEndBlockId();
}
// ProcessId
if (repoCommandParameter.hasProcessId()) {
os << " ProcessId: " << repoCommandParameter.getProcessId();
}
// MaxInterestNum
if (repoCommandParameter.hasMaxInterestNum()) {
os << " MaxInterestNum: " << repoCommandParameter.getMaxInterestNum();
}
// WatchTimeout
if (repoCommandParameter.hasProcessId()) {
os << " WatchTimeout: " << repoCommandParameter.getWatchTimeout();
}
// InterestLifetime
if (repoCommandParameter.hasProcessId()) {
os << " InterestLifetime: " << repoCommandParameter.getInterestLifetime();
}
os << " )";
return os;
}
} // namespace repo
#endif // REPO_REPO_COMMAND_PARAMETER_HPP
| 10,871 | 21.509317 | 111 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/rtt-estimator.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014 Regents of the University of California,
* Arizona Board of Regents,
* Colorado State University,
* University Pierre & Marie Curie, Sorbonne University,
* Washington University in St. Louis,
* Beijing Institute of Technology,
* The University of Memphis
*
* This file is part of NFD (Named Data Networking Forwarding Daemon).
* See AUTHORS.md for complete list of NFD authors and contributors.
*
* NFD is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef RTT_ESTIMATOR_HPP
#define RTT_ESTIMATOR_HPP
#include "common.hpp"
#include <ndn-cxx/util/time.hpp>
namespace ndn {
/**
* \brief implements the Mean-Deviation RTT estimator
*
* reference: ns3::RttMeanDeviation
*
* This RttEstimator algorithm is designed for TCP, which is a continuous stream.
* NDN Interest-Data traffic is not always a continuous stream,
* so NDN may need a different RttEstimator.
* The design of a more suitable RttEstimator is a research question.
*/
class RttEstimator
{
public:
typedef time::microseconds Duration;
static Duration
getInitialRtt(void)
{
return time::seconds(1);
}
RttEstimator(uint16_t maxMultiplier = 16,
Duration minRto = time::milliseconds(1),
double gain = 0.1);
void
addMeasurement(Duration measure);
void
incrementMultiplier();
void
doubleMultiplier();
Duration
computeRto() const;
private:
uint16_t m_maxMultiplier;
double m_minRto;
double m_rtt;
double m_gain;
double m_variance;
uint16_t m_multiplier;
uint32_t m_nSamples;
};
} // namespace ndn
#endif // FW_RTT_ESTIMATOR_HPP
| 2,394 | 27.176471 | 83 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/infomax-prioritizer.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "infomax-prioritizer.hpp"
namespace ndn {
Prioritizer::Prioritizer(Producer *producer)
{
m_producer = producer;
m_listVersion = 0;
}
void
Prioritizer::prioritize()
{
int type = 0;
m_producer->getContextOption(PREFIX, m_prefix);
m_producer->getContextOption(INFOMAX_ROOT, m_root);
m_producer->getContextOption(INFOMAX_PRIORITY, type);
m_listVersion++;
if(type == INFOMAX_SIMPLE_PRIORITY)
{
simplePrioritizer(&m_root);
}
else if(type == INFOMAX_MERGE_PRIORITY)
{
mergePrioritizer(&m_root);
}
else
{
dummy(&m_root);
}
}
void
Prioritizer::simplePrioritizer(TreeNode *root)
{
resetNodeStatus(root);
unsigned int numOfLeafNodes = root->getTreeSize();
vector<TreeNode*>* prioritizedVector = new vector<TreeNode*>();
while(root->getRevisionCount() < numOfLeafNodes) {
prioritizedVector->push_back(getNextPriorityNode(root));
}
produceInfoMaxList(Name(), prioritizedVector);
}
TreeNode*
Prioritizer::getNextPriorityNode(TreeNode *root)
{
if(root == 0)
{
return 0;
}
root->updateRevisionCount(root->getRevisionCount() + 1);
if(root->isDataNode() && !(root->isNodeMarked()))
{
root->markNode(true);
return root;
}
vector<TreeNode*> children = root->getChildren();
if(children.size() > 0)
{
uint64_t leastRevisionCountNow = std::numeric_limits<uint64_t>::max();;
TreeNode *nodeWithLeastCount = NULL;
for(unsigned int i=0; i<children.size(); i++ )
{
TreeNode* child = children[i];
if(child->getRevisionCount() < child->getTreeSize() || child->getRevisionCount() == 0)
{
if(nodeWithLeastCount == 0
|| (nodeWithLeastCount != 0 && leastRevisionCountNow > child->getRevisionCount()))
{
nodeWithLeastCount = child;
leastRevisionCountNow = child->getRevisionCount();
}
}
}
return getNextPriorityNode(nodeWithLeastCount);
}
return 0;
}
void
Prioritizer::mergePrioritizer(TreeNode *root)
{
mergeSort(root);
}
std::list<TreeNode *>*
Prioritizer::mergeSort(TreeNode *node)
{
std::list<TreeNode *> *mergeList = new std::list<TreeNode *> ();
if (node->isLeafNode())
{
mergeList->push_back(node);
return mergeList;
}
vector<TreeNode *> children = node->getChildren();
vector< std::list<TreeNode *>* > *subTreeMergeList = new vector< std::list<TreeNode *>* >();
for(unsigned int i=0; i<children.size(); i++)
{
subTreeMergeList->push_back(mergeSort(children[i]));
}
mergeList = merge(subTreeMergeList);
// convert list to vector
vector<TreeNode*>* prioritizedVector = new vector<TreeNode *>{ std::make_move_iterator(std::begin(*mergeList)), std::make_move_iterator(std::end(*mergeList)) };
Name subListName = Name();
if (!node->isRootNode()) {
subListName.append(node->getName());
}
produceInfoMaxList(subListName, prioritizedVector);
return mergeList;
}
std::list<TreeNode *>*
Prioritizer::merge(vector< std::list<TreeNode*>* > *subTreeMergeList)
{
bool isListAllEmpty = false;
std::list<TreeNode *> *mergeList = new std::list<TreeNode *> ();
while (!isListAllEmpty)
{
for (unsigned int i=0; i<subTreeMergeList->size(); i++)
{
if (!subTreeMergeList->at(i)->empty())
{
isListAllEmpty = false;
break;
}
isListAllEmpty = true;
}
for (unsigned int i=0; i<subTreeMergeList->size(); i++)
{
if (!subTreeMergeList->at(i)->empty())
{
mergeList->push_back(subTreeMergeList->at(i)->front());
subTreeMergeList->at(i)->pop_front();
}
}
}
return mergeList;
}
void
Prioritizer::dummy(TreeNode *root)
{
vector<TreeNode *> *prioritizedVector = new vector<TreeNode *> ();
prioritizedVector->push_back(root);
vector<TreeNode*> children = root->getChildren();
for(unsigned int i=0; i<children.size(); i++ ) {
TreeNode *n = children[i];
prioritizedVector->push_back(n);
}
produceInfoMaxList(root->getName(), prioritizedVector);
}
void
Prioritizer::resetNodeStatus(TreeNode* node)
{
node->updateRevisionCount(0);
node->markNode(false);
vector<TreeNode*> children = node->getChildren();
if(children.size() > 0) {
for (unsigned int i=0; i < children.size(); i++) {
resetNodeStatus(children[i]);
}
}
}
void
Prioritizer::produceInfoMaxList(Name prefix, vector<TreeNode*>* prioritizedVector)
{
for(unsigned int i=0; i<prioritizedVector->size(); i=i+INFOMAX_DEFAULT_LIST_SIZE)
{
uint64_t listNum = i / INFOMAX_DEFAULT_LIST_SIZE + 1;
Name listName = Name(prefix);
listName.append(INFOMAX_INTEREST_TAG);
listName.appendNumber(m_listVersion); // current version all same
listName.appendNumber(listNum);
std::string listContent = "";
for(size_t j=i; j<prioritizedVector->size(); j++)
{
listContent += prioritizedVector->at(j)->getName().getSubName(prefix.size()).toUri();
listContent += ' ';
}
m_producer->produce(listName, (uint8_t*)listContent.c_str(), listContent.size());
}
// Produce InfoMax list meta info (version number and the total number of lists)
Name listMetaInfoName = Name(prefix);
listMetaInfoName.append(INFOMAX_INTEREST_TAG);
listMetaInfoName.append(INFOMAX_META_INTEREST_TAG);
// listMetaInfoName.appendNumber(m_listVersion);
std::string listMetaInfoContent = "";
uint64_t totalListNum = prioritizedVector->size() / INFOMAX_DEFAULT_LIST_SIZE + 1;
listMetaInfoContent = to_string(m_listVersion) + " " + to_string(totalListNum);
int dataFreshness = 0;
m_producer->getContextOption(DATA_FRESHNESS, dataFreshness);
m_producer->setContextOption(DATA_FRESHNESS, 0);
m_producer->produce(listMetaInfoName, (uint8_t*)listMetaInfoContent.c_str(), listMetaInfoContent.size());
m_producer->setContextOption(DATA_FRESHNESS, dataFreshness);
}
}
| 6,799 | 26.755102 | 161 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/application-nack.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "application-nack.hpp"
namespace ndn {
ApplicationNack::ApplicationNack()
{
setContentType(tlv::ContentType_Nack);
setCode(ApplicationNack::NONE);
}
ApplicationNack::ApplicationNack(const Interest& interest, ApplicationNack::NackCode statusCode)
{
Name name = interest.getName();
name.append(Name("nack"));
name.appendNumber(ndn::random::generateSecureWord64());
setName(name);
setContentType(tlv::ContentType_Nack);
setCode(statusCode);
}
ApplicationNack::ApplicationNack(const Data& data)
: Data(data)
{
setContentType(tlv::ContentType_Nack);
decode();
}
ApplicationNack::~ApplicationNack()
{}
void
ApplicationNack::addKeyValuePair(const uint8_t* key, size_t keySize, const uint8_t* value, size_t valueSize)
{
std::string keyS(reinterpret_cast<const char*>(key), keySize);
std::string valueS(reinterpret_cast<const char*>(value), valueSize);
addKeyValuePair(keyS, valueS);
}
void
ApplicationNack::addKeyValuePair(std::string key, std::string value)
{
m_keyValuePairs[key] = value;
}
std::string
ApplicationNack::getValueByKey(std::string key)
{
std::map<std::string,std::string>::const_iterator it = m_keyValuePairs.find(key);
if (it == m_keyValuePairs.end())
{
return "";
}
else
{
return it->second;
}
}
void
ApplicationNack::eraseValueByKey(std::string key)
{
m_keyValuePairs.erase(m_keyValuePairs.find(key));
}
void
ApplicationNack::setCode(ApplicationNack::NackCode statusCode)
{
std::stringstream ss;
ss << statusCode;
std::string value = ss.str();
addKeyValuePair(STATUS_CODE_H, value);
}
ApplicationNack::NackCode
ApplicationNack::getCode()
{
std::string value = getValueByKey(STATUS_CODE_H);
if (value != "")
{
try
{
return (ApplicationNack::NackCode)atoi(value.c_str());
}
catch(std::exception e)
{
return ApplicationNack::NONE;
}
}
else
{
return ApplicationNack::NONE;
}
}
void
ApplicationNack::setDelay(uint32_t milliseconds)
{
std::stringstream ss;
ss << milliseconds;
std::string value = ss.str();
addKeyValuePair(RETRY_AFTER_H, value);
}
uint32_t
ApplicationNack::getDelay()
{
std::string value = getValueByKey(RETRY_AFTER_H);
return atoi(value.c_str());
}
template<bool T>
size_t
ApplicationNack::wireEncode(EncodingImpl<T>& blk) const
{
// Nack ::= CONTENT-TLV TLV-LENGTH
// KeyValuePair*
size_t totalLength = 0;
for (std::map<std::string, std::string>::const_reverse_iterator it = m_keyValuePairs.rbegin();
it != m_keyValuePairs.rend(); ++it)
{
std::string keyValue = it->first + "=" + it->second;
totalLength += blk.prependByteArray(reinterpret_cast<const uint8_t*>(keyValue.c_str()), keyValue.size());
totalLength += blk.prependVarNumber(keyValue.size());
totalLength += blk.prependVarNumber(tlv::KeyValuePair);
}
return totalLength;
}
template size_t
ApplicationNack::wireEncode<true>(EncodingImpl<true>& block) const;
template size_t
ApplicationNack::wireEncode<false>(EncodingImpl<false>& block) const;
void
ApplicationNack::encode()
{
EncodingEstimator estimator;
size_t estimatedSize = wireEncode(estimator);
EncodingBuffer buffer(estimatedSize, 0);
wireEncode(buffer);
setContentType(tlv::ContentType_Nack);
setContent(const_cast<uint8_t*>(buffer.buf()), buffer.size());
}
void
ApplicationNack::decode()
{
Block content = getContent();
content.parse();
// Nack ::= CONTENT-TLV TLV-LENGTH
// KeyValuePair*
for ( Block::element_const_iterator val = content.elements_begin();
val != content.elements_end(); ++val)
{
if (val->type() == tlv::KeyValuePair)
{
std::string str((char*)val->value(), val->value_size());
size_t index = str.find_first_of('=');
if (index == std::string::npos || index == 0 || (index == str.size() - 1))
continue;
std::string key = str.substr(0, index);
std::string value = str.substr(index + 1, str.size() - index - 1);
addKeyValuePair(key, value);
}
}
}
} // namespace ndn
| 5,206 | 24.650246 | 109 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/rtt-estimator.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014 Regents of the University of California,
* Arizona Board of Regents,
* Colorado State University,
* University Pierre & Marie Curie, Sorbonne University,
* Washington University in St. Louis,
* Beijing Institute of Technology,
* The University of Memphis
*
* This file is part of NFD (Named Data Networking Forwarding Daemon).
* See AUTHORS.md for complete list of NFD authors and contributors.
*
* NFD is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
**/
#include "rtt-estimator.hpp"
namespace ndn {
RttEstimator::RttEstimator(uint16_t maxMultiplier, Duration minRto, double gain)
: m_maxMultiplier(maxMultiplier)
, m_minRto(minRto.count())
, m_rtt(RttEstimator::getInitialRtt().count())
, m_gain(gain)
, m_variance(0)
, m_multiplier(1)
, m_nSamples(0)
{
}
void
RttEstimator::addMeasurement(Duration measure)
{
double m = static_cast<double>(measure.count());
if (m_nSamples > 0) {
double err = m - m_rtt;
double gErr = err * m_gain;
m_rtt += gErr;
double difference = std::abs(err) - m_variance;
m_variance += difference * m_gain;
} else {
m_rtt = m;
m_variance = m;
}
++m_nSamples;
m_multiplier = 1;
}
void
RttEstimator::incrementMultiplier()
{
m_multiplier = std::min(static_cast<uint16_t>(m_multiplier + 1), m_maxMultiplier);
}
void
RttEstimator::doubleMultiplier()
{
m_multiplier = std::min(static_cast<uint16_t>(m_multiplier * 2), m_maxMultiplier);
}
RttEstimator::Duration
RttEstimator::computeRto() const
{
double rto = std::max(m_minRto, m_rtt + 4 * m_variance);
rto *= m_multiplier;
return Duration(static_cast<Duration::rep>(rto));
}
} // namespace ndn
| 2,445 | 29.575 | 84 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/infomax-tree-node.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef TREE_NODE_HPP
#define TREE_NODE_HPP
#include "common.hpp"
using namespace std;
namespace ndn {
class TreeNode
{
private:
Name name;
vector<TreeNode *> children;
bool isMarked;
TreeNode *parent;
bool dataNode;
uint64_t revisionCount;
uint64_t treeSize;
private:
/**
* Helper function for the constructor to initialize the node.
*/
void init(Name &name, TreeNode *parent);
public:
/**
* Constructor for nodes.
*/
TreeNode(Name &name, TreeNode *parent);
TreeNode(const TreeNode& other);
TreeNode();
/**
* Function to get the name associated with the TreeNode.
*/
Name
getName();
/**
* Function to get the children of the TreeNode.
*/
vector<TreeNode *>
getChildren();
/**
* Function to mark the TreeNode.
*/
bool
markNode(bool status);
/**
* Function to check if the TreeNode is marked.
*/
bool
isNodeMarked();
/**
* Function to check if the TreeNode has data.
*/
bool
setDataNode(bool flag);
/**
* Function to check if the TreeNode has data.
*/
bool
isDataNode();
/**
* Function to change the revision count of the TreeNode.
*/
bool
updateRevisionCount(unsigned long long int revisionCount);
/**
* Function to get the revision count of the TreeNode.
*/
uint64_t
getRevisionCount();
/**
* Function to check if the current node is a leaf node.
*/
bool
isLeafNode();
/**
* Function to check if the current node is a leaf node.
*/
bool
isRootNode();
/**
* Function to get number of shared prefix with input name.
*/
int
getNumSharedPrefix(TreeNode *node);
/**
* Function to remove a child from the current TreeNode. Removing a child
* changes the treesize of the current node.
*/
bool
removeChild (TreeNode * child);
/**
* Function to add a child to the current TreeNode. Adding a child
* changes the treesize of the current node and has an upward spiral
* affect, i.e., it changes the size of the upper level TreeNodes as well.
* Complexity O(N).
*/
bool
addChild (TreeNode * child);
/**
* Function to change the tree size rooted at the current TreeNode.
* Changing the treesize of the current node and has an upward spiral
* affect, i.e., it changes the size of the upper level TreeNodes as well.
* Complexity O(N).
*/
bool
setTreeSize (unsigned long long int treeSize);
/**
* Function to get the tree size rooted at the current TreeNode.
*/
uint64_t
getTreeSize ();
/**
* Function to print tree nodes data for debugging purposes.
*/
void
printTreeNode();
/**
* Function to print tree nodes data for debugging purposes.
*/
void
printTreeNodeName();
/**
* Function to get the parent node.
*/
TreeNode*
getParent();
};
} // namespace ndn
#endif // TREE_NODE_HPP
| 3,871 | 23.049689 | 99 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/consumer-context.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef CONSUMER_CONTEXT_HPP
#define CONSUMER_CONTEXT_HPP
#include "context.hpp"
#include "context-options.hpp"
#include "context-default-values.hpp"
#include "data-retrieval-protocol.hpp"
#include "simple-data-retrieval.hpp"
#include "unreliable-data-retrieval.hpp"
#include "reliable-data-retrieval.hpp"
#include "infomax-data-retrieval.hpp"
#include <ndn-cxx/util/config-file.hpp>
#include <ndn-cxx/management/nfd-controller.hpp>
namespace ndn {
/**
* @brief Consumer context is a container of consumer-specific transmission parameters for a
* specific name prefix.
*
* Consumer context performs fetching of Application Data Units using Interest/Data exchanges.
* Consumer context can be tuned using set/getcontextopt primitives.
*/
class Consumer : public Context
{
public:
/**
* @brief Initializes consumer context.
*
* @param prefix - Name components that define the range of application frames (ADU)
* that can be retrieved from the network.
* @param protocol - 1) SDR 2) UDR 3) RDR
*/
explicit Consumer(const Name prefix, int protocol);
/**
* @brief Stops the ongoing fetching of the Application Data Unit (ADU) and releases all
* associated system resources.
*
*/
~Consumer();
/**
* @brief Performs transmission of Interest packets to fetch specified Application Data Unit (ADU).
* Consume() blocks until ADU is successfully fetched or an irrecoverable error occurs.
*
* @param suffix Name components that identify the boundary of Application Data Unit (ADU)
*/
int
consume(Name suffix);
/**
* @brief Performs transmission of Interest packets to fetch specified Application Data Unit (ADU).
* async_consume() does not block the caller thread.
*
* @param suffix Name components that identify the boundary of Application Data Unit (ADU)
*/
int
asyncConsume(Name suffix);
/**
* @brief Stops the ongoing fetching of the Application Data Unit (ADU).
*
*/
void
stop();
static void
consumeAll();
/*
* Context option setters
* Return OPTION_VALUE_SET if success; otherwise -- OPTION_VALUE_NOT_SET
*/
int
setContextOption(int optionName, int optionValue);
int
setContextOption(int optionName, bool optionValue);
int
setContextOption(int optionName, size_t optionValue);
int
setContextOption(int optionName, Name optionValue);
int
setContextOption(int optionName, ProducerDataCallback optionValue);
int
setContextOption(int optionName, ConsumerDataVerificationCallback optionValue);
int
setContextOption(int optionName, ConsumerDataCallback optionValue);
int
setContextOption(int optionName, ConsumerInterestCallback optionValue);
int
setContextOption(int optionName, ProducerInterestCallback optionValue);
int
setContextOption(int optionName, ConsumerContentCallback optionValue);
int
setContextOption(int optionName, ConsumerNackCallback optionValue);
int
setContextOption(int optionName, ConsumerManifestCallback optionValue);
int
setContextOption(int optionName, KeyLocator optionValue);
int
setContextOption(int optionName, Exclude optionValue);
/*
* Context option getters
* Return OPTION_FOUND if success; otherwise -- OPTION_NOT_FOUND
*/
int
getContextOption(int optionName, int& optionValue);
int
getContextOption(int optionName, size_t& optionValue);
int
getContextOption(int optionName, bool& optionValue);
int
getContextOption(int optionName, Name& optionValue);
int
getContextOption(int optionName, ProducerDataCallback& optionValue);
int
getContextOption(int optionName, ConsumerDataVerificationCallback& optionValue);
int
getContextOption(int optionName, ConsumerDataCallback& optionValue);
int
getContextOption(int optionName, ConsumerInterestCallback& optionValue);
int
getContextOption(int optionName, ProducerInterestCallback& optionValue);
int
getContextOption(int optionName, ConsumerContentCallback& optionValue);
int
getContextOption(int optionName, ConsumerNackCallback& optionValue);
int
getContextOption(int optionName, ConsumerManifestCallback& optionValue);
int
getContextOption(int optionName, KeyLocator& optionValue);
int
getContextOption(int optionName, Exclude& optionValue);
int
getContextOption(int optionName, shared_ptr<Face>& optionValue);
int
getContextOption(int optionName, TreeNode& optionValue);
private:
void
postponedConsume(Name suffix);
void
onStrategyChangeSuccess(const nfd::ControlParameters& commandSuccessResult, const std::string& message);
void
onStrategyChangeError(uint32_t code, const std::string& error, const std::string& message);
private:
// context inner state variables
bool m_isRunning;
shared_ptr<ndn::Face> m_face;
shared_ptr<DataRetrievalProtocol> m_dataRetrievalProtocol;
KeyChain m_keyChain;
shared_ptr<nfd::Controller> m_controller;
Name m_prefix;
Name m_suffix;
Name m_forwardingStrategy;
int m_interestLifetimeMillisec;
int m_minWindowSize;
int m_maxWindowSize;
int m_currentWindowSize;
int m_nMaxRetransmissions;
int m_nMaxExcludedDigests;
size_t m_sendBufferSize;
size_t m_receiveBufferSize;
bool m_isAsync;
/// selectors
int m_minSuffixComponents;
int m_maxSuffixComponents;
KeyLocator m_publisherKeyLocator;
Exclude m_exclude;
int m_childSelector;
bool m_mustBeFresh;
/// user-provided callbacks
ConsumerInterestCallback m_onInterestRetransmitted;
ConsumerInterestCallback m_onInterestToLeaveContext;
ConsumerInterestCallback m_onInterestExpired;
ConsumerInterestCallback m_onInterestSatisfied;
ConsumerDataCallback m_onDataEnteredContext;
ConsumerDataVerificationCallback m_onDataToVerify;
ConsumerDataCallback m_onContentData;
ConsumerNackCallback m_onNack;
ConsumerManifestCallback m_onManifest;
ConsumerContentCallback m_onPayloadReassembled;
};
} // namespace ndn
#endif // CONSUMER_CONTEXT_HPP
| 7,139 | 26.890625 | 106 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/producer-context.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef PRODUCER_CONTEXT_HPP
#define PRODUCER_CONTEXT_HPP
#include "common.hpp"
#include "context-options.hpp"
#include "context-default-values.hpp"
#include "context.hpp"
#include "cs.hpp"
#include "repo-command-parameter.hpp"
#include "infomax-tree-node.hpp"
#include "infomax-prioritizer.hpp"
#include <ndn-cxx/signature.hpp>
#include <ndn-cxx/security/key-chain.hpp>
#include <ndn-cxx/management/nfd-controller.hpp>
#include <ndn-cxx/util/scheduler.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/lockfree/queue.hpp>
#include <boost/atomic.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/asio.hpp>
#include <queue>
#include <time.h> // for nanosleep
namespace ndn {
class Prioritizer;
/**
* @brief Producer context is a container of producer-specific transmission parameters for a
* specific name prefix.
*
* Producer context performs transformation of Application Data Units into Data packets.
* Producer context can be tuned using set/getcontextopt primitives.
*/
class Producer : public Context
{
public:
/**
* @brief Initializes producer context with default parameters.
* Context's parameters can be changed with setContextOption function.
*
* @param prefix Name components that identify the namespace
* where all generated Data packets will be placed.
*/
explicit Producer(Name prefix);
/**
* @brief Detaches producer context from the network and releases all associated system resources.
*
*/
~Producer();
/**
* @brief Attaches producer context to the network by registering its name prefix.
*
*/
void
attach();
/**
* @brief Performs segmentation of the supplied memory buffer into Data packets.
* Produced Data packets are placed in the output buffer to satisfy pending and future Interests.
* Produce() blocks until all Data segments are succesfully placed in the output buffer.
*
* @param suffix Name components that identify the boundary of Application Data Unit (ADU)
* @param buffer Memory buffer storing Application Data Unit (ADU)
* @param bufferSize Size of the supplied memory buffer
*
* @return The number of produced Data packets or -1 if the supplied ADU requires
* more Data segments than it is possible to store in the output buffer.
*/
void
produce(Name suffix, const uint8_t* buffer, size_t bufferSize);
void
produce(Data& packet);
/**
* @brief Performs segmentation of the supplied memory buffer into Data packets.
* Produced Data packets are placed in the output buffer to satisfy pending and future Interests.
* asyncProduce() does not block and schedules segmentation for future execution.
*
* @param suffix Name components that identify the boundary of Application Data Unit (ADU)
* @param buffer Memory buffer storing Application Data Unit (ADU)
* @param bufferSize Size of the supplied memory buffer
*
*/
void
asyncProduce(Name suffix, const uint8_t* buffer, size_t bufferSize);
void
asyncProduce(Data& packet);
/**
* @brief Satisfies an Interest with Negative Acknowledgement.
*
* @param appNack Negative Acknowledgement
*/
int
nack(ApplicationNack appNack);
/*
* Context option setters
*/
int
setContextOption(int optionName, int optionValue);
int
setContextOption(int optionName, bool optionValue);
int
setContextOption(int optionName, size_t optionValue);
int
setContextOption(int optionName, Name optionValue);
int
setContextOption(int optionName, ProducerDataCallback optionValue);
int
setContextOption(int optionName, ProducerInterestCallback optionValue);
int
setContextOption(int optionName, ConsumerDataVerificationCallback optionValue);
int
setContextOption(int optionName, ConsumerDataCallback optionValue);
int
setContextOption(int optionName, ConsumerInterestCallback optionValue);
int
setContextOption(int optionName, ConsumerContentCallback optionValue);
int
setContextOption(int optionName, ConsumerNackCallback optionValue);
int
setContextOption(int optionName, ConsumerManifestCallback optionValue);
int
setContextOption(int optionName, KeyLocator optionValue);
int
setContextOption(int optionName, Exclude optionValue);
/*
* Context option getters
*/
int
getContextOption(int optionName, int& optionValue);
int
getContextOption(int optionName, bool& optionValue);
int
getContextOption(int optionName, size_t& optionValue);
int
getContextOption(int optionName, Name& optionValue);
int
getContextOption(int optionName, ProducerDataCallback& optionValue);
int
getContextOption(int optionName, ProducerInterestCallback& optionValue);
int
getContextOption(int optionName, ConsumerDataVerificationCallback& optionValue);
int
getContextOption(int optionName, ConsumerDataCallback& optionValue);
int
getContextOption(int optionName, ConsumerInterestCallback& optionValue);
int
getContextOption(int optionName, ConsumerContentCallback& optionValue);
int
getContextOption(int optionName, ConsumerNackCallback& optionValue);
int
getContextOption(int optionName, ConsumerManifestCallback& optionValue);
int
getContextOption(int optionName, KeyLocator& optionValue);
int
getContextOption(int optionName, Exclude& optionValue);
int
getContextOption(int optionName, shared_ptr<Face>& optionValue);
int
getContextOption(int optionName, TreeNode& optionValue);
private:
// context inner state variables
ndn::shared_ptr<ndn::Face> m_face;
boost::asio::io_service m_ioService;
shared_ptr<nfd::Controller> m_controller;
Scheduler* m_scheduler;
Name m_prefix;
Name m_targetRepoPrefix;
Name m_forwardingStrategy;
int m_dataPacketSize;
int m_dataFreshness;
int m_registrationStatus;
bool m_isMakingManifest;
// repo related stuff
bool m_isWritingToLocalRepo;
boost::asio::io_service m_repoIoService;
boost::asio::ip::tcp::socket m_repoSocket;
// infomax related stuff
uint64_t m_infomaxTreeVersion;
uint64_t m_infomaxUpdateInterval;
bool m_isNewInfomaxData;
TreeNode m_infomaxRoot;
shared_ptr<Prioritizer> m_infomaxPrioritizer;
int m_infomaxType; // currently there are only 2 types: normal and InfoMax producer
int m_signatureType;
int m_signatureSize;
int m_keyLocatorSize;
KeyLocator m_keyLocator;
KeyChain m_keyChain;
// buffers
Cs m_sendBuffer;
//boost::lockfree::queue<shared_ptr<const Interest> >m_receiveBuffer{DEFAULT_PRODUCER_RCV_BUFFER_SIZE};
std::queue< shared_ptr<const Interest> > m_receiveBuffer;
boost::mutex m_receiveBufferMutex;
boost::atomic_size_t m_receiveBufferCapacity;
boost::atomic_size_t m_receiveBufferSize;
// threads
boost::thread m_listeningThread;
boost::thread m_processingThread;
// user-defined callbacks
ProducerInterestCallback m_onInterestEntersContext;
ProducerInterestCallback m_onInterestDroppedFromRcvBuffer;
ProducerInterestCallback m_onInterestPassedRcvBuffer;
ProducerInterestCallback m_onInterestSatisfiedFromSndBuffer;
ProducerInterestCallback m_onInterestProcess;
ProducerDataCallback m_onNewSegment;
ProducerDataCallback m_onDataToSecure;
ProducerDataCallback m_onDataInSndBuffer;
ProducerDataCallback m_onDataLeavesContext;
ProducerDataCallback m_onDataEvictedFromSndBuffer;
private:
void
listen();
void
updateInfomaxTree();
void
onInterest(const Name& name, const Interest& interest);
void
onRegistrationSucceded (const ndn::Name& prefix);
void
onRegistrationFailed (const ndn::Name& prefix, const std::string& reason);
void
processIncomingInterest(/*const Name& name, const Interest& interest*/);
void
processInterestFromReceiveBuffer();
void
passSegmentThroughCallbacks(shared_ptr<Data> segment);
size_t
estimateManifestSize(shared_ptr<Manifest> manifest);
void
writeToRepo(Name dataPrefix, uint64_t startSegment, uint64_t endSegment);
void
onRepoReply(const ndn::Interest& interest, ndn::Data& data);
void
onRepoTimeout(const ndn::Interest& interest);
void
onStrategyChangeSuccess(const nfd::ControlParameters& commandSuccessResult,
const std::string& message);
void
onStrategyChangeError(uint32_t code, const std::string& error, const std::string& message);
};
} // namespace ndn
#endif // PRODUCER_CONTEXT_HPP
| 9,575 | 27.843373 | 105 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/cs-entry.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef NFD_TABLE_CS_ENTRY_HPP
#define NFD_TABLE_CS_ENTRY_HPP
#include "common.hpp"
#include <ndn-cxx/util/crypto.hpp>
namespace ndn {
namespace cs {
class Entry;
/** \brief represents a CS entry
*/
class Entry : noncopyable
{
public:
typedef std::map<int, std::list<Entry*>::iterator > LayerIterators;
Entry();
/** \brief releases reference counts on shared objects
*/
void
release();
/** \brief returns the name of the Data packet stored in the CS entry
* \return{ NDN name }
*/
const Name&
getName() const;
/** \brief Data packet is unsolicited if this particular NDN node
* did not receive an Interest packet for it, or the Interest packet has already expired
* \return{ True if the Data packet is unsolicited; otherwise False }
*/
bool
isUnsolicited() const;
/** \brief returns the absolute time when Data becomes expired
* \return{ Time (resolution up to time::milliseconds) }
*/
const time::steady_clock::TimePoint&
getStaleTime() const;
/** \brief returns the Data packet stored in the CS entry
*/
const Data&
getData() const;
/** \brief changes the content of CS entry and recomputes digest
*/
void
setData(const Data& data, bool isUnsolicited);
/** \brief changes the content of CS entry and modifies digest
*/
void
setData(const Data& data, bool isUnsolicited, const ndn::ConstBufferPtr& digest);
/** \brief refreshes the time when Data becomes expired
* according to the current absolute time.
*/
void
updateStaleTime();
/** \brief returns the digest of the Data packet stored in the CS entry.
*/
const ndn::ConstBufferPtr&
getDigest() const;
/** \brief saves the iterator pointing to the CS entry on a specific layer of skip list
*/
void
setIterator(int layer, const LayerIterators::mapped_type& layerIterator);
/** \brief removes the iterator pointing to the CS entry on a specific layer of skip list
*/
void
removeIterator(int layer);
/** \brief returns the table containing <layer, iterator> pairs.
*/
const LayerIterators&
getIterators() const;
private:
/** \brief prints <layer, iterator> pairs.
*/
void
printIterators() const;
private:
time::steady_clock::TimePoint m_staleAt;
shared_ptr<const Data> m_dataPacket;
bool m_isUnsolicited;
Name m_nameWithDigest;
mutable ndn::ConstBufferPtr m_digest;
LayerIterators m_layerIterators;
};
inline
Entry::Entry()
{
}
inline const Name&
Entry::getName() const
{
return m_nameWithDigest;
}
inline const Data&
Entry::getData() const
{
return *m_dataPacket;
}
inline bool
Entry::isUnsolicited() const
{
return m_isUnsolicited;
}
inline const time::steady_clock::TimePoint&
Entry::getStaleTime() const
{
return m_staleAt;
}
inline const Entry::LayerIterators&
Entry::getIterators() const
{
return m_layerIterators;
}
} // namespace cs
} // namespace nfd
#endif // NFD_TABLE_CS_ENTRY_HPP
| 4,007 | 23.290909 | 99 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/context-default-values.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef CONTEXT_DEFAULT_VALUES_HPP
#define CONTEXT_DEFAULT_VALUES_HPP
// this file contains various default values
// numbers here are not unique
#define EMPTY_CALLBACK 0
// protocols
#define SDR 0
#define UDR 1
#define RDR 2
#define IDR 3
// forwarding strategies
const ndn::Name BEST_ROUTE("ndn:/localhost/nfd/strategy/best-route");
const ndn::Name BROADCAST("ndn:/localhost/nfd/strategy/broadcast");
const ndn::Name CLIENT_CONTROL("ndn:/localhost/nfd/strategy/client-control");
//const ndn::Name NCC("ndn:/localhost/nfd/strategy/ncc");
// default values
#define DEFAULT_INTEREST_LIFETIME 200 // milliseconds
#define DEFAULT_DATA_FRESHNESS 100000 // milliseconds ~= 100 seconds
#define DEFAULT_DATA_PACKET_SIZE 2048 // bytes
#define DEFAULT_INTEREST_SCOPE 2
#define DEFAULT_MIN_SUFFIX_COMP -1
#define DEFAULT_MAX_SUFFIX_COMP -1
#define DEFAULT_PRODUCER_RCV_BUFFER_SIZE 1000 // of Interests
#define DEFAULT_PRODUCER_SND_BUFFER_SIZE 1000 // of Data
#define DEFAULT_KEY_LOCATOR_SIZE 256 // of bytes
#define DEFAULT_SAFETY_OFFSET 10 // of bytes
#define DEFAULT_MIN_WINDOW_SIZE 4 // of Interests
#define DEFAULT_MAX_WINDOW_SIZE 64 // of Interests
#define DEFAULT_DIGEST_SIZE 32 // of bytes
#define DEFAULT_FAST_RETX_CONDITION 3 // of out-of-order segments
// maximum allowed values
#define CONSUMER_MIN_RETRANSMISSIONS 0
#define CONSUMER_MAX_RETRANSMISSIONS 32
#define DEFAULT_MAX_EXCLUDED_DIGESTS 5
#define MAX_DATA_PACKET_SIZE 8096
// set/getcontextoption values
#define OPTION_FOUND 0
#define OPTION_NOT_FOUND 1
#define OPTION_VALUE_SET 2
#define OPTION_VALUE_NOT_SET 3
#define OPTION_DEFAULT_VALUE 666 // some rare number
// misc. values
#define PRODUCER_OPERATION_FAILED 10
#define CONSUMER_READY 0
#define CONSUMER_BUSY 1
#define REGISTRATION_NOT_ATTEMPTED 0
#define REGISTRATION_SUCCESS 1
#define REGISTRATION_FAILURE 2
#define REGISTRATION_IN_PROGRESS 3
#define LEFTMOST_CHILD 0
#define RIGHTMOST_CHILD 1
#define SHA_256 1
#define RSA_256 2
// Negative acknowledgement related constants
#define NACK_DATA_TYPE tlv::ContentType_Nack
#define NACK_DELAY 1
#define NACK_INTEREST_NOT_VERIFIED 2
// Manifest related constants
#define MANIFEST_DATA_TYPE tlv::ContentType_Manifest
#define FULL_NAME_ENUMERATION 0
#define DIGEST_ENUMERATION 1
#define CONTENT_DATA_TYPE tlv::ContentType_Blob
// InfoMax parameter
#define INFOMAX_DEFAULT_LIST_SIZE 10
#define INFOMAX_INTEREST_TAG "InfoMax"
#define INFOMAX_META_INTEREST_TAG "MetaInfo"
#define INFOMAX_DEFAULT_UPDATE_INTERVAL 5000 // 5 seconds
// InfoMax prioritizer
#define INFOMAX_NONE 0
#define INFOMAX_SIMPLE_PRIORITY 1
#define INFOMAX_MERGE_PRIORITY 2
#endif
| 3,817 | 32.491228 | 99 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/unreliable-data-retrieval.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef UNRELIABLE_DATA_RETRIEVAL_HPP
#define UNRELIABLE_DATA_RETRIEVAL_HPP
#include "data-retrieval-protocol.hpp"
#include "selector-helper.hpp"
namespace ndn {
/*
* UDR provides unreliable and unordered delivery of data segments that belong to a single ADU
* between the consumer application and the NDN network.
* In UDR, the transfer of every ADU begins with the segment number zero.
* UDR infers the name of the last data segment of the sequence with help of FinalBlockID field,
* and stops the transmission of Interest packets at this name (segment).
* FinalBlockID packet field is set at the moment of application frame (ADU) segmentation.
*/
class UnreliableDataRetrieval : public DataRetrievalProtocol
{
public:
UnreliableDataRetrieval(Context* context);
void
start();
void
stop();
private:
void
sendInterest();
void
onData(const ndn::Interest& interest, ndn::Data& data);
void
onTimeout(const ndn::Interest& interest);
void
checkFastRetransmissionConditions(const ndn::Interest& interest);
void
fastRetransmit(const ndn::Interest& interest, uint64_t segNumber);
void
removeAllPendingInterests();
private:
bool m_isFinalBlockNumberDiscovered;
int m_nTimeouts;
uint64_t m_finalBlockNumber;
uint64_t m_segNumber;
int m_currentWindowSize;
int m_interestsInFlight;
std::unordered_map<uint64_t, const PendingInterestId*> m_expressedInterests; // by segment number
// Fast Retransmission
std::map<uint64_t, bool> m_receivedSegments;
std::map<uint64_t, bool> m_fastRetxSegments;
};
} // namespace ndn
#endif // UNRELIABLE_DATA_RETRIEVAL_HPP
| 2,715 | 29.516854 | 99 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/unreliable-data-retrieval.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "unreliable-data-retrieval.hpp"
#include "consumer-context.hpp"
namespace ndn {
UnreliableDataRetrieval::UnreliableDataRetrieval(Context* context)
: DataRetrievalProtocol(context)
, m_isFinalBlockNumberDiscovered(false)
, m_nTimeouts(0)
, m_finalBlockNumber(std::numeric_limits<uint64_t>::max())
, m_segNumber(0)
, m_currentWindowSize(0)
, m_interestsInFlight(0)
{
context->getContextOption(FACE, m_face);
}
void
UnreliableDataRetrieval::start()
{
m_isRunning = true;
m_isFinalBlockNumberDiscovered = false;
m_nTimeouts = 0;
m_finalBlockNumber = std::numeric_limits<uint64_t>::max();
m_segNumber = 0;
m_interestsInFlight = 0;
m_currentWindowSize = 0;
// this is to support window size "inheritance" between consume calls
/*int currentWindowSize = -1;
m_context->getContextOption(CURRENT_WINDOW_SIZE, currentWindowSize);
if (currentWindowSize > 0)
{
m_currentWindowSize = currentWindowSize;
}
else
{
int minWindowSize = -1;
m_context->getContextOption(MIN_WINDOW_SIZE, minWindowSize);
m_currentWindowSize = minWindowSize;
}
// initial burst of Interests
while (m_interestsInFlight < m_currentWindowSize)
{
if (m_isFinalBlockNumberDiscovered)
{
if (m_segNumber < m_finalBlockNumber)
{
sendInterest();
}
else
{
break;
}
}
else
{
sendInterest();
}
}*/
//send exactly 1 Interest to get the FinalBlockId
sendInterest();
bool isAsync = false;
m_context->getContextOption(ASYNC_MODE, isAsync);
if (!isAsync)
{
m_face->processEvents();
}
}
void
UnreliableDataRetrieval::sendInterest()
{
Name prefix;
m_context->getContextOption(PREFIX, prefix);
Name suffix;
m_context->getContextOption(SUFFIX, suffix);
if (!suffix.empty())
{
prefix.append(suffix);
}
prefix.appendSegment(m_segNumber);
Interest interest(prefix);
int interestLifetime = 0;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
interest.setInterestLifetime(time::milliseconds(interestLifetime));
SelectorHelper::applySelectors(interest, m_context);
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), interest);
}
m_interestsInFlight++;
m_expressedInterests[m_segNumber] = m_face->expressInterest(interest,
bind(&UnreliableDataRetrieval::onData, this, _1, _2),
bind(&UnreliableDataRetrieval::onTimeout, this, _1));
m_segNumber++;
}
void
UnreliableDataRetrieval::stop()
{
m_isRunning = false;
removeAllPendingInterests();
}
void
UnreliableDataRetrieval::onData(const ndn::Interest& interest, ndn::Data& data)
{
if (m_isRunning == false)
return;
m_interestsInFlight--;
ConsumerDataCallback onDataEnteredContext = EMPTY_CALLBACK;
m_context->getContextOption(DATA_ENTER_CNTX, onDataEnteredContext);
if (onDataEnteredContext != EMPTY_CALLBACK)
{
onDataEnteredContext(*dynamic_cast<Consumer*>(m_context), data);
}
ConsumerInterestCallback onInterestSatisfied = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_SATISFIED, onInterestSatisfied);
if (onInterestSatisfied != EMPTY_CALLBACK)
{
onInterestSatisfied(*dynamic_cast<Consumer*>(m_context), const_cast<Interest&>(interest));
}
ConsumerDataVerificationCallback onDataToVerify = EMPTY_CALLBACK;
m_context->getContextOption(DATA_TO_VERIFY, onDataToVerify);
bool isDataSecure = false;
if (onDataToVerify == EMPTY_CALLBACK)
{
isDataSecure = true;
}
else
{
if (onDataToVerify(*dynamic_cast<Consumer*>(m_context), data) == true) // runs verification routine
{
isDataSecure = true;
}
}
if (isDataSecure)
{
checkFastRetransmissionConditions(interest);
if (data.getContentType() == CONTENT_DATA_TYPE)
{
int maxWindowSize = -1;
m_context->getContextOption(MAX_WINDOW_SIZE, maxWindowSize);
if (m_currentWindowSize < maxWindowSize)
{
m_currentWindowSize++;
}
if (!data.getFinalBlockId().empty())
{
m_isFinalBlockNumberDiscovered = true;
m_finalBlockNumber = data.getFinalBlockId().toSegment();
}
const Block content = data.getContent();
ConsumerContentCallback onPayload = EMPTY_CALLBACK;
m_context->getContextOption(CONTENT_RETRIEVED, onPayload);
if (onPayload != EMPTY_CALLBACK)
{
onPayload(*dynamic_cast<Consumer*>(m_context), content.value(), content.value_size());
}
}
else if (data.getContentType() == NACK_DATA_TYPE)
{
int minWindowSize = -1;
m_context->getContextOption(MIN_WINDOW_SIZE, minWindowSize);
if (m_currentWindowSize > minWindowSize)
{
m_currentWindowSize = m_currentWindowSize / 2; // cut in half
if (m_currentWindowSize == 0)
m_currentWindowSize++;
}
shared_ptr<ApplicationNack> nack = make_shared<ApplicationNack>(data);
ConsumerNackCallback onNack = EMPTY_CALLBACK;
m_context->getContextOption(NACK_ENTER_CNTX, onNack);
if (onNack != EMPTY_CALLBACK)
{
onNack(*dynamic_cast<Consumer*>(m_context), *nack);
}
}
}
if (!m_isRunning ||
((m_isFinalBlockNumberDiscovered) && (data.getName().get(-1).toSegment() >= m_finalBlockNumber)))
{
removeAllPendingInterests();
m_isRunning = false;
//reduce window size to prevent its speculative growth in case when consume() is called in loop
int currentWindowSize = -1;
m_context->getContextOption(CURRENT_WINDOW_SIZE, currentWindowSize);
if (currentWindowSize > m_finalBlockNumber)
{
m_context->setContextOption(CURRENT_WINDOW_SIZE, (int)(m_finalBlockNumber));
}
}
// some flow control
while (m_interestsInFlight < m_currentWindowSize)
{
if (m_isFinalBlockNumberDiscovered)
{
if (m_segNumber <= m_finalBlockNumber)
{
sendInterest();
}
else
{
break;
}
}
else
{
sendInterest();
}
}
}
void
UnreliableDataRetrieval::onTimeout(const ndn::Interest& interest)
{
if (m_isRunning == false)
return;
m_interestsInFlight--;
int minWindowSize = -1;
m_context->getContextOption(MIN_WINDOW_SIZE, minWindowSize);
if (m_currentWindowSize > minWindowSize)
{
m_currentWindowSize = m_currentWindowSize / 2; // cut in half
if (m_currentWindowSize == 0)
m_currentWindowSize++;
}
ConsumerInterestCallback onInterestExpired = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_EXPIRED, onInterestExpired);
if (onInterestExpired != EMPTY_CALLBACK)
{
onInterestExpired(*dynamic_cast<Consumer*>(m_context), const_cast<Interest&>(interest));
}
// this code handles the situation when an application frame is small (1 or several packets)
// and packets are lost. Without this code, the protocol continues to send Interests for
// non-existing packets, because it was never able to discover the correct FinalBlockID.
if (!m_isFinalBlockNumberDiscovered)
{
m_nTimeouts++;
if(m_nTimeouts > 2)
{
m_isRunning = false;
return;
}
}
// some flow control
while (m_interestsInFlight < m_currentWindowSize)
{
//std::cout << "inFlight: " << m_interestsInFlight << " windSize " << m_currentWindowSize << std::endl;
if (m_isFinalBlockNumberDiscovered)
{
if (m_segNumber <= m_finalBlockNumber)
{
sendInterest();
}
else
{
break;
}
}
else
{
sendInterest();
}
}
}
void
UnreliableDataRetrieval::checkFastRetransmissionConditions(const ndn::Interest& interest)
{
uint64_t segNumber = interest.getName().get(-1).toSegment();
m_receivedSegments[segNumber] = true;
m_fastRetxSegments.erase(segNumber);
uint64_t possiblyLostSegment = 0;
uint64_t highestReceivedSegment = m_receivedSegments.rbegin()->first;
for (uint64_t i = 0; i <= highestReceivedSegment; i++)
{
if (m_receivedSegments.find(i) == m_receivedSegments.end()) // segment is not received yet
{
// segment has not been fast retransmitted yet
if (m_fastRetxSegments.find(i) == m_fastRetxSegments.end())
{
possiblyLostSegment = i;
uint8_t nOutOfOrderSegments = 0;
for (uint64_t j = i; j <= highestReceivedSegment; j++)
{
if (m_receivedSegments.find(j) != m_receivedSegments.end())
{
nOutOfOrderSegments++;
if (nOutOfOrderSegments == DEFAULT_FAST_RETX_CONDITION)
{
m_fastRetxSegments[possiblyLostSegment] = true;
fastRetransmit(interest, possiblyLostSegment);
}
}
}
}
}
}
}
void
UnreliableDataRetrieval::fastRetransmit(const ndn::Interest& interest, uint64_t segNumber)
{
Name name = interest.getName().getPrefix(-1);
name.appendSegment(segNumber);
Interest retxInterest(name);
SelectorHelper::applySelectors(retxInterest, m_context);
ConsumerInterestCallback onInterestRetransmitted = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_RETRANSMIT, onInterestRetransmitted);
if (onInterestRetransmitted != EMPTY_CALLBACK)
{
onInterestRetransmitted(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
//retransmit
m_interestsInFlight++;
m_expressedInterests[m_segNumber] = m_face->expressInterest(retxInterest,
bind(&UnreliableDataRetrieval::onData, this, _1, _2),
bind(&UnreliableDataRetrieval::onTimeout, this, _1));
}
void
UnreliableDataRetrieval::removeAllPendingInterests()
{
bool isAsync = false;
m_context->getContextOption(ASYNC_MODE, isAsync);
if (!isAsync)
{
//won't work ---> m_face->getIoService().stop();
m_face->removePendingInterest(); // faster, but destroys everything
}
else // slower, but destroys only necessary Interests
{
for(std::unordered_map<uint64_t, const PendingInterestId*>::iterator it = m_expressedInterests.begin();
it != m_expressedInterests.end(); ++it)
{
m_face->removePendingInterest(it->second);
}
}
m_expressedInterests.clear();
}
} //namespace ndn
| 11,990 | 27.618138 | 107 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/data-retrieval-protocol.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "data-retrieval-protocol.hpp"
namespace ndn {
DataRetrievalProtocol::DataRetrievalProtocol(Context* context)
: m_context(context)
, m_isRunning(false)
{
}
void
DataRetrievalProtocol::updateFace()
{
m_context->getContextOption(FACE, m_face);
}
bool
DataRetrievalProtocol::isRunning()
{
return m_isRunning;
}
} //namespace nfd
| 1,415 | 30.466667 | 99 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/consumer-context.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "consumer-context.hpp"
namespace ndn {
Consumer::Consumer(Name prefix, int protocol)
: m_isRunning(false)
, m_prefix(prefix)
, m_interestLifetimeMillisec(DEFAULT_INTEREST_LIFETIME)
, m_minWindowSize(DEFAULT_MIN_WINDOW_SIZE)
, m_maxWindowSize(DEFAULT_MAX_WINDOW_SIZE)
, m_currentWindowSize(-1)
, m_nMaxRetransmissions(CONSUMER_MAX_RETRANSMISSIONS)
, m_nMaxExcludedDigests(DEFAULT_MAX_EXCLUDED_DIGESTS)
, m_isAsync(false)
, m_minSuffixComponents(DEFAULT_MIN_SUFFIX_COMP)
, m_maxSuffixComponents(DEFAULT_MAX_SUFFIX_COMP)
, m_childSelector(0)
, m_mustBeFresh(false)
, m_onInterestToLeaveContext(EMPTY_CALLBACK)
, m_onInterestExpired(EMPTY_CALLBACK)
, m_onInterestSatisfied(EMPTY_CALLBACK)
, m_onDataEnteredContext(EMPTY_CALLBACK)
, m_onDataToVerify(EMPTY_CALLBACK)
, m_onContentData(EMPTY_CALLBACK)
, m_onNack(EMPTY_CALLBACK)
, m_onManifest(EMPTY_CALLBACK)
, m_onPayloadReassembled(EMPTY_CALLBACK)
{
m_face = ndn::make_shared<Face>();
//m_ioService = ndn::make_shared<boost::asio::io_service>();
m_controller = ndn::make_shared<nfd::Controller>(*m_face, m_keyChain);
if (protocol == UDR)
{
m_dataRetrievalProtocol = make_shared<UnreliableDataRetrieval>(this);
}
else if (protocol == RDR)
{
m_dataRetrievalProtocol = make_shared<ReliableDataRetrieval>(this);
}
else if (protocol == IDR)
{
m_dataRetrievalProtocol = make_shared<InfoMaxDataRetrieval>(this);
}
else
{
m_dataRetrievalProtocol = make_shared<SimpleDataRetrieval>(this);
}
}
Consumer::~Consumer()
{
stop();
m_dataRetrievalProtocol.reset(); // reset the pointer counter
m_face.reset(); // reset the pointer counter
}
int
Consumer::consume(Name suffix)
{
if (m_isRunning/*m_dataRetrievalProtocol->isRunning()*/)
{
// put in the schedule
m_face->getIoService().post(bind(&Consumer::postponedConsume, this, suffix));
return CONSUMER_BUSY;
}
// if previously used in non-blocking mode
if (m_isAsync)
{
m_face = ndn::make_shared<Face>();
m_controller = ndn::make_shared<nfd::Controller>(*m_face, m_keyChain);
m_dataRetrievalProtocol->updateFace();
}
m_suffix = suffix;
m_isAsync = false;
m_dataRetrievalProtocol->start();
m_isRunning = false;
return CONSUMER_READY;
}
void
Consumer::postponedConsume(Name suffix)
{
// if previously used in non-blocking mode
if (m_isAsync)
{
m_face = ndn::make_shared<Face>();
m_controller = ndn::make_shared<nfd::Controller>(*m_face, m_keyChain);
m_dataRetrievalProtocol->updateFace();
}
m_suffix = suffix;
m_isAsync = false;
m_dataRetrievalProtocol->start();
}
int
Consumer::asyncConsume(Name suffix)
{
if (m_dataRetrievalProtocol->isRunning())
{
return CONSUMER_BUSY;
}
if (!m_isAsync) // if previously used in blocking mode
{
m_face = FaceHelper::getFace();
m_controller = ndn::make_shared<nfd::Controller>(*m_face, m_keyChain);
m_dataRetrievalProtocol->updateFace();
}
m_suffix = suffix;
m_isAsync = true;
m_dataRetrievalProtocol->start();
return CONSUMER_READY;
}
void
Consumer::stop()
{
if (m_dataRetrievalProtocol->isRunning())
{
m_dataRetrievalProtocol->stop();
m_face->getIoService().stop();
m_face->getIoService().reset();
}
m_isRunning = false;
}
int
Consumer::setContextOption(int optionName, int optionValue)
{
switch (optionName)
{
case MIN_WINDOW_SIZE:
m_minWindowSize = optionValue;
return OPTION_VALUE_SET;
case MAX_WINDOW_SIZE:
m_maxWindowSize = optionValue;
return OPTION_VALUE_SET;
case MAX_EXCLUDED_DIGESTS:
m_nMaxExcludedDigests = optionValue;
return OPTION_VALUE_SET;
case CURRENT_WINDOW_SIZE:
m_currentWindowSize = optionValue;
return OPTION_VALUE_SET;
case RCV_BUF_SIZE:
m_receiveBufferSize = optionValue;
return OPTION_VALUE_SET;
case SND_BUF_SIZE:
m_sendBufferSize = optionValue;
return OPTION_VALUE_SET;
case INTEREST_RETX:
if (optionValue < CONSUMER_MAX_RETRANSMISSIONS)
{
m_nMaxRetransmissions = optionValue;
return OPTION_VALUE_SET;
}
else
{
return OPTION_VALUE_NOT_SET;
}
case INTEREST_LIFETIME:
m_interestLifetimeMillisec = optionValue;
return OPTION_VALUE_SET;
case MIN_SUFFIX_COMP_S:
if (optionValue >= 0)
{
m_minSuffixComponents = optionValue;
}
else
{
m_minSuffixComponents = DEFAULT_MIN_SUFFIX_COMP;
return OPTION_VALUE_NOT_SET;
}
case MAX_SUFFIX_COMP_S:
if (optionValue >= 0)
{
m_maxSuffixComponents = optionValue;
}
else
{
m_maxSuffixComponents = DEFAULT_MAX_SUFFIX_COMP;
return OPTION_VALUE_NOT_SET;
}
case RIGHTMOST_CHILD_S:
if (optionValue == 1)
{
m_childSelector = 1;
}
else
{
m_childSelector = 0;
}
return OPTION_VALUE_SET;
case LEFTMOST_CHILD_S:
if (optionValue == 1)
{
m_childSelector = 0;
}
else
{
m_childSelector = 1;
}
return OPTION_VALUE_SET;
case INTEREST_RETRANSMIT:
if (optionValue == EMPTY_CALLBACK)
{
m_onInterestRetransmitted = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case INTEREST_EXPIRED:
if (optionValue == EMPTY_CALLBACK)
{
m_onInterestExpired = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case INTEREST_SATISFIED:
if (optionValue == EMPTY_CALLBACK)
{
m_onInterestSatisfied = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case INTEREST_LEAVE_CNTX:
if (optionValue == EMPTY_CALLBACK)
{
m_onInterestToLeaveContext = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case DATA_ENTER_CNTX:
if (optionValue == EMPTY_CALLBACK)
{
m_onDataEnteredContext = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case DATA_TO_VERIFY:
if (optionValue == EMPTY_CALLBACK)
{
m_onDataToVerify = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case CONTENT_RETRIEVED:
if (optionValue == EMPTY_CALLBACK)
{
m_onPayloadReassembled = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, size_t optionValue)
{
switch (optionName)
{
case RCV_BUF_SIZE:
m_receiveBufferSize = optionValue;
return OPTION_VALUE_SET;
case SND_BUF_SIZE:
m_sendBufferSize = optionValue;
return OPTION_VALUE_SET;
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, bool optionValue)
{
switch (optionName)
{
case MUST_BE_FRESH_S:
m_mustBeFresh = optionValue;
return OPTION_VALUE_SET;
case RIGHTMOST_CHILD_S:
if (optionValue == true)
{
m_childSelector = 1;
}
else
{
m_childSelector = 0;
}
return OPTION_VALUE_SET;
case LEFTMOST_CHILD_S:
if (optionValue == true)
{
m_childSelector = 0;
}
else
{
m_childSelector = 1;
}
return OPTION_VALUE_SET;
case RUNNING:
m_isRunning = optionValue;
return OPTION_VALUE_SET;
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, Name optionValue)
{
switch (optionName)
{
case PREFIX:
m_prefix = optionValue;;
return OPTION_VALUE_SET;
case SUFFIX:
m_suffix = optionValue;
return OPTION_VALUE_SET;
case FORWARDING_STRATEGY:
m_forwardingStrategy = optionValue;
if (m_forwardingStrategy.empty())
{
nfd::ControlParameters parameters;
parameters.setName(m_prefix);
m_controller->start<nfd::StrategyChoiceUnsetCommand>(parameters,
bind(&Consumer::onStrategyChangeSuccess, this, _1,
"Successfully unset strategy choice"),
bind(&Consumer::onStrategyChangeError, this, _1, _2,
"Failed to unset strategy choice"));
}
else
{
nfd::ControlParameters parameters;
parameters
.setName(m_prefix)
.setStrategy(m_forwardingStrategy);
m_controller->start<nfd::StrategyChoiceSetCommand>(parameters,
bind(&Consumer::onStrategyChangeSuccess, this, _1,
"Successfully set strategy choice"),
bind(&Consumer::onStrategyChangeError, this, _1, _2,
"Failed to set strategy choice"));
}
return OPTION_VALUE_SET;
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, ConsumerDataCallback optionValue)
{
switch (optionName)
{
case DATA_ENTER_CNTX:
m_onDataEnteredContext = optionValue;;
return OPTION_VALUE_SET;
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, ProducerDataCallback optionValue)
{
return OPTION_VALUE_NOT_SET;
}
int
Consumer::setContextOption(int optionName, ConsumerDataVerificationCallback optionValue)
{
switch (optionName)
{
case DATA_TO_VERIFY:
m_onDataToVerify = optionValue;
return OPTION_VALUE_SET;
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, ConsumerInterestCallback optionValue)
{
switch (optionName)
{
case INTEREST_RETRANSMIT:
m_onInterestRetransmitted = optionValue;
return OPTION_VALUE_SET;
case INTEREST_LEAVE_CNTX:
m_onInterestToLeaveContext = optionValue;
return OPTION_VALUE_SET;
case INTEREST_EXPIRED:
m_onInterestExpired = optionValue;
return OPTION_VALUE_SET;
case INTEREST_SATISFIED:
m_onInterestSatisfied = optionValue;
return OPTION_VALUE_SET;
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, ProducerInterestCallback optionValue)
{
return OPTION_VALUE_NOT_SET;
}
int
Consumer::setContextOption(int optionName, ConsumerContentCallback optionValue)
{
switch (optionName)
{
case CONTENT_RETRIEVED:
m_onPayloadReassembled = optionValue;
return OPTION_VALUE_SET;
default: return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, ConsumerNackCallback optionValue)
{
switch (optionName)
{
case NACK_ENTER_CNTX:
m_onNack = optionValue;
return OPTION_VALUE_SET;
default: return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, ConsumerManifestCallback optionValue)
{
switch (optionName)
{
case MANIFEST_ENTER_CNTX:
m_onManifest = optionValue;
return OPTION_VALUE_SET;
default: return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, KeyLocator optionValue)
{
return OPTION_VALUE_NOT_SET;
}
int
Consumer::setContextOption(int optionName, Exclude optionValue)
{
switch (optionName)
{
case EXCLUDE_S:
m_exclude = optionValue;
return OPTION_VALUE_SET;
default: return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::getContextOption(int optionName, int& optionValue)
{
switch (optionName)
{
case MIN_WINDOW_SIZE:
optionValue = m_minWindowSize;
return OPTION_FOUND;
case MAX_WINDOW_SIZE:
optionValue = m_maxWindowSize;
return OPTION_FOUND;
case MAX_EXCLUDED_DIGESTS:
optionValue = m_nMaxExcludedDigests;
return OPTION_FOUND;
case CURRENT_WINDOW_SIZE:
optionValue = m_currentWindowSize;
return OPTION_FOUND;
case RCV_BUF_SIZE:
optionValue = m_receiveBufferSize;
return OPTION_FOUND;
case SND_BUF_SIZE:
optionValue = m_sendBufferSize;
return OPTION_FOUND;
case INTEREST_RETX:
optionValue = m_nMaxRetransmissions;
return OPTION_FOUND;
case INTEREST_LIFETIME:
optionValue = m_interestLifetimeMillisec;
return OPTION_FOUND;
case MIN_SUFFIX_COMP_S:
optionValue = m_minSuffixComponents;
return OPTION_FOUND;
case MAX_SUFFIX_COMP_S:
optionValue = m_maxSuffixComponents;
return OPTION_FOUND;
case RIGHTMOST_CHILD_S:
optionValue = m_childSelector;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, size_t& optionValue)
{
switch (optionName)
{
case RCV_BUF_SIZE:
optionValue = m_receiveBufferSize;
return OPTION_FOUND;
case SND_BUF_SIZE:
optionValue = m_sendBufferSize;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, bool& optionValue)
{
switch (optionName)
{
case MUST_BE_FRESH_S:
optionValue = m_mustBeFresh;
return OPTION_FOUND;
case ASYNC_MODE:
optionValue = m_isAsync;
return OPTION_FOUND;
case RUNNING:
optionValue = m_isRunning;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, Name& optionValue)
{
switch (optionName)
{
case PREFIX:
optionValue = m_prefix;
return OPTION_FOUND;
case SUFFIX:
optionValue = m_suffix;
return OPTION_FOUND;
case FORWARDING_STRATEGY:
optionValue = m_forwardingStrategy;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, ConsumerDataCallback& optionValue)
{
switch (optionName)
{
case DATA_ENTER_CNTX:
optionValue = m_onDataEnteredContext;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, ProducerDataCallback& optionValue)
{
return OPTION_NOT_FOUND;
}
int
Consumer::getContextOption(int optionName, ConsumerDataVerificationCallback& optionValue)
{
switch (optionName)
{
case DATA_TO_VERIFY:
optionValue = m_onDataToVerify;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, ConsumerInterestCallback& optionValue)
{
switch (optionName)
{
case INTEREST_RETRANSMIT:
optionValue = m_onInterestRetransmitted;
return OPTION_FOUND;
case INTEREST_LEAVE_CNTX:
optionValue = m_onInterestToLeaveContext;
return OPTION_FOUND;
case INTEREST_EXPIRED:
optionValue = m_onInterestExpired;
return OPTION_FOUND;
case INTEREST_SATISFIED:
optionValue = m_onInterestSatisfied;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, ProducerInterestCallback& optionValue)
{
return OPTION_NOT_FOUND;
}
int
Consumer::getContextOption(int optionName, ConsumerContentCallback& optionValue)
{
switch (optionName)
{
case CONTENT_RETRIEVED:
optionValue = m_onPayloadReassembled;
return OPTION_FOUND;
default: return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, ConsumerNackCallback& optionValue)
{
switch (optionName)
{
case NACK_ENTER_CNTX:
optionValue = m_onNack;
return OPTION_FOUND;
default: return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, ConsumerManifestCallback& optionValue)
{
switch (optionName)
{
case MANIFEST_ENTER_CNTX:
optionValue = m_onManifest;
return OPTION_FOUND;
default: return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, KeyLocator& optionValue)
{
switch (optionName)
{
case KEYLOCATOR_S:
optionValue = m_publisherKeyLocator;
return OPTION_FOUND;
default: return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, Exclude& optionValue)
{
switch (optionName)
{
case EXCLUDE_S:
optionValue = m_exclude;
return OPTION_FOUND;
default: return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, shared_ptr<Face>& optionValue)
{
switch (optionName)
{
case FACE:
optionValue = m_face;
return OPTION_FOUND;
default: return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, TreeNode& optionValue)
{
return OPTION_NOT_FOUND;
}
void
Consumer::onStrategyChangeSuccess(const nfd::ControlParameters& commandSuccessResult,
const std::string& message)
{
//std::cout << message << ": " << commandSuccessResult << std::endl;
}
void
Consumer::onStrategyChangeError(uint32_t code, const std::string& error, const std::string& message)
{
/*std::ostringstream os;
os << message << ": " << error << " (code: " << code << ")";
throw Error(os.str());*/
}
void
Consumer::consumeAll()
{
shared_ptr<Face> face = FaceHelper::getFace();
face->processEvents();
}
} //namespace ndn
| 18,660 | 21.840881 | 101 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/cs.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef NFD_TABLE_CS_HPP
#define NFD_TABLE_CS_HPP
#include "common.hpp"
#include "cs-entry.hpp"
#include <boost/multi_index/member.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/thread/mutex.hpp>
#include <queue>
namespace ndn {
typedef std::list<cs::Entry*> SkipListLayer;
typedef std::list<SkipListLayer*> SkipList;
class StalenessComparator
{
public:
bool
operator()(const cs::Entry* entry1, const cs::Entry* entry2) const
{
return entry1->getStaleTime() < entry2->getStaleTime();
}
};
class UnsolicitedComparator
{
public:
bool
operator()(const cs::Entry* entry1, const cs::Entry* entry2) const
{
return entry1->isUnsolicited();
}
};
// tags
class unsolicited;
class byStaleness;
class byArrival;
typedef boost::multi_index_container<
cs::Entry*,
boost::multi_index::indexed_by<
// by arrival (FIFO)
boost::multi_index::sequenced<
boost::multi_index::tag<byArrival>
>
>
> CleanupIndex;
/** \brief represents Content Store
*/
class Cs : noncopyable
{
public:
explicit
Cs(int nMaxPackets = 65536); // ~500MB with average packet size = 8KB
~Cs();
/** \brief inserts a Data packet
* This method does not consider the payload of the Data packet.
*
* Packets are considered duplicate if the name matches.
* The new Data packet with the identical name, but a different payload
* is not placed in the Content Store
* \return{ whether the Data is added }
*/
bool
insert(const Data& data, bool isUnsolicited = false);
/** \brief finds the best match Data for an Interest
* \return{ the best match, if any; otherwise 0 }
*/
const Data*
find(const Interest& interest);
/** \brief deletes CS entry by the exact name
*/
void
erase(const Name& exactName);
/** \brief sets maximum allowed size of Content Store (in packets)
*/
void
setLimit(size_t nMaxPackets);
/** \brief returns maximum allowed size of Content Store (in packets)
* \return{ number of packets that can be stored in Content Store }
*/
size_t
getLimit() const;
/** \brief returns current size of Content Store measured in packets
* \return{ number of packets located in Content Store }
*/
size_t
size() const;
protected:
/** \brief removes one Data packet from Content Store based on replacement policy
* \return{ whether the Data was removed }
*/
bool
evictItem();
private:
/** \brief returns True if the Content Store is at its maximum capacity
* \return{ True if Content Store is full; otherwise False}
*/
bool
isFull() const;
/** \brief Computes the layer where new Content Store Entry is placed
*
* Reference: "Skip Lists: A Probabilistic Alternative to Balanced Trees" by W.Pugh
* \return{ returns random layer (number) in a skip list}
*/
size_t
pickRandomLayer() const;
/** \brief Inserts a new Content Store Entry in a skip list
* \return{ returns a pair containing a pointer to the CS Entry,
* and a flag indicating if the entry was newly created (True) or refreshed (False) }
*/
std::pair<cs::Entry*, bool>
insertToSkipList(const Data& data, bool isUnsolicited = false);
/** \brief Removes a specific CS Entry from all layers of a skip list
* \return{ returns True if CS Entry was succesfully removed and False if CS Entry was not found}
*/
bool
eraseFromSkipList(cs::Entry* entry);
/** \brief Implements child selector (leftmost, rightmost, undeclared).
* Operates on the first layer of a skip list.
*
* startingPoint must be less than Interest Name.
* startingPoint can be equal to Interest Name only when the item is in the begin() position.
*
* Iterates toward greater Names, terminates when CS entry falls out of Interest prefix.
* When childSelector = leftmost, returns first CS entry that satisfies other selectors.
* When childSelector = rightmost, it goes till the end, and returns CS entry that satisfies
* other selectors. Returned CS entry is the leftmost child of the rightmost child.
* \return{ the best match, if any; otherwise 0 }
*/
const Data*
selectChild(const Interest& interest, SkipListLayer::iterator startingPoint) const;
/** \brief checks if Content Store entry satisfies Interest selectors (MinSuffixComponents,
* MaxSuffixComponents, Implicit Digest, MustBeFresh)
* \return{ true if satisfies all selectors; false otherwise }
*/
bool
doesComplyWithSelectors(const Interest& interest,
cs::Entry* entry,
bool doesInterestContainDigest) const;
/** \brief interprets minSuffixComponent and name lengths to understand if Interest contains
* implicit digest of the data
* \return{ True if Interest name contains digest; False otherwise }
*/
bool
recognizeInterestWithDigest(const Interest& interest, cs::Entry* entry) const;
/** \brief Prints contents of the skip list, starting from the top layer
*/
void
printSkipList() const;
private:
SkipList m_skipList;
CleanupIndex m_cleanupIndex;
size_t m_nMaxPackets; // user defined maximum size of the Content Store in packets
size_t m_nPackets; // current number of packets in Content Store
std::queue<cs::Entry*> m_freeCsEntries; // memory pool
boost::mutex m_mutex;
};
} // namespace nfd
#endif // NFD_TABLE_CS_HPP
| 6,579 | 30.333333 | 100 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/infomax-data-retrieval.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef INFOMAX_DATA_RETRIEVAL_HPP
#define INFOMAX_DATA_RETRIEVAL_HPP
#include "reliable-data-retrieval.hpp"
namespace ndn {
class InfoMaxDataRetrieval : public DataRetrievalProtocol
{
public:
InfoMaxDataRetrieval(Context* context);
~InfoMaxDataRetrieval();
void
start();
void
stop();
private:
void
processInfoMaxPayload(Consumer&, const uint8_t*, size_t);
void
processInfoMaxData(Consumer&, const Data&);
void
processLeavingInfoMaxInterest(Consumer&, Interest&);
void
processInfoMaxInitPayload(Consumer&, const uint8_t*, size_t);
void
processInfoMaxInitData(Consumer&, const Data&);
void
processLeavingInfoMaxInitInterest(Consumer&, Interest&);
void
convertStringToList(std::string&);
private:
std::list< shared_ptr<Name> > m_infoMaxList;
shared_ptr<ReliableDataRetrieval> m_rdr;
uint64_t m_requestVersion;
uint64_t m_requestListNum;
uint64_t m_maxListNum;
bool m_isInit;
};
} // namespace ndn
#endif // INFOMAX_DATA_RETRIEVAL_HPP
| 2,073 | 26.653333 | 99 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/face-helper.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef FACE_HELPER_HPP
#define FACE_HELPER_HPP
#include "common.hpp"
namespace ndn {
class FaceHelper
{
public:
static shared_ptr<Face> getFace();
private:
FaceHelper(){};
FaceHelper(const FaceHelper& helper){}; // copy constructor is private
FaceHelper& operator=(const FaceHelper& helper){return *this;}; // assignment operator is private
static shared_ptr<Face> m_face;
};
} // namespace ndn
#endif // FACE_HELPER_HPP
| 1,506 | 33.25 | 99 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/selector-helper.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef SELECTOR_HELPER_HPP
#define SELECTOR_HELPER_HPP
#include "common.hpp"
#include "context.hpp"
#include "context-options.hpp"
#include "context-default-values.hpp"
namespace ndn {
class SelectorHelper
{
public:
static void
applySelectors(Interest& interest, Context* m_context);
};
} //namespace ndn
#endif // SELECTOR_HELPER_HPP
| 1,416 | 31.204545 | 99 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/reliable-data-retrieval.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "reliable-data-retrieval.hpp"
#include "consumer-context.hpp"
namespace ndn {
ReliableDataRetrieval::ReliableDataRetrieval(Context* context)
: DataRetrievalProtocol(context)
, m_isFinalBlockNumberDiscovered(false)
, m_finalBlockNumber(std::numeric_limits<uint64_t>::max())
, m_lastReassembledSegment(0)
, m_contentBufferSize(0)
, m_currentWindowSize(0)
, m_interestsInFlight(0)
, m_segNumber(0)
{
context->getContextOption(FACE, m_face);
m_scheduler = new Scheduler(m_face->getIoService());
}
ReliableDataRetrieval::~ReliableDataRetrieval()
{
stop();
delete m_scheduler;
}
void
ReliableDataRetrieval::start()
{
m_isRunning = true;
m_isFinalBlockNumberDiscovered = false;
m_finalBlockNumber = std::numeric_limits<uint64_t>::max();
m_segNumber = 0;
m_interestsInFlight = 0;
m_lastReassembledSegment = 0;
m_contentBufferSize = 0;
m_contentBuffer.clear();
m_interestRetransmissions.clear();
m_receiveBuffer.clear();
m_unverifiedSegments.clear();
m_verifiedManifests.clear();
// this is to support window size "inheritance" between consume calls
/*int currentWindowSize = -1;
m_context->getContextOption(CURRENT_WINDOW_SIZE, currentWindowSize);
if (currentWindowSize > 0)
{
m_currentWindowSize = currentWindowSize;
}
else*/
/*{
int minWindowSize = -1;
m_context->getContextOption(MIN_WINDOW_SIZE, minWindowSize);
m_currentWindowSize = minWindowSize;
}*/
// initial burst of Interest packets
/*while (m_interestsInFlight < m_currentWindowSize)
{
if (m_isFinalBlockNumberDiscovered)
{
if (m_segNumber <= m_finalBlockNumber)
{
sendInterest();
}
else
{
break;
}
}
else
{
sendInterest();
}
}*/
//send exactly 1 Interest to get the FinalBlockId
sendInterest();
bool isAsync = false;
m_context->getContextOption(ASYNC_MODE, isAsync);
bool isContextRunning = false;
m_context->getContextOption(RUNNING, isContextRunning);
if (!isAsync && !isContextRunning)
{
m_context->setContextOption(RUNNING, true);
m_face->processEvents();
}
}
void
ReliableDataRetrieval::sendInterest()
{
Name prefix;
m_context->getContextOption(PREFIX, prefix);
Name suffix;
m_context->getContextOption(SUFFIX, suffix);
if (!suffix.empty())
{
prefix.append(suffix);
}
prefix.appendSegment(m_segNumber);
Interest interest(prefix);
int interestLifetime = DEFAULT_INTEREST_LIFETIME;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
interest.setInterestLifetime(time::milliseconds(interestLifetime));
SelectorHelper::applySelectors(interest, m_context);
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), interest);
}
// because user could stop the context in one of the prev callbacks
//if (m_isRunning == false)
// return;
m_interestsInFlight++;
m_interestRetransmissions[m_segNumber] = 0;
m_interestTimepoints[m_segNumber] = time::steady_clock::now();
m_expressedInterests[m_segNumber] = m_face->expressInterest(interest,
bind(&ReliableDataRetrieval::onData, this, _1, _2),
bind(&ReliableDataRetrieval::onTimeout, this, _1));
m_segNumber++;
}
void
ReliableDataRetrieval::stop()
{
m_isRunning = false;
removeAllPendingInterests();
removeAllScheduledInterests();
}
void
ReliableDataRetrieval::onData(const ndn::Interest& interest, ndn::Data& data)
{
if (m_isRunning == false)
return;
m_interestsInFlight--;
uint64_t segment = interest.getName().get(-1).toSegment();
m_expressedInterests.erase(segment);
m_scheduledInterests.erase(segment);
if (m_interestTimepoints.find(segment) != m_interestTimepoints.end())
{
time::steady_clock::duration duration = time::steady_clock::now() - m_interestTimepoints[segment];
m_rttEstimator.addMeasurement(boost::chrono::duration_cast<boost::chrono::microseconds>(duration));
RttEstimator::Duration rto = m_rttEstimator.computeRto();
boost::chrono::milliseconds lifetime = boost::chrono::duration_cast<boost::chrono::milliseconds>(rto);
int interestLifetime = DEFAULT_INTEREST_LIFETIME;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
// update lifetime only if user didn't specify prefered value
if (interestLifetime == DEFAULT_INTEREST_LIFETIME)
{
m_context->setContextOption(INTEREST_LIFETIME, (int)lifetime.count());
}
}
ConsumerDataCallback onDataEnteredContext = EMPTY_CALLBACK;
m_context->getContextOption(DATA_ENTER_CNTX, onDataEnteredContext);
if (onDataEnteredContext != EMPTY_CALLBACK)
{
onDataEnteredContext(*dynamic_cast<Consumer*>(m_context), data);
}
ConsumerInterestCallback onInterestSatisfied = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_SATISFIED, onInterestSatisfied);
if (onInterestSatisfied != EMPTY_CALLBACK)
{
onInterestSatisfied(*dynamic_cast<Consumer*>(m_context), const_cast<Interest&>(interest));
}
if (data.getContentType() == MANIFEST_DATA_TYPE)
{
onManifestData(interest, data);
}
else if (data.getContentType() == NACK_DATA_TYPE)
{
onNackData(interest, data);
}
else if (data.getContentType() == CONTENT_DATA_TYPE)
{
onContentData(interest, data);
}
if (segment == 0) // if it was the first Interest
{
// in a next round try to transmit all Interests, except the first one
m_currentWindowSize = m_finalBlockNumber;
int maxWindowSize = -1;
m_context->getContextOption(MAX_WINDOW_SIZE, maxWindowSize);
// if there are too many Interests to send, put an upper boundary on it.
if (m_currentWindowSize > maxWindowSize)
{
m_currentWindowSize = maxWindowSize;
}
//int rtt = -1;
//m_context->getContextOption(INTEREST_LIFETIME, rtt);
//paceInterests(m_currentWindowSize, time::milliseconds(10));
while (m_interestsInFlight < m_currentWindowSize)
{
if (m_isFinalBlockNumberDiscovered)
{
if (m_segNumber <= m_finalBlockNumber)
{
sendInterest();
}
else
{
break;
}
}
else
{
sendInterest();
}
}
}
else
{
if (m_isRunning)
{
while (m_interestsInFlight < m_currentWindowSize)
{
if (m_isFinalBlockNumberDiscovered)
{
if (m_segNumber <= m_finalBlockNumber)
{
sendInterest();
}
else
{
break;
}
}
else
{
sendInterest();
}
}
}
}
}
void
ReliableDataRetrieval::paceInterests(int nInterests, time::milliseconds timeWindow)
{
if (nInterests <= 0)
return;
time::nanoseconds interval = time::nanoseconds(1000000*timeWindow) / nInterests;
for (int i = 1; i <= nInterests; i++)
{
// schedule next Interest
m_scheduledInterests[m_segNumber + i] = m_scheduler->scheduleEvent(i*interval,
bind(&ReliableDataRetrieval::sendInterest, this));
}
}
void
ReliableDataRetrieval::onManifestData(const ndn::Interest& interest, ndn::Data& data)
{
if (m_isRunning == false)
return;
//std::cout << "OnManifest" << std::endl;
ConsumerDataVerificationCallback onDataToVerify = EMPTY_CALLBACK;
m_context->getContextOption(DATA_TO_VERIFY, onDataToVerify);
bool isDataSecure = false;
if (onDataToVerify == EMPTY_CALLBACK)
{
// perform integrity check if possible
if (data.getSignature().getType() == tlv::DigestSha256)
{
ndn::name::Component claimedDigest( data.getSignature().getValue().value(),
data.getSignature().getValue().value_size());
// recalculate digest
m_keyChain.signWithSha256(data);
ndn::name::Component actualDigest(data.getSignature().getValue().value(),
data.getSignature().getValue().value_size());
if (!claimedDigest.equals(actualDigest))
{
isDataSecure = false;
}
}
else
{
isDataSecure = true;
}
}
else
{
if (onDataToVerify(*dynamic_cast<Consumer*>(m_context), data) == true) // runs verification routine
{
isDataSecure = true;
}
}
if (isDataSecure)
{
checkFastRetransmissionConditions(interest);
int maxWindowSize = -1;
m_context->getContextOption(MAX_WINDOW_SIZE, maxWindowSize);
if (m_currentWindowSize < maxWindowSize) // don't expand window above max level
{
m_currentWindowSize++;
m_context->setContextOption(CURRENT_WINDOW_SIZE, m_currentWindowSize);
}
shared_ptr<Manifest> manifest = make_shared<Manifest>(data);
//std::cout << "MANIFEST CONTAINS " << manifest->size() << " names" << std::endl;
m_verifiedManifests.insert(std::pair<uint64_t, shared_ptr<Manifest> >(
data.getName().get(-1).toSegment(),
manifest));
m_receiveBuffer[manifest->getName().get(-1).toSegment()] = manifest;
// TODO: names in manifest are in order, so we can exit the loop earlier
for(std::map<uint64_t, shared_ptr<Data> >::iterator it = m_unverifiedSegments.begin();
it != m_unverifiedSegments.end(); ++it)
{
if (!m_isRunning)
{
return;
}
// data segment is verified with manifest
if (verifySegmentWithManifest(*manifest, *(it->second)))
{
if (!it->second->getFinalBlockId().empty())
{
m_isFinalBlockNumberDiscovered = true;
m_finalBlockNumber = it->second->getFinalBlockId().toSegment();
}
m_receiveBuffer[it->second->getName().get(-1).toSegment()] = it->second;
reassemble();
}
else // data segment failed verification with manifest
{
// retransmit interest with implicit digest from the manifest
retransmitInterestWithDigest(interest, data, *manifest);
}
}
}
else // failed to verify manifest
{
retransmitInterestWithExclude(interest,data);
}
}
void
ReliableDataRetrieval::retransmitFreshInterest(const ndn::Interest& interest)
{
int maxRetransmissions;
m_context->getContextOption(INTEREST_RETX, maxRetransmissions);
uint64_t segment = interest.getName().get(-1).toSegment();
if(m_interestRetransmissions[segment] < maxRetransmissions)
{
if (m_isRunning)
{
Interest retxInterest(interest.getName()); // because we need new nonce
int interestLifetime = DEFAULT_INTEREST_LIFETIME;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
retxInterest.setInterestLifetime(time::milliseconds(interestLifetime));
SelectorHelper::applySelectors(retxInterest, m_context);
retxInterest.setMustBeFresh(true); // to bypass cache
// this is to inherit the exclusions from the nacked interest
Exclude exclusion = retxInterest.getExclude();
for(Exclude::exclude_type::const_iterator it = interest.getExclude().begin();
it != interest.getExclude().end(); ++it)
{
exclusion.appendExclude(it->first, false);
}
retxInterest.setExclude(exclusion);
ConsumerInterestCallback onInterestRetransmitted = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_RETRANSMIT, onInterestRetransmitted);
if (onInterestRetransmitted != EMPTY_CALLBACK)
{
onInterestRetransmitted(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
// because user could stop the context in one of the prev callbacks
if (m_isRunning == false)
return;
m_interestsInFlight++;
m_interestRetransmissions[segment]++;
m_expressedInterests[segment] = m_face->expressInterest(retxInterest,
bind(&ReliableDataRetrieval::onData, this, _1, _2),
bind(&ReliableDataRetrieval::onTimeout, this, _1));
}
}
else
{
m_isRunning = false;
}
}
bool
ReliableDataRetrieval::retransmitInterestWithExclude( const ndn::Interest& interest,
Data& dataSegment)
{
int maxRetransmissions;
m_context->getContextOption(INTEREST_RETX, maxRetransmissions);
uint64_t segment = interest.getName().get(-1).toSegment();
m_unverifiedSegments.erase(segment); // remove segment, because it is useless
if(m_interestRetransmissions[segment] < maxRetransmissions)
{
Interest interestWithExlusion(interest.getName());
int interestLifetime = DEFAULT_INTEREST_LIFETIME;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
interestWithExlusion.setInterestLifetime(time::milliseconds(interestLifetime));
SelectorHelper::applySelectors(interestWithExlusion, m_context);
int nMaxExcludedDigests = 0;
m_context->getContextOption(MAX_EXCLUDED_DIGESTS, nMaxExcludedDigests);
if (interest.getExclude().size() < nMaxExcludedDigests)
{
const Block& block = dataSegment.wireEncode();
ndn::ConstBufferPtr implicitDigestBuffer = ndn::crypto::sha256(block.wire(), block.size());
name::Component implicitDigest = name::Component::fromImplicitSha256Digest(implicitDigestBuffer);
Exclude exclusion = interest.getExclude();
exclusion.appendExclude(implicitDigest, false);
interestWithExlusion.setExclude(exclusion);
}
else
{
m_isRunning = false;
return false;
}
ConsumerInterestCallback onInterestRetransmitted = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_RETRANSMIT, onInterestRetransmitted);
if (onInterestRetransmitted != EMPTY_CALLBACK)
{
onInterestRetransmitted(*dynamic_cast<Consumer*>(m_context), interestWithExlusion);
}
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), interestWithExlusion);
}
// because user could stop the context in one of the prev callbacks
if (m_isRunning == false)
return false;
//retransmit
m_interestsInFlight++;
m_interestRetransmissions[segment]++;
m_expressedInterests[segment] = m_face->expressInterest(interestWithExlusion,
bind(&ReliableDataRetrieval::onData, this, _1, _2),
bind(&ReliableDataRetrieval::onTimeout, this, _1));
}
else
{
m_isRunning = false;
return false;
}
return true;
}
bool
ReliableDataRetrieval::retransmitInterestWithDigest(const ndn::Interest& interest,
const Data& dataSegment,
Manifest& manifestSegment)
{
int maxRetransmissions;
m_context->getContextOption(INTEREST_RETX, maxRetransmissions);
uint64_t segment = interest.getName().get(-1).toSegment();
m_unverifiedSegments.erase(segment); // remove segment, because it is useless
if(m_interestRetransmissions[segment] < maxRetransmissions)
{
name::Component implicitDigest = getDigestFromManifest(manifestSegment, dataSegment);
if (implicitDigest.empty())
{
m_isRunning = false;
return false;
}
Name nameWithDigest(interest.getName());
nameWithDigest.append(implicitDigest);
Interest interestWithDigest(nameWithDigest);
int interestLifetime = DEFAULT_INTEREST_LIFETIME;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
interestWithDigest.setInterestLifetime(time::milliseconds(interestLifetime));
SelectorHelper::applySelectors(interestWithDigest, m_context);
ConsumerInterestCallback onInterestRetransmitted = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_RETRANSMIT, onInterestRetransmitted);
if (onInterestRetransmitted != EMPTY_CALLBACK)
{
onInterestRetransmitted(*dynamic_cast<Consumer*>(m_context), interestWithDigest);
}
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), interestWithDigest);
}
// because user could stop the context in one of the prev callbacks
if (m_isRunning == false)
return false;
//retransmit
m_interestsInFlight++;
m_interestRetransmissions[segment]++;
m_expressedInterests[segment] = m_face->expressInterest(interestWithDigest,
bind(&ReliableDataRetrieval::onData, this, _1, _2),
bind(&ReliableDataRetrieval::onTimeout, this, _1));
}
else
{
m_isRunning = false;
return false;
}
return true;
}
void
ReliableDataRetrieval::onNackData(const ndn::Interest& interest, ndn::Data& data)
{
if (m_isRunning == false)
return;
if (m_isFinalBlockNumberDiscovered)
{
if (data.getName().get(-3).toSegment() > m_finalBlockNumber)
{
return;
}
}
ConsumerDataVerificationCallback onDataToVerify = EMPTY_CALLBACK;
m_context->getContextOption(DATA_TO_VERIFY, onDataToVerify);
bool isDataSecure = false;
if (onDataToVerify == EMPTY_CALLBACK)
{
// perform integrity check if possible
if (data.getSignature().getType() == tlv::DigestSha256)
{
ndn::name::Component claimedDigest( data.getSignature().getValue().value(),
data.getSignature().getValue().value_size());
// recalculate digest
m_keyChain.signWithSha256(data);
ndn::name::Component actualDigest(data.getSignature().getValue().value(),
data.getSignature().getValue().value_size());
if (claimedDigest.equals(actualDigest))
{
isDataSecure = true;
}
else
{
isDataSecure = false;
}
}
else
{
isDataSecure = true;
}
}
else
{
if (onDataToVerify(*dynamic_cast<Consumer*>(m_context), data) == true) // runs verification routine
{
isDataSecure = true;
}
}
if (isDataSecure)
{
checkFastRetransmissionConditions(interest);
int minWindowSize = -1;
m_context->getContextOption(MIN_WINDOW_SIZE, minWindowSize);
if (m_currentWindowSize > minWindowSize) // don't shrink window below minimum level
{
m_currentWindowSize = m_currentWindowSize / 2; // cut in half
if (m_currentWindowSize == 0)
m_currentWindowSize++;
m_context->setContextOption(CURRENT_WINDOW_SIZE, m_currentWindowSize);
}
shared_ptr<ApplicationNack> nack = make_shared<ApplicationNack>(data);
ConsumerNackCallback onNack = EMPTY_CALLBACK;
m_context->getContextOption(NACK_ENTER_CNTX, onNack);
if (onNack != EMPTY_CALLBACK)
{
onNack(*dynamic_cast<Consumer*>(m_context), *nack);
}
switch (nack->getCode())
{
case ApplicationNack::DATA_NOT_AVAILABLE:
{
m_isRunning = false;
break;
}
case ApplicationNack::NONE:
{
// TODO: reduce window size ?
break;
}
case ApplicationNack::PRODUCER_DELAY:
{
uint64_t segment = interest.getName().get(-1).toSegment();
m_scheduledInterests[segment] = m_scheduler->scheduleEvent(time::milliseconds(nack->getDelay()),
bind(&ReliableDataRetrieval::retransmitFreshInterest, this, interest));
break;
}
default: break;
}
}
else // if NACK is not verified
{
retransmitInterestWithExclude(interest, data);
}
}
void
ReliableDataRetrieval::onContentData(const ndn::Interest& interest, ndn::Data& data)
{
ConsumerDataVerificationCallback onDataToVerify = EMPTY_CALLBACK;
m_context->getContextOption(DATA_TO_VERIFY, onDataToVerify);
bool isDataSecure = false;
if (onDataToVerify == EMPTY_CALLBACK)
{
// perform integrity check if possible
if (data.getSignature().getType() == tlv::DigestSha256)
{
ndn::name::Component claimedDigest( data.getSignature().getValue().value(),
data.getSignature().getValue().value_size());
// recalculate digest
m_keyChain.signWithSha256(data);
ndn::name::Component actualDigest(data.getSignature().getValue().value(),
data.getSignature().getValue().value_size());
if (claimedDigest.equals(actualDigest))
{
isDataSecure = true;
}
else
{
isDataSecure = false;
retransmitInterestWithExclude(interest, data);
}
}
else
{
isDataSecure = true;
}
}
else
{
if (!data.getSignature().hasKeyLocator())
{
retransmitInterestWithExclude(interest, data);
return;
}
// if data segment points to inlined manifest
if (referencesManifest(data))
{
Name referencedManifestName = data.getSignature().getKeyLocator().getName();
uint64_t manifestSegmentNumber = referencedManifestName.get(-1).toSegment();
if (m_verifiedManifests.find(manifestSegmentNumber) == m_verifiedManifests.end())
{
// save segment for some time, because manifest can be out of order
//std::cout << "SAVING SEGMENT for MANIFEST" << std::endl;
m_unverifiedSegments.insert(
std::pair<uint64_t, shared_ptr<Data> >( data.getName().get(-1).toSegment(),
data.shared_from_this()));
}
else
{
//std::cout << "NEAREST M " << m_verifiedManifests[manifestSegmentNumber]->getName() << std::endl;
isDataSecure = verifySegmentWithManifest(*(m_verifiedManifests[manifestSegmentNumber]), data);
if (!isDataSecure)
{
//std::cout << "Retx Digest" << std::endl;
retransmitInterestWithDigest( interest, data,
*m_verifiedManifests.find(manifestSegmentNumber)->second);
}
}
}
else // data segment points to the key
{
if (onDataToVerify(*dynamic_cast<Consumer*>(m_context), data) == true) // runs verification routine
{
isDataSecure = true;
}
else
{
retransmitInterestWithExclude(interest, data);
}
}
}
if (isDataSecure)
{
checkFastRetransmissionConditions(interest);
int maxWindowSize = -1;
m_context->getContextOption(MAX_WINDOW_SIZE, maxWindowSize);
if (m_currentWindowSize < maxWindowSize) // don't expand window above max level
{
m_currentWindowSize++;
m_context->setContextOption(CURRENT_WINDOW_SIZE, m_currentWindowSize);
}
if (!data.getFinalBlockId().empty())
{
m_isFinalBlockNumberDiscovered = true;
m_finalBlockNumber = data.getFinalBlockId().toSegment();
}
m_receiveBuffer[data.getName().get(-1).toSegment()] = data.shared_from_this();
reassemble();
}
}
bool
ReliableDataRetrieval::referencesManifest(ndn::Data& data)
{
Name keyLocatorPrefix = data.getSignature().getKeyLocator().getName().getPrefix(-1);
Name dataPrefix = data.getName().getPrefix(-1);
if (keyLocatorPrefix.equals(dataPrefix))
{
return true;
}
return false;
}
void
ReliableDataRetrieval::onTimeout(const ndn::Interest& interest)
{
if (m_isRunning == false)
return;
m_interestsInFlight--;
ConsumerInterestCallback onInterestExpired = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_EXPIRED, onInterestExpired);
if (onInterestExpired != EMPTY_CALLBACK)
{
onInterestExpired(*dynamic_cast<Consumer*>(m_context), const_cast<Interest&>(interest));
}
uint64_t segment = interest.getName().get(-1).toSegment();
m_expressedInterests.erase(segment);
m_scheduledInterests.erase(segment);
if (m_isFinalBlockNumberDiscovered)
{
if (interest.getName().get(-1).toSegment() > m_finalBlockNumber)
return;
}
int minWindowSize = -1;
m_context->getContextOption(MIN_WINDOW_SIZE, minWindowSize);
if (m_currentWindowSize > minWindowSize) // don't shrink window below minimum level
{
m_currentWindowSize = m_currentWindowSize / 2; // cut in half
if (m_currentWindowSize == 0)
m_currentWindowSize++;
m_context->setContextOption(CURRENT_WINDOW_SIZE, m_currentWindowSize);
}
int maxRetransmissions;
m_context->getContextOption(INTEREST_RETX, maxRetransmissions);
if(m_interestRetransmissions[segment] < maxRetransmissions)
{
Interest retxInterest(interest.getName()); // because we need new nonce
int interestLifetime = DEFAULT_INTEREST_LIFETIME;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
retxInterest.setInterestLifetime(time::milliseconds(interestLifetime));
SelectorHelper::applySelectors(retxInterest, m_context);
// this is to inherit the exclusions from the timed out interest
Exclude exclusion = retxInterest.getExclude();
for(Exclude::exclude_type::const_iterator it = interest.getExclude().begin();
it != interest.getExclude().end(); ++it)
{
exclusion.appendExclude(it->first, false);
}
retxInterest.setExclude(exclusion);
ConsumerInterestCallback onInterestRetransmitted = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_RETRANSMIT, onInterestRetransmitted);
if (onInterestRetransmitted != EMPTY_CALLBACK)
{
onInterestRetransmitted(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
// because user could stop the context in one of the prev callbacks
if (m_isRunning == false)
return;
//retransmit
m_interestsInFlight++;
m_interestRetransmissions[segment]++;
m_expressedInterests[segment] = m_face->expressInterest(retxInterest,
bind(&ReliableDataRetrieval::onData, this, _1, _2),
bind(&ReliableDataRetrieval::onTimeout, this, _1));
}
else
{
m_isRunning = false;
reassemble(); // to pass up all content we have so far
}
}
void
ReliableDataRetrieval::copyContent(Data& data)
{
const Block content = data.getContent();
m_contentBuffer.insert(m_contentBuffer.end(), &content.value()[0], &content.value()[content.value_size()]);
if ((data.getName().get(-1).toSegment() == m_finalBlockNumber) || (!m_isRunning))
{
removeAllPendingInterests();
removeAllScheduledInterests();
// return content to the user
ConsumerContentCallback onPayload = EMPTY_CALLBACK;
m_context->getContextOption(CONTENT_RETRIEVED, onPayload);
if (onPayload != EMPTY_CALLBACK)
{
onPayload(*dynamic_cast<Consumer*>(m_context), m_contentBuffer.data(), m_contentBuffer.size());
}
//reduce window size to prevent its speculative growth in case when consume() is called in loop
int currentWindowSize = -1;
m_context->getContextOption(CURRENT_WINDOW_SIZE, currentWindowSize);
if (currentWindowSize > m_finalBlockNumber)
{
m_context->setContextOption(CURRENT_WINDOW_SIZE, (int)(m_finalBlockNumber));
}
m_isRunning = false;
}
}
void
ReliableDataRetrieval::reassemble()
{
std::map<uint64_t, shared_ptr<Data> >::iterator head = m_receiveBuffer.find(m_lastReassembledSegment);
while (head != m_receiveBuffer.end())
{
// do not copy from manifests
if (head->second->getContentType() == CONTENT_DATA_TYPE)
{
copyContent(*(head->second));
}
m_receiveBuffer.erase(head);
m_lastReassembledSegment++;
head = m_receiveBuffer.find(m_lastReassembledSegment);
}
}
bool
ReliableDataRetrieval::verifySegmentWithManifest(Manifest& manifestSegment, Data& dataSegment)
{
//std::cout << "Verify Segment With MAnifest" << std::endl;
bool result = false;
for (std::list<Name>::const_iterator it = manifestSegment.catalogueBegin();
it != manifestSegment.catalogueEnd(); ++it)
{
if (it->get(-2) == dataSegment.getName().get(-1)) // if segment numbers match
{
//re-calculate implicit digest
const Block& block = dataSegment.wireEncode();
ndn::ConstBufferPtr implicitDigest = ndn::crypto::sha256(block.wire(), block.size());
// convert to name component for easier comparison
name::Component digestComp = name::Component::fromImplicitSha256Digest(implicitDigest);
if (digestComp.equals(it->get(-1)))
{
result = true;
break;
}
else
{
break;
}
}
}
//if (!result)
// std::cout << "Segment failed verification by manifest" << result<< std::endl;
return result;
}
name::Component
ReliableDataRetrieval::getDigestFromManifest(Manifest& manifestSegment, const Data& dataSegment)
{
name::Component result;
for (std::list<Name>::const_iterator it = manifestSegment.catalogueBegin();
it != manifestSegment.catalogueEnd(); ++it)
{
if (it->get(-2) == dataSegment.getName().get(-1)) // if segment numbers match
{
result = it->get(-1);
return result;
}
}
return result;
}
void
ReliableDataRetrieval::checkFastRetransmissionConditions(const ndn::Interest& interest)
{
uint64_t segNumber = interest.getName().get(-1).toSegment();
m_receivedSegments[segNumber] = true;
m_fastRetxSegments.erase(segNumber);
uint64_t possiblyLostSegment = 0;
uint64_t highestReceivedSegment = m_receivedSegments.rbegin()->first;
for (uint64_t i = 0; i <= highestReceivedSegment; i++)
{
if (m_receivedSegments.find(i) == m_receivedSegments.end()) // segment is not received yet
{
// segment has not been fast retransmitted yet
if (m_fastRetxSegments.find(i) == m_fastRetxSegments.end())
{
possiblyLostSegment = i;
uint8_t nOutOfOrderSegments = 0;
for (uint64_t j = i; j <= highestReceivedSegment; j++)
{
if (m_receivedSegments.find(j) != m_receivedSegments.end())
{
nOutOfOrderSegments++;
if (nOutOfOrderSegments == DEFAULT_FAST_RETX_CONDITION)
{
m_fastRetxSegments[possiblyLostSegment] = true;
fastRetransmit(interest, possiblyLostSegment);
}
}
}
}
}
}
}
void
ReliableDataRetrieval::fastRetransmit(const ndn::Interest& interest, uint64_t segNumber)
{
int maxRetransmissions;
m_context->getContextOption(INTEREST_RETX, maxRetransmissions);
if (m_interestRetransmissions[segNumber] < maxRetransmissions)
{
Name name = interest.getName().getPrefix(-1);
name.appendSegment(segNumber);
Interest retxInterest(name);
SelectorHelper::applySelectors(retxInterest, m_context);
// this is to inherit the exclusions from the lost interest
Exclude exclusion = retxInterest.getExclude();
for(Exclude::exclude_type::const_iterator it = interest.getExclude().begin();
it != interest.getExclude().end(); ++it)
{
exclusion.appendExclude(it->first, false);
}
retxInterest.setExclude(exclusion);
ConsumerInterestCallback onInterestRetransmitted = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_RETRANSMIT, onInterestRetransmitted);
if (onInterestRetransmitted != EMPTY_CALLBACK)
{
onInterestRetransmitted(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
// because user could stop the context in one of the prev callbacks
if (m_isRunning == false)
return;
//retransmit
m_interestsInFlight++;
m_interestRetransmissions[segNumber]++;
//std::cout << "fast retx" << std::endl;
m_expressedInterests[segNumber] = m_face->expressInterest(retxInterest,
bind(&ReliableDataRetrieval::onData, this, _1, _2),
bind(&ReliableDataRetrieval::onTimeout, this, _1));
}
}
void
ReliableDataRetrieval::removeAllPendingInterests()
{
bool isAsync = false;
m_context->getContextOption(ASYNC_MODE, isAsync);
if (!isAsync)
{
// This won't work ---> m_face->getIoService().stop();
m_face->removeAllPendingInterests(); // faster, but destroys everything
}
else // slower, but destroys only necessary Interests
{
for(std::unordered_map<uint64_t, const PendingInterestId*>::iterator it = m_expressedInterests.begin();
it != m_expressedInterests.end(); ++it)
{
m_face->removePendingInterest(it->second);
}
}
m_expressedInterests.clear();
}
void
ReliableDataRetrieval::removeAllScheduledInterests()
{
for(std::unordered_map<uint64_t, EventId>::iterator it = m_scheduledInterests.begin();
it != m_scheduledInterests.end(); ++it)
{
m_scheduler->cancelEvent(it->second);
}
m_scheduledInterests.clear();
}
} //namespace ndn
| 36,331 | 30.429066 | 109 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/application-nack.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef APPLICATION_NACK_HPP
#define APPLICATION_NACK_HPP
#include "common.hpp"
#include <ndn-cxx/encoding/tlv.hpp>
#include "tlv.hpp"
#include <ndn-cxx/util/random.hpp>
namespace ndn {
// NACK Headers
#define STATUS_CODE_H "Status-code"
#define RETRY_AFTER_H "Retry-after"
class ApplicationNack : public Data
{
public:
class Error : public std::runtime_error
{
public:
explicit
Error(const std::string& what)
: std::runtime_error(what)
{
}
};
enum NackCode {
NONE = 0,
PRODUCER_DELAY = 1,
DATA_NOT_AVAILABLE = 2,
INTEREST_NOT_VERIFIED = 3
};
/**
* Default constructor.
*/
ApplicationNack();
/**
* Constructs ApplicationNack from a given Interest packet
*/
ApplicationNack(const Interest& interest, ApplicationNack::NackCode statusCode);
/**
* Constructor performing upcasting from Data to ApplicationNack
*/
ApplicationNack(const Data& data);
~ApplicationNack();
void
addKeyValuePair(const uint8_t* key, size_t keySize, const uint8_t* value, size_t valueSize);
void
addKeyValuePair(std::string key, std::string value);
std::string
getValueByKey(std::string key);
void
eraseValueByKey(std::string key);
void
setCode(ApplicationNack::NackCode statusCode);
ApplicationNack::NackCode
getCode();
void
setDelay(uint32_t milliseconds);
uint32_t
getDelay();
void
encode();
template<bool T>
size_t
wireEncode(EncodingImpl<T>& block) const;
void
decode();
private:
std::map<std::string, std::string> m_keyValuePairs;
};
} //namespace ndn
#endif // APPLICATION_NACK_HPP
| 2,711 | 22.582609 | 99 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/manifest.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "manifest.hpp"
namespace ndn {
Manifest::Manifest()
{
setContentType(tlv::ContentType_Manifest);
}
Manifest::Manifest(const Name& name)
: Data(name)
{
setContentType(tlv::ContentType_Manifest);
}
Manifest::Manifest(const Data& data)
: Data(data)
{
setContentType(tlv::ContentType_Manifest);
decode();
}
Manifest::~Manifest()
{
}
void
Manifest::addKeyValuePair(const uint8_t* key, size_t keySize, const uint8_t* value, size_t valueSize)
{
std::string keyS(reinterpret_cast<const char*>(key), keySize);
std::string valueS(reinterpret_cast<const char*>(value), valueSize);
addKeyValuePair(keyS, valueS);
}
void
Manifest::addKeyValuePair(std::string key, std::string value)
{
m_keyValuePairs[key] = value;
}
std::string
Manifest::getValueByKey(std::string key)
{
std::map<std::string,std::string>::const_iterator it = m_keyValuePairs.find(key);
if (it == m_keyValuePairs.end())
{
return "";
}
else
{
return it->second;
}
}
void
Manifest::eraseValueByKey(std::string key)
{
m_keyValuePairs.erase(m_keyValuePairs.find(key));
}
void
Manifest::addNameToCatalogue(const Name& name)
{
m_catalogueNames.push_back(name);
}
void
Manifest::addNameToCatalogue(const Name& name, const Block& digest)
{
Name fullName(name);
fullName.append(ndn::name::Component::fromImplicitSha256Digest(digest.value(), digest.value_size()));
m_catalogueNames.push_back(fullName);
}
void
Manifest::addNameToCatalogue(const Name& name, const ndn::ConstBufferPtr& digest)
{
Name fullName(name);
fullName.append(ndn::name::Component::fromImplicitSha256Digest(digest));
m_catalogueNames.push_back(fullName);
}
template<bool T>
size_t
Manifest::wireEncode(EncodingImpl<T>& blk) const
{
// Manifest ::= CONTENT-TLV TLV-LENGTH
// Catalogue?
// Name*
// KeyValuePair*
size_t totalLength = 0;
size_t catalogueLength = 0;
for (std::map<std::string, std::string>::const_reverse_iterator it = m_keyValuePairs.rbegin();
it != m_keyValuePairs.rend(); ++it)
{
std::string keyValue = it->first + "=" + it->second;
totalLength += blk.prependByteArray(reinterpret_cast<const uint8_t*>(keyValue.c_str()), keyValue.size());
totalLength += blk.prependVarNumber(keyValue.size());
totalLength += blk.prependVarNumber(tlv::KeyValuePair);
}
for (std::list<Name>::const_reverse_iterator it = m_catalogueNames.rbegin();
it != m_catalogueNames.rend(); ++it)
{
size_t blockSize = prependBlock(blk, it->wireEncode());
totalLength += blockSize;
catalogueLength += blockSize;
}
if (catalogueLength > 0)
{
totalLength += blk.prependVarNumber(catalogueLength);
totalLength += blk.prependVarNumber(tlv::ManifestCatalogue);
}
//totalLength += blk.prependVarNumber(totalLength);
//totalLength += blk.prependVarNumber(tlv::Content);
return totalLength;
}
template size_t
Manifest::wireEncode<true>(EncodingImpl<true>& block) const;
template size_t
Manifest::wireEncode<false>(EncodingImpl<false>& block) const;
void
Manifest::encode()
{
EncodingEstimator estimator;
size_t estimatedSize = wireEncode(estimator);
EncodingBuffer buffer(estimatedSize, 0);
wireEncode(buffer);
setContentType(tlv::ContentType_Manifest);
setContent(const_cast<uint8_t*>(buffer.buf()), buffer.size());
}
void
Manifest::decode()
{
Block content = getContent();
content.parse();
// Manifest ::= CONTENT-TLV TLV-LENGTH
// Catalogue?
// Name*
// KeyValuePair*
for ( Block::element_const_iterator val = content.elements_begin();
val != content.elements_end(); ++val)
{
if (val->type() == tlv::ManifestCatalogue)
{
val->parse();
for ( Block::element_const_iterator catalogueNameElem = val->elements_begin();
catalogueNameElem != val->elements_end(); ++catalogueNameElem)
{
if (catalogueNameElem->type() == tlv::Name)
{
Name name(*catalogueNameElem);
m_catalogueNames.push_back(name);
}
}
}
else if (val->type() == tlv::KeyValuePair)
{
std::string str((char*)val->value(), val->value_size());
size_t index = str.find_first_of('=');
if (index == std::string::npos || index == 0 || (index == str.size() - 1))
continue;
std::string key = str.substr(0, index);
std::string value = str.substr(index + 1, str.size() - index - 1);
addKeyValuePair(key, value);
}
}
}
} // namespace ndn
| 5,728 | 26.81068 | 109 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/selector-helper.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "selector-helper.hpp"
namespace ndn {
void
SelectorHelper::applySelectors(Interest& interest, Context* context)
{
int minSuffix = -1;
context->getContextOption(MIN_SUFFIX_COMP_S, minSuffix);
if (minSuffix >= 0)
{
interest.setMinSuffixComponents(minSuffix);
}
int maxSuffix = -1;
context->getContextOption(MAX_SUFFIX_COMP_S, maxSuffix);
if (maxSuffix >= 0)
{
interest.setMaxSuffixComponents(maxSuffix);
}
Exclude exclusion;
context->getContextOption(EXCLUDE_S, exclusion);
if (!exclusion.empty())
{
interest.setExclude(exclusion);
}
bool mustBeFresh = false;
context->getContextOption(MUST_BE_FRESH_S, mustBeFresh);
if (mustBeFresh)
{
interest.setMustBeFresh(mustBeFresh);
}
int child = -10;
context->getContextOption(RIGHTMOST_CHILD_S, child);
if (child != -10)
{
interest.setChildSelector(child);
}
KeyLocator keyLocator;
context->getContextOption(KEYLOCATOR_S, keyLocator);
if (!keyLocator.empty())
{
interest.setPublisherPublicKeyLocator(keyLocator);
}
}
} //namespace ndn
| 2,174 | 26.1875 | 99 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/cs.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "cs.hpp"
#include <ndn-cxx/util/crypto.hpp>
#include <ndn-cxx/security/signature-sha256-with-rsa.hpp>
#define SKIPLIST_MAX_LAYERS 32
#define SKIPLIST_PROBABILITY 25 // 25% (p = 1/4)
namespace ndn {
Cs::Cs(int nMaxPackets)
: m_nMaxPackets(nMaxPackets)
, m_nPackets(0)
{
SkipListLayer* zeroLayer = new SkipListLayer();
m_skipList.push_back(zeroLayer);
for (size_t i = 0; i < m_nMaxPackets; i++)
m_freeCsEntries.push(new cs::Entry());
}
Cs::~Cs()
{
// evict all items from CS
while (evictItem())
;
BOOST_ASSERT(m_freeCsEntries.size() == m_nMaxPackets);
while (!m_freeCsEntries.empty())
{
delete m_freeCsEntries.front();
m_freeCsEntries.pop();
}
}
size_t
Cs::size() const
{
return m_nPackets; // size of the first layer in a skip list
}
void
Cs::setLimit(size_t nMaxPackets)
{
size_t oldNMaxPackets = m_nMaxPackets;
m_nMaxPackets = nMaxPackets;
while (isFull())
{
if (!evictItem())
break;
}
if (m_nMaxPackets >= oldNMaxPackets)
{
for (size_t i = oldNMaxPackets; i < m_nMaxPackets; i++)
{
m_freeCsEntries.push(new cs::Entry());
}
}
else
{
for (size_t i = oldNMaxPackets; i > m_nMaxPackets; i--)
{
delete m_freeCsEntries.front();
m_freeCsEntries.pop();
}
}
}
size_t
Cs::getLimit() const
{
return m_nMaxPackets;
}
//Reference: "Skip Lists: A Probabilistic Alternative to Balanced Trees" by W.Pugh
std::pair<cs::Entry*, bool>
Cs::insertToSkipList(const Data& data, bool isUnsolicited)
{
BOOST_ASSERT(m_cleanupIndex.size() <= size());
BOOST_ASSERT(m_freeCsEntries.size() > 0);
m_mutex.lock();
// take entry for the memory pool
cs::Entry* entry = m_freeCsEntries.front();
m_freeCsEntries.pop();
m_nPackets++;
entry->setData(data, isUnsolicited);
bool insertInFront = false;
bool isIterated = false;
SkipList::reverse_iterator topLayer = m_skipList.rbegin();
SkipListLayer::iterator updateTable[SKIPLIST_MAX_LAYERS];
SkipListLayer::iterator head = (*topLayer)->begin();
if (!(*topLayer)->empty())
{
//start from the upper layer towards bottom
int layer = m_skipList.size() - 1;
for (SkipList::reverse_iterator rit = topLayer; rit != m_skipList.rend(); ++rit)
{
//if we didn't do any iterations on the higher layers, start from the begin() again
if (!isIterated)
head = (*rit)->begin();
updateTable[layer] = head;
if (head != (*rit)->end())
{
// it can happen when begin() contains the element in front of which we need to insert
if (!isIterated && ((*head)->getName() >= entry->getName()))
{
--updateTable[layer];
insertInFront = true;
}
else
{
SkipListLayer::iterator it = head;
while ((*it)->getName() < entry->getName())
{
head = it;
updateTable[layer] = it;
isIterated = true;
++it;
if (it == (*rit)->end())
break;
}
}
}
if (layer > 0)
head = (*head)->getIterators().find(layer - 1)->second; // move HEAD to the lower layer
layer--;
}
}
else
{
updateTable[0] = (*topLayer)->begin(); //initialization
}
head = updateTable[0];
++head; // look at the next slot to check if it contains a duplicate
bool isCsEmpty = (size() == 0);
bool isInBoundaries = (head != (*m_skipList.begin())->end());
bool isNameIdentical = false;
if (!isCsEmpty && isInBoundaries)
{
isNameIdentical = (*head)->getName() == entry->getName();
}
//check if this is a duplicate packet
if (isNameIdentical)
{
(*head)->setData(data, isUnsolicited, entry->getDigest()); //updates stale time
// new entry not needed, returning to the pool
entry->release();
m_freeCsEntries.push(entry);
m_nPackets--;
m_mutex.unlock();
return std::make_pair(*head, false);
}
size_t randomLayer = pickRandomLayer();
while (m_skipList.size() < randomLayer + 1)
{
SkipListLayer* newLayer = new SkipListLayer();
m_skipList.push_back(newLayer);
updateTable[(m_skipList.size() - 1)] = newLayer->begin();
}
size_t layer = 0;
for (SkipList::iterator i = m_skipList.begin();
i != m_skipList.end() && layer <= randomLayer; ++i)
{
if (updateTable[layer] == (*i)->end() && !insertInFront)
{
(*i)->push_back(entry);
SkipListLayer::iterator last = (*i)->end();
--last;
entry->setIterator(layer, last);
}
else if (updateTable[layer] == (*i)->end() && insertInFront)
{
(*i)->push_front(entry);
entry->setIterator(layer, (*i)->begin());
}
else
{
++updateTable[layer]; // insert after
SkipListLayer::iterator position = (*i)->insert(updateTable[layer], entry);
entry->setIterator(layer, position); // save iterator where item was inserted
}
layer++;
}
m_mutex.unlock();
return std::make_pair(entry, true);
}
bool
Cs::insert(const Data& data, bool isUnsolicited)
{
if (isFull())
{
evictItem();
}
//pointer and insertion status
std::pair<cs::Entry*, bool> entry = insertToSkipList(data, isUnsolicited);
//new entry
if (static_cast<bool>(entry.first) && (entry.second == true))
{
m_cleanupIndex.push_back(entry.first);
return true;
}
return false;
}
size_t
Cs::pickRandomLayer() const
{
int layer = -1;
int randomValue;
do
{
layer++;
randomValue = rand() % 100 + 1;
}
while ((randomValue < SKIPLIST_PROBABILITY) && (layer < SKIPLIST_MAX_LAYERS));
return static_cast<size_t>(layer);
}
bool
Cs::isFull() const
{
if (size() >= m_nMaxPackets) //size of the first layer vs. max size
return true;
return false;
}
bool
Cs::eraseFromSkipList(cs::Entry* entry)
{
m_mutex.lock();
bool isErased = false;
const std::map<int, std::list<cs::Entry*>::iterator>& iterators = entry->getIterators();
if (!iterators.empty())
{
int layer = 0;
for (SkipList::iterator it = m_skipList.begin(); it != m_skipList.end(); )
{
std::map<int, std::list<cs::Entry*>::iterator>::const_iterator i = iterators.find(layer);
if (i != iterators.end())
{
(*it)->erase(i->second);
entry->removeIterator(layer);
isErased = true;
//remove layers that do not contain any elements (starting from the second layer)
if ((layer != 0) && (*it)->empty())
{
delete *it;
it = m_skipList.erase(it);
}
else
++it;
layer++;
}
else
break;
}
}
//delete entry;
if (isErased)
{
entry->release();
m_freeCsEntries.push(entry);
m_nPackets--;
}
m_mutex.unlock();
return isErased;
}
bool
Cs::evictItem()
{
if (!m_cleanupIndex.get<byArrival>().empty())
{
eraseFromSkipList(*m_cleanupIndex.get<byArrival>().begin());
m_cleanupIndex.get<byArrival>().erase(m_cleanupIndex.get<byArrival>().begin());
return true;
}
return false;
}
const Data*
Cs::find(const Interest& interest)
{
m_mutex.lock();
bool isIterated = false;
SkipList::const_reverse_iterator topLayer = m_skipList.rbegin();
SkipListLayer::iterator head = (*topLayer)->begin();
if (!(*topLayer)->empty())
{
//start from the upper layer towards bottom
int layer = m_skipList.size() - 1;
for (SkipList::const_reverse_iterator rit = topLayer; rit != m_skipList.rend(); ++rit)
{
//if we didn't do any iterations on the higher layers, start from the begin() again
if (!isIterated)
head = (*rit)->begin();
if (head != (*rit)->end())
{
// it happens when begin() contains the element we want to find
if (!isIterated && (interest.getName().isPrefixOf((*head)->getName())))
{
if (layer > 0)
{
layer--;
continue; // try lower layer
}
else
{
isIterated = true;
}
}
else
{
SkipListLayer::iterator it = head;
while ((*it)->getName() < interest.getName())
{
head = it;
isIterated = true;
++it;
if (it == (*rit)->end())
break;
}
}
}
if (layer > 0)
{
head = (*head)->getIterators().find(layer - 1)->second; // move HEAD to the lower layer
}
else //if we reached the first layer
{
if (isIterated)
{
m_mutex.unlock();
return selectChild(interest, head);
}
}
layer--;
}
}
m_mutex.unlock();
return 0;
}
const Data*
Cs::selectChild(const Interest& interest, SkipListLayer::iterator startingPoint) const
{
BOOST_ASSERT(startingPoint != (*m_skipList.begin())->end());
if (startingPoint != (*m_skipList.begin())->begin())
{
BOOST_ASSERT((*startingPoint)->getName() < interest.getName());
}
bool hasLeftmostSelector = (interest.getChildSelector() <= 0);
bool hasRightmostSelector = !hasLeftmostSelector;
if (hasLeftmostSelector)
{
bool doesInterestContainDigest = recognizeInterestWithDigest(interest, *startingPoint);
bool isInPrefix = false;
if (doesInterestContainDigest)
{
isInPrefix = interest.getName().getPrefix(-1).isPrefixOf((*startingPoint)->getName());
}
else
{
isInPrefix = interest.getName().isPrefixOf((*startingPoint)->getName());
}
if (isInPrefix)
{
if (doesComplyWithSelectors(interest, *startingPoint, doesInterestContainDigest))
{
return &(*startingPoint)->getData();
}
}
}
//iterate to the right
SkipListLayer::iterator rightmost = startingPoint;
if (startingPoint != (*m_skipList.begin())->end())
{
SkipListLayer::iterator rightmostCandidate = startingPoint;
Name currentChildPrefix("");
while (true)
{
++rightmostCandidate;
bool isInBoundaries = (rightmostCandidate != (*m_skipList.begin())->end());
bool isInPrefix = false;
bool doesInterestContainDigest = false;
if (isInBoundaries)
{
doesInterestContainDigest = recognizeInterestWithDigest(interest,
*rightmostCandidate);
if (doesInterestContainDigest)
{
isInPrefix = interest.getName().getPrefix(-1)
.isPrefixOf((*rightmostCandidate)->getName());
}
else
{
isInPrefix = interest.getName().isPrefixOf((*rightmostCandidate)->getName());
}
}
if (isInPrefix)
{
if (doesComplyWithSelectors(interest, *rightmostCandidate, doesInterestContainDigest))
{
if (hasLeftmostSelector)
{
return &(*rightmostCandidate)->getData();
}
if (hasRightmostSelector)
{
if (doesInterestContainDigest)
{
// get prefix which is one component longer than Interest name
// (without digest)
const Name& childPrefix = (*rightmostCandidate)->getName()
.getPrefix(interest.getName().size());
if (currentChildPrefix.empty() || (childPrefix != currentChildPrefix))
{
currentChildPrefix = childPrefix;
rightmost = rightmostCandidate;
}
}
else
{
// get prefix which is one component longer than Interest name
const Name& childPrefix = (*rightmostCandidate)->getName()
.getPrefix(interest.getName().size() + 1);
if (currentChildPrefix.empty() || (childPrefix != currentChildPrefix))
{
currentChildPrefix = childPrefix;
rightmost = rightmostCandidate;
}
}
}
}
}
else
break;
}
}
if (rightmost != startingPoint)
{
return &(*rightmost)->getData();
}
if (hasRightmostSelector) // if rightmost was not found, try starting point
{
bool doesInterestContainDigest = recognizeInterestWithDigest(interest, *startingPoint);
bool isInPrefix = false;
if (doesInterestContainDigest)
{
isInPrefix = interest.getName().getPrefix(-1).isPrefixOf((*startingPoint)->getName());
}
else
{
isInPrefix = interest.getName().isPrefixOf((*startingPoint)->getName());
}
if (isInPrefix)
{
if (doesComplyWithSelectors(interest, *startingPoint, doesInterestContainDigest))
{
return &(*startingPoint)->getData();
}
}
}
return 0;
}
bool
Cs::doesComplyWithSelectors(const Interest& interest,
cs::Entry* entry,
bool doesInterestContainDigest) const
{
/// \todo The following detection is not correct
/// 1. If data name ends with 32-octet component doesn't mean that this component is digest
/// 2. Only min/max selectors (both 0) can be specified, all other selectors do not
/// make sense for interests with digest (though not sure if we need to enforce this)
if (doesInterestContainDigest)
{
const ndn::name::Component& last = interest.getName().get(-1);
const ndn::ConstBufferPtr& digest = entry->getDigest();
BOOST_ASSERT(digest->size() == last.value_size());
BOOST_ASSERT(digest->size() == ndn::crypto::SHA256_DIGEST_SIZE);
if (std::memcmp(digest->buf(), last.value(), ndn::crypto::SHA256_DIGEST_SIZE) != 0)
{
return false;
}
}
if (!doesInterestContainDigest)
{
if (interest.getMinSuffixComponents() >= 0)
{
size_t minDataNameLength = interest.getName().size() + interest.getMinSuffixComponents();
bool isSatisfied = (minDataNameLength <= entry->getName().size());
if (!isSatisfied)
{
return false;
}
}
if (interest.getMaxSuffixComponents() >= 0)
{
size_t maxDataNameLength = interest.getName().size() + interest.getMaxSuffixComponents();
bool isSatisfied = (maxDataNameLength >= entry->getName().size());
if (!isSatisfied)
{
return false;
}
}
}
if (!interest.getPublisherPublicKeyLocator().empty())
{
if (entry->getData().getSignature().getType() == ndn::Signature::Sha256WithRsa)
{
ndn::SignatureSha256WithRsa rsaSignature(entry->getData().getSignature());
if (rsaSignature.getKeyLocator() != interest.getPublisherPublicKeyLocator())
{
return false;
}
}
else
{
return false;
}
}
if (doesInterestContainDigest)
{
const ndn::name::Component& lastComponent = entry->getName().get(-1);
if (!lastComponent.empty())
{
if (interest.getExclude().isExcluded(lastComponent))
{
return false;
}
}
}
else
{
if (entry->getName().size() >= interest.getName().size() + 1)
{
const ndn::name::Component& nextComponent = entry->getName()
.get(interest.getName().size());
if (!nextComponent.empty())
{
if (interest.getExclude().isExcluded(nextComponent))
{
return false;
}
}
}
}
return true;
}
bool
Cs::recognizeInterestWithDigest(const Interest& interest, cs::Entry* entry) const
{
// only when min selector is not specified or specified with value of 0
// and Interest's name length is exactly the length of the name of CS entry
if (interest.getMinSuffixComponents() <= 0 &&
interest.getName().size() == (entry->getName().size()))
{
const ndn::name::Component& last = interest.getName().get(-1);
if (last.value_size() == ndn::crypto::SHA256_DIGEST_SIZE)
{
return true;
}
}
return false;
}
void
Cs::erase(const Name& exactName)
{
m_mutex.lock();
bool isIterated = false;
SkipListLayer::iterator updateTable[SKIPLIST_MAX_LAYERS];
SkipList::reverse_iterator topLayer = m_skipList.rbegin();
SkipListLayer::iterator head = (*topLayer)->begin();
if (!(*topLayer)->empty())
{
//start from the upper layer towards bottom
int layer = m_skipList.size() - 1;
for (SkipList::reverse_iterator rit = topLayer; rit != m_skipList.rend(); ++rit)
{
//if we didn't do any iterations on the higher layers, start from the begin() again
if (!isIterated)
head = (*rit)->begin();
updateTable[layer] = head;
if (head != (*rit)->end())
{
// it can happen when begin() contains the element we want to remove
if (!isIterated && ((*head)->getName() == exactName))
{
eraseFromSkipList(*head);
m_mutex.unlock();
return;
}
else
{
SkipListLayer::iterator it = head;
while ((*it)->getName() < exactName)
{
head = it;
updateTable[layer] = it;
isIterated = true;
++it;
if (it == (*rit)->end())
break;
}
}
}
if (layer > 0)
head = (*head)->getIterators().find(layer - 1)->second; // move HEAD to the lower layer
layer--;
}
}
else
{
m_mutex.unlock();
return;
}
head = updateTable[0];
++head; // look at the next slot to check if it contains the item we want to remove
bool isCsEmpty = (size() == 0);
bool isInBoundaries = (head != (*m_skipList.begin())->end());
bool isNameIdentical = false;
if (!isCsEmpty && isInBoundaries)
{
isNameIdentical = (*head)->getName() == exactName;
}
if (isNameIdentical)
{
eraseFromSkipList(*head);
}
}
void
Cs::printSkipList() const
{
//start from the upper layer towards bottom
int layer = m_skipList.size() - 1;
for (SkipList::const_reverse_iterator rit = m_skipList.rbegin(); rit != m_skipList.rend(); ++rit)
{
for (SkipListLayer::iterator it = (*rit)->begin(); it != (*rit)->end(); ++it)
{
std::cout << "Layer " << layer << " " << (*it)->getName() << std::endl;
}
layer--;
}
}
} //namespace nfd
| 21,494 | 27.320158 | 101 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/manifest.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef MANIFEST_HPP
#define MANIFEST_HPP
#include "common.hpp"
#include "context.hpp"
#include "context-options.hpp"
#include "context-default-values.hpp"
#include "tlv.hpp"
#include <ndn-cxx/encoding/tlv.hpp>
#include <ndn-cxx/util/crypto.hpp>
#include <ndn-cxx/security/key-chain.hpp>
namespace ndn {
class Manifest : public Data
{
public:
class Error : public std::runtime_error
{
public:
explicit
Error(const std::string& what)
: std::runtime_error(what)
{
}
};
/**
* Default constructor.
*/
Manifest();
explicit
Manifest(const Name& name);
explicit
Manifest(const Data& data);
/**
* The virtual destructor.
*/
virtual
~Manifest();
inline void
wireDecode(const Block& wire);
void
addKeyValuePair(const uint8_t* key, size_t keySize, const uint8_t* value, size_t valueSize);
void
addKeyValuePair(std::string key, std::string value);
std::string
getValueByKey(std::string key);
void
eraseValueByKey(std::string key);
/**
* Begin iterator (const).
*/
std::list<Name>::const_iterator
catalogueBegin() const
{
return m_catalogueNames.begin();
}
/**
* End iterator (const).
*/
std::list<Name>::const_iterator
catalogueEnd() const
{
return m_catalogueNames.end();
}
/**
* Adds full name (with digest) to the manifest.
* @param name Name must contain a digest in its last component.
*/
void
addNameToCatalogue(const Name& name);
/**
* Concatenates the name prefix with the digest and adds the resulting full name to the manifest.
* @param name The name prefix without digest component.
* @param digest The tlv block containing digest (data.getSignature().getValue())
*/
void
addNameToCatalogue(const Name& name, const Block& digest);
/**
* Concatenates the name prefix with the digest and adds the resulting full name to the manifest.
* @param name The name prefix without digest component.
* @param digest The buffer containing digest
*/
void
addNameToCatalogue(const Name& name, const ndn::ConstBufferPtr& digest);
void
eraseNameFromCatalogue(const std::vector<Name>::iterator it);
/**
* encode manifest into content (Data packet)
*/
void
encode();
void
decode();
template<bool T>
size_t
wireEncode(EncodingImpl<T>& block) const;
private:
std::list<Name> m_catalogueNames;
std::map<std::string, std::string> m_keyValuePairs;
};
} //namespace ndn
#endif // MANIFEST_HPP
| 3,593 | 23.283784 | 99 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/simple-data-retrieval.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef SIMPLE_DATA_RETRIEVAL_HPP
#define SIMPLE_DATA_RETRIEVAL_HPP
#include "data-retrieval-protocol.hpp"
#include "context-options.hpp"
#include "context-default-values.hpp"
#include "selector-helper.hpp"
namespace ndn {
/*
* Any communication in NDN network involves Interest/Data exchanges,
* and Simple Data Retrieval protocol (SDR) is the simplest form of fetching Data from NDN network,
* corresponding to "one Interest / one Data" pattern.
* SDR provides no guarantee of Interest or Data delivery.
* If SDR cannot verify an incoming Data packet, the packet is dropped.
* SDR can be used by applications that want to directly control Interest transmission
* and error correction, or have small ADUs that fit in one Data packet.
*/
class SimpleDataRetrieval : public DataRetrievalProtocol
{
public:
SimpleDataRetrieval(Context* context);
void
start();
void
stop();
private:
void
onData(const ndn::Interest& interest, ndn::Data& data);
void
onTimeout(const ndn::Interest& interest);
void
sendInterest();
};
} // namespace ndn
#endif // SIMPLE_DATA_RETRIEVAL_HPP
| 2,188 | 32.166667 | 99 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/data-retrieval-protocol.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef DATA_RETRIEVAL_PROTOCOL_HPP
#define DATA_RETRIEVAL_PROTOCOL_HPP
#include <ndn-cxx/util/scheduler.hpp>
#include "context.hpp"
namespace ndn {
class Consumer;
class DataRetrievalProtocol
{
public:
DataRetrievalProtocol(Context* context);
void updateFace();
bool isRunning();
virtual void
start() = 0;
virtual void
stop() = 0;
protected:
Context* m_context;
shared_ptr<ndn::Face> m_face;
bool m_isRunning;
};
} // namespace ndn
#endif // DATA_RETRIEVAL_PROTOCOL_HPP
| 1,580 | 27.232143 | 99 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/cs-entry.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "cs-entry.hpp"
namespace ndn {
namespace cs {
void
Entry::release()
{
BOOST_ASSERT(m_layerIterators.empty());
m_dataPacket.reset();
m_digest.reset();
m_nameWithDigest.clear();
}
void
Entry::setData(const Data& data, bool isUnsolicited)
{
m_isUnsolicited = isUnsolicited;
m_dataPacket = data.shared_from_this();
m_digest.reset();
updateStaleTime();
m_nameWithDigest = data.getName();
m_nameWithDigest.append(ndn::name::Component(getDigest()));
}
void
Entry::setData(const Data& data, bool isUnsolicited, const ndn::ConstBufferPtr& digest)
{
m_dataPacket = data.shared_from_this();
m_digest = digest;
updateStaleTime();
m_nameWithDigest = data.getName();
m_nameWithDigest.append(ndn::name::Component(getDigest()));
}
void
Entry::updateStaleTime()
{
m_staleAt = time::steady_clock::now() + m_dataPacket->getFreshnessPeriod();
}
const ndn::ConstBufferPtr&
Entry::getDigest() const
{
if (!static_cast<bool>(m_digest))
{
const Block& block = m_dataPacket->wireEncode();
m_digest = ndn::crypto::sha256(block.wire(), block.size());
}
return m_digest;
}
void
Entry::setIterator(int layer, const Entry::LayerIterators::mapped_type& layerIterator)
{
m_layerIterators[layer] = layerIterator;
}
void
Entry::removeIterator(int layer)
{
m_layerIterators.erase(layer);
}
void
Entry::printIterators() const
{
}
} // namespace cs
} // namespace nfd
| 2,484 | 24.10101 | 99 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/infomax-prioritizer.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef PRIORITIZERS_HPP
#define PRIORITIZERS_HPP
#include "producer-context.hpp"
#include "infomax-tree-node.hpp"
#include <list>
namespace ndn {
class Producer;
class Prioritizer
{
public:
Prioritizer(Producer* p);
void
prioritize();
private:
void
simplePrioritizer(TreeNode* root);
void
mergePrioritizer(TreeNode* root);
void
dummy(TreeNode* root);
TreeNode*
getNextPriorityNode(TreeNode* root);
std::list<TreeNode *>*
mergeSort(TreeNode* node);
std::list<TreeNode *>*
merge(vector< std::list<TreeNode*>* > *subTreeMergeList);
void
produceInfoMaxList(Name, vector<TreeNode*>* prioritizedVector);
bool
treeNodePointerComparator(TreeNode* i, TreeNode* j);
void
resetNodeStatus(TreeNode* node);
private:
Producer *m_producer;
uint64_t m_listVersion;
Name m_prefix;
TreeNode m_root;
};
}
#endif // PRIORITIZERS_HPP
| 1,957 | 24.763158 | 99 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/README.md
|
Interest Control Protocol For NDN (ndn-icp-download)
======================================
This is a library implementing an Interest control protocol that applications can use for downloading data.
The protocol implements:
- reliable data fetching
- Interest window based flow control based on delay measurements;
- congestion control using remote active queue management;
- multipath management by using explicit path labeling if NFD
supports path labeling;
- NFD patch to enable path labeling is also available and
provided in this package.
A complete description and analysis of the protocol is available in
the following publication:
Carofiglio, G.; Gallo, M.; Muscariello, L.; Papalini, M.; Sen Wang,
"Optimal multipath congestion control and request forwarding in
Information-Centric Networks," Network Protocols (ICNP),
21st IEEE International Conference on , vol., no., pp.1,10, 7-10 Oct. 2013
http://dx.doi.org/10.1109/ICNP.2013.6733576
The application requires installation of ndn-cxx and boost libraries.
## Prerequisites ##
Compiling and running ndn-icp-download requires the following dependencies:
1. C++ Boost Libraries version >= 1.48
On Ubuntu 14.04 and later
sudo apt-get install libboost-all-dev
On OSX with macports
sudo port install boost
On OSX with brew
brew install boost
On other platforms Boost Libraries can be installed from the packaged version for the
distribution, if the version matches requirements, or compiled from source
(http://www.boost.org)
2. ndn-cxx library (https://github.com/named-data/ndn-cxx)
For detailed installation instructions refer to
https://github.com/named-data/ndn-cxx
3. NDN forwarding daemon (https://github.com/named-data/NFD)
-----------------------------------------------------
## 1. Compile And Installation Instructions: ##
./waf configure --prefix=/usr
./waf
sudo ./waf install
## 2. Usage
This library can be used by including the header file <ndn-icp-download.hpp>.
If you correctly installed the library you should have this file under /usr/include.
The application can exploit the library in this way:
```cpp
#include <ndn-icp-download.hpp>
#include <fstream>
namespace ndn
{
int
main(int argc, char** argv)
{
bool allow_stale = false;
int sysTimeout = -1;
unsigned InitialMaxwindow = RECEPTION_BUFFER - 1; // Constants declared inside ndn-icp-download.hpp
unsigned int m_timer = DEFAULT_INTEREST_TIMEOUT;
double drop_factor = DROP_FACTOR;
double p_min = P_MIN;
double beta = BETA;
unsigned int gamma = GAMMA;
unsigned int samples = SAMPLES;
unsigned int nchunks = -1; // XXX chunks=-1 means: download the whole file!
bool output = false;
bool report_path = false;
std::string name = argv[1];
NdnIcpDownload ndnicpdownload(InitialMaxwindow, gamma, beta, allow_stale, m_timer/1000);
shared_ptr<DataPath> initPath = make_shared<DataPath>(drop_factor, p_min, m_timer, samples);
ndnicpdownload.insertToPathTable(DEFAULT_PATH_ID, initPath);
ndnicpdownload.setCurrentPath(initPath);
ndnicpdownload.setStartTimetoNow();
ndnicpdownload.setLastTimeOutoNow();
if (output)
ndnicpdownload.enableOutput();
if (report_path)
ndnicpdownload.enablePathReport();
if (sysTimeout >= 0)
ndnicpdownload.setSystemTimeout(sysTimeout);
std::ofstream output_file;
output_file.open("book.pdf", std::ios::out | std::ios::binary);
std::vector<char> * data = new std::vector<char>;
bool res;
while(true)
{
res = ndnicpdownload.download(name, data, -1, 1000);
std::cout << data->empty() << std::endl;
for (std::vector<char>::const_iterator i = data->begin(); i != data->end(); ++i)
output_file << *i;
if (res)
break;
}
output_file.close();
return 0;
}
}
int
main(int argc, char** argv)
{
return ndn::main(argc, argv);
}
```
To ensure compatibity with all the ICN repositories, the support for PATH_LABELLING has been
disabled. You can re-enabled it by adding the configuration option --with-path-labelling.
```
./waf configure --prefix=/usr --with-path-labelling
```
There are basically 2 ways to download a file using this library:
- The first consists in downloading the whole file, storing it in RAM. It is useful for small files,
that can be stored into a buffer.
You have to create a std::vector<char> and then pass a pointer to it to the download method if the class NdnIcpDownload,
in this way:
```cpp
std::vector<char> * data = new std::vector<char>;
bool res = ndnicpdownload.download(name, data);
```
- The second way works as the data transfer implemented by the system call recv. Basically you create a buffer and then
you download a certain number of chunk, as the example above. The function will return after the download of the number of chunk specified.
It is so possible to download a certain amount of data, store it in the hard disk and then continue the download,
without wasting memory with buffer of Gigabytes of data.
```cpp
std::vector<char> * data = new std::vector<char>;
bool res;
while(true)
{
res = ndnicpdownload.download(name, data, -1, 1000);
std::cout << data->empty() << std::endl;
// XXX It would be better to store the data through blocks, not char by char.
for (std::vector<char>::const_iterator i = data->begin(); i != data->end(); ++i)
output_file << *i;
if (res)
break;
}
```
If there is any error during the download, the download method will throw an exception.
If you change the name in the middle of another download, the download will restart from zero.
| 5,872 | 30.239362 | 144 |
md
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/rate-estimation.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Jacques Samain <[email protected]>
*
*/
#ifndef RATE_ESTIMATOR_H
#define RATE_ESTIMATOR_H
#include <unistd.h>
#include <ndn-cxx/face.hpp>
#include <boost/unordered_map.hpp>
#include "data-path.hpp"
#include "pending-interest.hpp"
#define BATCH 50
#define KV 20
namespace ndn {
class Variables
{
public:
Variables();
struct timeval begin;
volatile double alpha;
volatile double avgWin;
volatile double avgRtt;
volatile double rtt;
volatile double instantaneousThroughput;
volatile double winChange;
volatile int batchingStatus;
volatile bool isRunning;
volatile double winCurrent;
volatile bool isBusy;
volatile int maxPacketSize;
}; //end class Variables
class NdnIcpDownloadRateEstimator
{
public:
NdnIcpDownloadRateEstimator(){};
~NdnIcpDownloadRateEstimator(){};
virtual void onRttUpdate(double rtt){};
virtual void onDataReceived(int packetSize){};
virtual void onWindowIncrease(double winCurrent){};
virtual void onWindowDecrease(double winCurrent){};
Variables *m_variables;
};
//A rate estimator based on the RTT: upon the reception
class InterRttEstimator : public NdnIcpDownloadRateEstimator
{
public:
InterRttEstimator(Variables *var);
void onRttUpdate(double rtt);
void onDataReceived(int packetSize) {};
void onWindowIncrease(double winCurrent);
void onWindowDecrease(double winCurrent);
private:
pthread_t * myTh;
bool ThreadisRunning;
};
//A rate estimator, this one
class BatchingPacketsEstimator : public NdnIcpDownloadRateEstimator
{
public:
BatchingPacketsEstimator(Variables *var,int batchingParam);
void onRttUpdate(double rtt);
void onDataReceived(int packetSize) {};
void onWindowIncrease(double winCurrent);
void onWindowDecrease(double winCurrent);
private:
int batchingParam;
pthread_t * myTh;
bool ThreadisRunning;
};
//A Rate estimator, this one is the simplest: counting batchingParam packets and then divide the sum of the size of these packets by the time taken to DL them.
class SimpleEstimator : public NdnIcpDownloadRateEstimator
{
public:
SimpleEstimator(Variables *var, int batchingParam);
void onRttUpdate(double rtt);
void onDataReceived(int packetSize);
void onWindowIncrease(double winCurrent){};
void onWindowDecrease(double winCurrent){};
private:
int batchingParam;
};
void *Timer(void * data);
}//end of namespace ndn
#endif //RATE_ESTIMATOR_H
| 3,429 | 26.44 | 160 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/chunktimeObserver.cpp
|
/*
* Timing of NDN Interest packets and NDN Data packets while downloading.
*/
#include "chunktimeObserver.hpp"
//for logging/terminal output
#include "stdio.h"
#include <sstream>
#include <iostream>
// To catch a potential OOR map issue
#include <stdexcept>
// For bandit context
#include <chrono>
#include <thread>
ChunktimeObserver::ChunktimeObserver(int sample)
{
this->sampleSize = sample;
this->lastInterestKey = "Dummy";
this->lastDataKey = "Dummy";
this->sampleNumber = 0;
this->cumulativeTp = 0.0;
pFile = fopen("log_ChunktimeObserver", "a");
startTime = boost::chrono::system_clock::now();
}
ChunktimeObserver::~ChunktimeObserver()
{
fclose(pFile);
}
void ChunktimeObserver::addThroughputSignal(ThroughputNotificationSlot slot) {
signalThroughputToDASHReceiver.connect(slot);
}
void ChunktimeObserver::addContextSignal(ContextNotificationSlot slot) {
signalContextToDASHReceiver.connect(slot);
}
//logging method
void ChunktimeObserver::writeLogFile(const std::string szString)
{
double timePoint = boost::chrono::duration_cast<boost::chrono::microseconds>(boost::chrono::system_clock::now() - startTime).count();
timePoint = timePoint * 0.000001; //from microseconds to seconds
fprintf(pFile, "%f",timePoint);
fprintf(pFile, "\t%s",szString.c_str());
}
void ChunktimeObserver::onInterestSent(const ndn::Interest &interest)
{
boost::chrono::time_point<boost::chrono::system_clock> timestamp = boost::chrono::system_clock::now();
//Build the key and key-1
int chunkNo = interest.getName()[-1].toSegment();
int chunkNoMinusOne = chunkNo - 1;
std::string chunkID = interest.getName().toUri();
std::string key = chunkID.substr(0, 9).append(std::to_string(chunkNo));
std::string keyMinusOne = chunkID.substr(0, 9).append(std::to_string(chunkNoMinusOne));
//Insert timestamp into the Map
if (timingMap.count(keyMinusOne) == 0) //no key-1 in map -> first Interest of Segment
{
if(this->lastInterestKey.compare("Dummy") == 0) //no lastInterestKey set -> first Interest overall
{
//logging start
std::stringstream stringstreamI;
stringstreamI << "IKey: " << key << "\t" << "(no) IKey-1: " << keyMinusOne << "\n";
this->writeLogFile(stringstreamI.str());
//logging end
std::vector<boost::chrono::time_point<boost::chrono::system_clock>> timeVector(4);
timeVector.at(0) = timestamp;
timeVector.at(1) = timestamp; timeVector.at(2) = timestamp; timeVector.at(3) = timestamp; //TODOTIMO: initialise new vector (with dummy values for yet unknown spots)
timingMap.emplace(key, timeVector); //as Interest1
this->lastInterestKey = key;
} else //last Key set -> NOT first Interest overall
{
//logging start
std::stringstream stringstreamI;
stringstreamI << "IKey: " << key << "\t" << "LastIKey: " << this->lastInterestKey << "\n";
this->writeLogFile(stringstreamI.str());
//logging end
timingMap.at(this->lastInterestKey).at(1) = timestamp; //as Interest2
std::vector<boost::chrono::time_point<boost::chrono::system_clock>> timeVector(4);
timeVector.at(0) = timestamp;
timingMap.emplace(key, timeVector); //as Interest1
this->lastInterestKey = key;
}
}
else //NOT first Interest
{
//logging start
std::stringstream stringstreamI;
stringstreamI << "IKey: " << key << "\t" << "IKey-1: " << keyMinusOne << "\n";
this->writeLogFile(stringstreamI.str());
//logging end
timingMap.at(keyMinusOne).at(1) = timestamp; //as Interest2
std::vector<boost::chrono::time_point<boost::chrono::system_clock>> timeVector(4);
timeVector.at(0) = timestamp;
timingMap.emplace(key, timeVector); //as Interest1
this->lastInterestKey = key;
}
}
double ChunktimeObserver::onDataReceived(const ndn::Data &data)
{
try {
boost::chrono::time_point<boost::chrono::system_clock> timestamp = boost::chrono::system_clock::now();
//Build key and key-1
int chunkNo = data.getName()[-1].toSegment();
int chunkNoMinusOne = chunkNo - 1;
std::string chunkID = data.getName().toUri();
std::string tail = chunkID.substr(std::max<int>(chunkID.size()-6,0));
bool initChunk = (tail.compare("%00%00") == 0); //true, if it is the first chunk of a segment (no viable measurement)
std::string key = chunkID.substr(0, 9).append(std::to_string(chunkNo));
std::string keyMinusOne = chunkID.substr(0, 9).append(std::to_string(chunkNoMinusOne));
int thisRTT = boost::chrono::duration_cast<boost::chrono::microseconds>(timestamp - timingMap.at(key).at(0)).count();
int numHops = 0;
auto numHopsTag = data.getTag<ndn::lp::NumHopsTag>();
if (numHopsTag != nullptr) {
numHops = (uint64_t)numHopsTag->get(); // Comes out as a unsigned long int
}
signalContextToDASHReceiver((uint64_t)thisRTT, (uint64_t)numHops);
//Insert timestamp into the map
if (timingMap.count(keyMinusOne) == 0) //no key-1 in map -> first Data packet of the Segment
{
if(this->lastDataKey.compare("Dummy") == 0) //no lastDataKey set -> first Data packet overall)
{
std::stringstream stringstreamD;
stringstreamD << "DKey: " << key << "\t" << "(no) DKey-1: " << keyMinusOne << "\n";
this->writeLogFile(stringstreamD.str());
timingMap.at(key).at(2) = timestamp; //as Data1
this->lastDataKey = key;
return 0; //what to return when there is no gap b.c. of first Data packet of Segment?
} else
{
std::stringstream stringstreamD;
stringstreamD << "DKey: " << key << "\t" << "LastDKey: " << this->lastDataKey << "\n";
this->writeLogFile(stringstreamD.str());
timingMap.at(this->lastDataKey).at(3) = timestamp; //as Data2
timingMap.at(key).at(2) = timestamp; //as Data1
//timingVector is complete for map[lastDataKey] -> measurement computations can be triggered now!
int dataPacketSize = data.wireEncode().size();
int interestDelay = this->computeInterestDelay(this->lastDataKey);
int dataDelay = this->computeDataDelay(this->lastDataKey);
int firstRTT = this->computeRTT(this->lastDataKey, true);
int secondRTT = this->computeRTT(this->lastDataKey, false);
double quotient = this->interestDataQuotient((double) dataDelay, interestDelay);
double classicBW = this->computeClassicBW(firstRTT, dataPacketSize);
double throughput = this->throughputEstimation(dataDelay, dataPacketSize);
double sampledTp = 0.0;
//SEPERATION: chunks at the beginning of a segment download may not have viable values
// AND out of order reception data delays also no viable values
// AND firstRTT must not be 0 because then, the dummy value in the timestamp vector is used (= the data delay is not viable)
if(isValidMeasurement(throughput, firstRTT, dataDelay) && !initChunk)
sampledTp = this->getSampledThroughput(throughput);
else
this->writeLogFile("Invalid computation.\n");
//logging start
std::stringstream loggingString;
loggingString << "I-Delay: " << interestDelay << "\t" << "D-Delay: " << dataDelay << "\t"
<< "First RTT: " << firstRTT << "\t" << "Second RTT: " << secondRTT << "\t"
<< "Classic BW: " << classicBW << "\t" << "gOut/gIn: " << quotient << "\t" << "Throughput: " << throughput << "\n";
this->writeLogFile(loggingString.str());
if(sampleNumber==0 && sampledTp != 0.0) //TODO Does this work?
{
std::stringstream sampleString;
sampleString << sampleSize << "-Sampled Throughput: " << sampledTp << "\n";
this->writeLogFile(sampleString.str());
}
//logging end
this->lastDataKey = key;
if(isValidMeasurement(throughput, firstRTT, dataDelay) && !initChunk)
return throughput; //unsampled throughput
else
return 0; //invalid throughput
}
}
else //NOT first Data packet
{
std::stringstream stringstreamD;
stringstreamD << "DKey: " << key << "\t" << "DKey-1: " << keyMinusOne << "\n";
this->writeLogFile(stringstreamD.str());
timingMap.at(keyMinusOne).at(3) = timestamp; //as Data2
timingMap.at(key).at(2) = timestamp; //as Data1
//timingVector is complete for map[keyMinusOne] -> measurement computations can be triggered now!
int dataPacketSize = data.wireEncode().size();
int interestDelay = this->computeInterestDelay(keyMinusOne);
int dataDelay = this->computeDataDelay(keyMinusOne);
int firstRTT = this->computeRTT(keyMinusOne, true);
int secondRTT = this->computeRTT(keyMinusOne, false);
double quotient = this->interestDataQuotient((double) dataDelay, interestDelay);
double classicBW = this->computeClassicBW(secondRTT, dataPacketSize);
double throughput = this->throughputEstimation(dataDelay, dataPacketSize);
double sampledTp = 0.0;
//SEPERATION: chunks at the beginning of a segment download may not have viable values
// AND out of order reception data delays also no viable values
// AND firstRTT must not be 0 because then, the dummy value in the timestamp vector is used (= the data delay is not viable)
//only consider values bigger 0.1
if(isValidMeasurement(throughput, firstRTT, dataDelay) && !initChunk)
sampledTp = this->getSampledThroughput(throughput);
else
this->writeLogFile("Invalid computation.\n");
//logging start
std::stringstream loggingString;
loggingString << "I-Delay: " << interestDelay << "\t" << "D-Delay: " << dataDelay << "\t"
<< "First RTT: " << firstRTT << "\t" << "Second RTT: " << secondRTT << "\t"
<< "Classic BW: " << classicBW << "\t" << "gOut/gIn: " << quotient << "\t" << "Throughput: " << throughput << "\n";
this->writeLogFile(loggingString.str());
if(sampleNumber==0 && sampledTp != 0.0)
{
std::stringstream sampleString;
sampleString << sampleSize << "-Sampled Throughput: " << sampledTp << "\n";
this->writeLogFile(sampleString.str());
}
//logging end
this->lastDataKey = key;
return throughput; //unsampled
}
}
catch (const std::out_of_range& oor) {
std::cout << "Out of range error: " << oor.what() << std::endl;
}
}
bool ChunktimeObserver::isValidMeasurement(double throughput, int firstRTT, int dataDelay)
{
return dataDelay > 0 && firstRTT > 0 && throughput > 0.1;
}
double ChunktimeObserver::getSampledThroughput(double throughput) //sampling: harmonic avg over n throughput computations (n is set in the contructor)
{
this->cumulativeTp = this->cumulativeTp + (1/throughput);
sampleNumber++;
if(this->sampleNumber == this->sampleSize)
{
double sampledThroughput = this->sampleNumber / this->cumulativeTp; // harmonic avg = n/(sum of inverses)
this->sampleNumber = 0;
this->cumulativeTp = 0.0;
double convertedThroughput = sampledThroughput * 1000000; //convertation from Mbit/s to Bit/s
signalThroughputToDASHReceiver((uint64_t)convertedThroughput); //trigger notification-function in DASHReceiver
return sampledThroughput;
}
else
return 0; //not enough samples yet
}
//******************************************************************************************
//**********************************COMPUTATION FORMULAS************************************
//******************************************************************************************
int ChunktimeObserver::computeInterestDelay(std::string key) //in µs (timeI2 - timeI1)
{
return boost::chrono::duration_cast<boost::chrono::microseconds>(timingMap.at(key).at(1) - timingMap.at(key).at(0)).count();
}
int ChunktimeObserver::computeDataDelay(std::string key) //in µs (timeD2 - timeD1)
{
return boost::chrono::duration_cast<boost::chrono::microseconds>(timingMap.at(key).at(3) - timingMap.at(key).at(2)).count();
}
int ChunktimeObserver::computeRTT(std::string key, bool first) //in µs (first = timeD1 - timeI1, !first = timeD2 - timeI2)
{
if(first)
return boost::chrono::duration_cast<boost::chrono::microseconds>(timingMap.at(key).at(2) - timingMap.at(key).at(0)).count();
else
return boost::chrono::duration_cast<boost::chrono::microseconds>(timingMap.at(key).at(3) - timingMap.at(key).at(1)).count();
}
double ChunktimeObserver::computeClassicBW(int rtt, int size) //in MBit/s
{
return (double) (size*8)/(rtt/2);
}
double ChunktimeObserver::throughputEstimation(int gap, int size) //in Bit/µs = Mbit/s
{
if(gap != 0)
return (double) (size*8)/gap;
else
{
//this->writeLogFile("### Throughput Estimation: \t Data packet delay is 0 µs. DIV by ZERO! -> Throughput=0 ### \n");
//return 0.0;
this->writeLogFile("### Throughput Estimation: \t Data packet delay is 0 µs. DIV by ZERO! -> Data delay set to min=1 ### \n");
return (double) (size*8)/(gap+1);
}
}
double ChunktimeObserver::interestDataQuotient(double gIn, int gOut)
{
if(gIn != 0)
return gOut/gIn;
else
{
//this->writeLogFile("### Interest-Data-Quotient: \t Data packet delay is 0 µs. DIV by ZERO! -> Quotient=0 ### \n");
//return 0.0;
this->writeLogFile("### Interest-Data-Quotient: \t Data packet delay is 0 µs. DIV by ZERO! -> Data delay set to min=1 ### \n");
return gOut/gIn;
}
}
/*
int ChunktimeObserver::interestDataGap(int gIn, int gOut)
{
return gIn - gOut;
}
double ChunktimeObserver::gapResponseCurve(int gIn, int gOut)
{
double div = gOut / gIn;
if(div <= 1.0)
return 1.0;
else
return 0.0; //dummy
}
*/
| 15,350 | 42.120787 | 177 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/data-path.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Luca Muscariello <[email protected]>
* @author Zeng Xuan <[email protected]>
* @author Mauro Sardara <[email protected]>
* @author Michele Papalini <[email protected]>
*
*/
#include <sys/time.h>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#define TIMEOUT_SMOOTHER 0.1
#define TIMEOUT_RATIO 10
#define ALPHA 0.8
namespace ndn {
class DataPath
{
public:
DataPath(double drop_factor,
double p_min,
unsigned new_timer,
unsigned int samples,
uint64_t new_rtt = 1000,
uint64_t new_rtt_min = 1000,
uint64_t new_rtt_max = 1000);
public:
/*
* @brief Print Path Status
*/
void
pathReporter();
/*
* @brief Add a new RTT to the RTT queue of the path, check if RTT queue is full, and thus need overwrite.
* Also it maintains the validity of min and max of RTT.
* @param new_rtt is the value of the new RTT
*/
void
insertNewRtt(double new_rtt, double winSize, double *averageThroughput);
/**
* @brief Update the path statistics
* @param packet_size the size of the packet received, including the ICN header
* @param data_size the size of the data received, without the ICN header
*/
void
updateReceivedStats(std::size_t packet_size, std::size_t data_size);
/**
* @brief Get the value of the drop factor parameter
*/
double
getDropFactor();
/**
* @brief Get the value of the drop probability
*/
double
getDropProb();
/**
* @brief Set the value pf the drop probability
* @param drop_prob is the value of the drop probability
*/
void
setDropProb(double drop_prob);
/**
* @brief Get the minimum drop probability
*/
double
getPMin();
/**
* @brief Get last RTT
*/
double
getRtt();
/**
* @brief Get average RTT
*/
double
getAverageRtt();
/**
* @brief Get the current m_timer value
*/
double
getTimer();
/**
* @brief Smooth he value of the m_timer accordingly with the last RTT measured
*/
void
smoothTimer();
/**
* @brief Get the maximum RTT among the last samples
*/
double
getRttMax();
/**
* @brief Get the minimum RTT among the last samples
*/
double
getRttMin();
/**
* @brief Get the number of saved samples
*/
unsigned
getSampleValue();
/**
* @brief Get the size og the RTT queue
*/
unsigned
getRttQueueSize();
/*
* @brief Change drop probability according to RTT statistics
* Invoked in RAAQM(), before control window size update.
*/
void
updateDropProb();
/**
* @brief This function convert the time from struct timeval to its value in microseconds
*/
static double getMicroSeconds(struct timeval time);
void setAlpha(double alpha);
private:
/**
* The value of the drop factor
*/
double m_dropFactor;
/**
* The minumum drop probability
*/
double m_pMin;
/**
* The timer, expressed in milliseconds
*/
double m_timer;
/**
* The number of samples to store for computing the protocol measurements
*/
const unsigned int m_samples;
/**
* The last, the minimum and the maximum value of the RTT (among the last m_samples samples)
*/
double m_rtt, m_rttMin, m_rttMax;
/**
* The current drop probability
*/
double m_dropProb;
/**
* The number of packets received in this path
*/
intmax_t m_packetsReceived;
/**
* The first packet received after the statistics print
*/
intmax_t m_lastPacketsReceived;
/**
* Total number of bytes received including the ICN header
*/
intmax_t m_packetsBytesReceived;
/**
* The amount of packet bytes received at the last path summary computation
*/
intmax_t m_lastPacketsBytesReceived;
/**
* Total number of bytes received without including the ICN header
*/
intmax_t m_rawDataBytesReceived;
/**
* The amount of raw dat bytes received at the last path summary computation
*/
intmax_t m_lastRawDataBytesReceived;
class byArrival;
class byOrder;
/**
* Double ended queue for the RTTs
*/
typedef boost::multi_index_container
<
unsigned,
boost::multi_index::indexed_by<
// by arrival (FIFO)
boost::multi_index::sequenced<boost::multi_index::tag<byArrival> >,
// index by ascending order
boost::multi_index::ordered_non_unique<
boost::multi_index::tag<byOrder>,
boost::multi_index::identity<unsigned>
>
>
> RTTQueue;
RTTQueue m_rttSamples;
/**
* Time of the last call to the path reporter method
*/
struct timeval m_previousCallOfPathReporter;
double m_averageRtt;
double m_alpha;
};
} // namespace ndn
| 6,140 | 22.619231 | 110 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/pending-interest.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Luca Muscariello <[email protected]>
* @author Zeng Xuan <[email protected]>
* @author Mauro Sardara <[email protected]>
* @author Michele Papalini <[email protected]>
*
*/
#include <ctime>
#include <ndn-cxx/data.hpp>
namespace ndn {
class PendingInterest
{
public:
PendingInterest();
/**
* @brief Get the send time of the interest
*/
const timeval &
getSendTime();
/**
* @brief Set the send time of the interest
*/
PendingInterest
setSendTime(const timeval &now);
/**
* @brief Get the size of the data without considering the ICN header
*/
std::size_t
getRawDataSize();
/**
* @brief Get the size of the data packet considering the ICN header
*/
std::size_t
getPacketSize();
/**
* @brief True means that the data addressed by this pending interest has been received
*/
PendingInterest
markAsReceived(bool val);
/**
* @brief If the data has been received returns true, otherwise returns false
*/
bool
checkIfDataIsReceived();
/**
* @brief Temporarily store here the out of order data received
* @param data The data corresponding to this pending interest
*/
PendingInterest
addRawData(const Data &data);
/**
* @brieg Get the raw data block
*/
const char *
getRawData();
/**
* @brief Free the memory occupied by the raw data block
*/
PendingInterest
removeRawData();
/**
* @brief Get the number of times this interest has been retransmitted
*/
unsigned int
getRetxCount();
/**
* @brief Increase the number of retransmission of this packet
*/
PendingInterest
increaseRetxCount();
private:
/**
* The buffer storing the raw data received out of order
*/
unsigned char *m_rawData;
/**
* The size of the raw data buffer
*/
std::size_t m_rawDataSize;
/**
* The size of the whole packet, including the ICN header
*/
std::size_t m_packetSize;
/**
* True means that the data has been received.
*/
bool m_isReceived;
/**
* Delivering time of this interest
*/
struct timeval m_sendTime;
private:
/**
* Counter of the number of retransmissions of this interest
*/
unsigned int m_retxCount;
}; // end class PendingInterests
} // end namespace ndn
| 3,439 | 23.397163 | 91 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/chunktimeObserver.hpp
|
/*
* Timing of NDN Interest packets and NDN Data packets while downloading.
*/
#ifndef CHUNKTIME_OBSERVER_H
#define CHUNKTIME_OBSERVER_H
#include <ndn-cxx/interest.hpp>
#include <ndn-cxx/data.hpp>
#include <map>
#include <vector>
#include <boost/chrono/include.hpp>
#include <string>
#include <boost/signals2.hpp>
class ChunktimeObserver
{
public:
ChunktimeObserver(int samples);
~ChunktimeObserver();
/**
* Used signal to trigger DASHReceiver-Function (notifybpsChunk and context) from ChunktimeObserver
*/
typedef boost::signals2::signal<void (uint64_t)>::slot_type ThroughputNotificationSlot;
typedef boost::signals2::signal<void (uint64_t, uint64_t)>::slot_type ContextNotificationSlot;
void addThroughputSignal(ThroughputNotificationSlot slot);
void addContextSignal(ContextNotificationSlot slot);
/**
* Used to log the timing measurements seperately.
*/
void writeLogFile(const std::string szString);
/**
* Insert the timestamps of the sent Interest into the map.
*/
void onInterestSent(const ndn::Interest &interest);
/**
* Insert the timestamps of the received Data packet into the map.
@return (double) the measured throughput OR "0.0" when only 1 Data packet is received yet (-> no Data Delay computation possible) in MBit/s !
*/
double onDataReceived(const ndn::Data &data);
private:
//Signal triggering the NotifybpsChunk-Function in DASHReceiver
boost::signals2::signal<void(uint64_t)> signalThroughputToDASHReceiver;
boost::signals2::signal<void(uint64_t, uint64_t)> signalContextToDASHReceiver;
// map< key, vector< timeI1, timeI2, timeD1, timeD2 > >
std::map<std::string, std::vector<boost::chrono::time_point<boost::chrono::system_clock>>> timingMap;
// Some magic to get the key from the last element if we can not compute it.
std::string lastInterestKey;
std::string lastDataKey;
//for sampling over chunk throughput measurements
int sampleSize;
int sampleNumber;
double cumulativeTp;
//for logging
FILE* pFile;
boost::chrono::time_point<boost::chrono::system_clock> startTime;
/**
* @param samplesize, throughput
* @eturn (double) avg throughput over samplesize OR 0.0 (if not enough samples gathered yet)
*/
double getSampledThroughput(double throughput);
/**
* @param the string build from the last data packet
* @eturn (int) delay between two consecutive Interests (in microseconds µs)
*/
int computeInterestDelay(std::string key);
/**
* @param (string) the key built from the last data packet
* @eturn (int) delay between two consecutive Data packets (in microseconds µs)
*/
int computeDataDelay(std::string key);
/**
* @param (string) the key built from the last data packet, (bool) if the first Interest-Data pair is wanted (true) or the second pair (false)
* @eturn (int) delay between two consecutive Data packets (in microseconds µs)
*/
int computeRTT(std::string key, bool first);
/**
* @param (string) the rtt in µs, (int) the datasize in Byte
* @eturn (double) computed BW with the formula [datasize/(rount-trip time/2)] (in Bit/µs = MBit/s)
*/
double computeClassicBW(int rtt, int size);
/**
* @param (int) the gap between two consecutive Data packets in µs, (int) the datasize in Byte
* @eturn (double) computed throughput with the formula [datasize/gap] (in Bit/µs = MBit/s)
*/
double throughputEstimation(int gap, int size);
/**
* @param (int) gap between two consecutive Data packets (incoming), (int) gap between two consecutive Interest packets (outgoing)
* @return (double)
*/
double interestDataQuotient(double gIn, int gOut);
bool isValidMeasurement(double throughput, int firstRTT, int dataDelay);
//implement when needed
int interestDataGap(int gIn, int gOut);
double gapResponseCurve(int gIn, int gOut);
};//end class ChunktimeObserver
#endif //CHUNKTIME_OBSERVER_H
| 4,164 | 32.055556 | 155 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/pending-interest.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Luca Muscariello <[email protected]>
* @author Zeng Xuan <[email protected]>
* @author Mauro Sardara <[email protected]>
* @author Michele Papalini <[email protected]>
*
*/
#include "pending-interest.hpp"
namespace ndn {
PendingInterest::PendingInterest()
: m_rawData(NULL)
, m_rawDataSize(0)
, m_packetSize(0)
, m_isReceived(false)
, m_retxCount(0)
{
}
const timeval &
PendingInterest::getSendTime()
{
return m_sendTime;
}
PendingInterest
PendingInterest::setSendTime(const timeval &now)
{
m_sendTime.tv_sec = now.tv_sec;
m_sendTime.tv_usec = now.tv_usec;
return *this;
}
std::size_t
PendingInterest::getRawDataSize()
{
return m_rawDataSize;
}
std::size_t
PendingInterest::getPacketSize()
{
return m_packetSize;
}
unsigned int
PendingInterest::getRetxCount()
{
return m_retxCount;
}
PendingInterest
PendingInterest::increaseRetxCount()
{
m_retxCount++;
return *this;
}
PendingInterest
PendingInterest::markAsReceived(bool val)
{
m_isReceived = val;
return *this;
}
bool
PendingInterest::checkIfDataIsReceived()
{
return m_isReceived;
}
PendingInterest
PendingInterest::addRawData(const Data &data)
{
if (m_rawData != NULL)
removeRawData();
const Block &content = data.getContent();
m_rawDataSize = content.value_size();
m_packetSize = data.wireEncode().size();
m_rawData = (unsigned char *) malloc(m_rawDataSize);
memcpy(m_rawData,
reinterpret_cast<const char *>(content.value()),
content.value_size());
return *this;
}
const char *
PendingInterest::getRawData()
{
if (m_rawData != NULL)
return reinterpret_cast<const char *>(m_rawData);
else
return nullptr;
}
PendingInterest
PendingInterest::removeRawData()
{
if (m_rawData != NULL)
{
free(m_rawData);
m_rawData = NULL;
m_rawDataSize = 0;
m_packetSize = 0;
}
return *this;
}
} // namespace ndn
| 2,977 | 21.059259 | 90 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/data-path.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Luca Muscariello <[email protected]>
* @author Zeng Xuan <[email protected]>
* @author Mauro Sardara <[email protected]>
* @author Michele Papalini <[email protected]>
*
*/
#include "data-path.hpp"
namespace ndn {
DataPath::DataPath(double drop_factor,
double p_min,
unsigned new_timer,
unsigned int samples,
uint64_t new_rtt,
uint64_t new_rtt_min,
uint64_t new_rtt_max)
: m_dropFactor(drop_factor)
, m_pMin(p_min)
, m_timer(new_timer)
, m_samples(samples)
, m_rtt(new_rtt)
, m_rttMin(new_rtt_min)
, m_rttMax(new_rtt_max)
, m_dropProb(0)
, m_packetsReceived(0)
, m_lastPacketsReceived(0)
, m_packetsBytesReceived(0)
, m_lastPacketsBytesReceived(0)
, m_rawDataBytesReceived(0)
, m_lastRawDataBytesReceived(0)
, m_averageRtt(0)
, m_alpha(ALPHA)
{
gettimeofday(&m_previousCallOfPathReporter, 0);
}
void
DataPath::pathReporter()
{
struct timeval now;
gettimeofday(&now, 0);
double rate, delta_t;
delta_t = getMicroSeconds(now) - getMicroSeconds(m_previousCallOfPathReporter);
rate = (m_packetsBytesReceived - m_lastPacketsBytesReceived) * 8 / delta_t; // MB/s
std::cout << "DataPath status report: "
<< "at time " << (long) now.tv_sec << "." << (unsigned) now.tv_usec << " sec:\n"
<< (void *) this << " path\n"
<< "Packets Received: " << (m_packetsReceived - m_lastPacketsReceived) << "\n"
<< "delta_t " << delta_t << " [us]\n"
<< "rate " << rate << " [Mbps]\n"
<< "Last RTT " << m_rtt << " [us]\n"
<< "RTT_max " << m_rttMax << " [us]\n"
<< "RTT_min " << m_rttMin << " [us]\n" << std::endl;
m_lastPacketsReceived = m_packetsReceived;
m_lastPacketsBytesReceived = m_packetsBytesReceived;
gettimeofday(&m_previousCallOfPathReporter, 0);
}
void
DataPath::insertNewRtt(double new_rtt, double winSize, double *averageThroughput)
{
if(winSize)
{
if(*averageThroughput == 0)
*averageThroughput = winSize / new_rtt;
*averageThroughput = m_alpha * *averageThroughput + (1 - m_alpha) * (winSize / new_rtt);
}
//if(m_averageRtt == 0)
// m_averageRtt = new_rtt;
//m_averageRtt = m_alpha * m_averageRtt + (1 - m_alpha) * new_rtt; // not really promising measurement
m_rtt = new_rtt;
m_rttSamples.get<byArrival>().push_back(new_rtt);
if (m_rttSamples.get<byArrival>().size() > m_samples)
m_rttSamples.get<byArrival>().pop_front();
m_rttMax = *(m_rttSamples.get<byOrder>().rbegin());
m_rttMin = *(m_rttSamples.get<byOrder>().begin());
}
void
DataPath::updateReceivedStats(std::size_t packet_size, std::size_t data_size)
{
m_packetsReceived++;
m_packetsBytesReceived += packet_size;
m_rawDataBytesReceived += data_size;
}
double
DataPath::getDropFactor()
{
return m_dropFactor;
}
double
DataPath::getDropProb()
{
return m_dropProb;
}
void
DataPath::setDropProb(double dropProb)
{
m_dropProb = dropProb;
}
double
DataPath::getPMin()
{
return m_pMin;
}
double
DataPath::getTimer()
{
return m_timer;
}
void
DataPath::smoothTimer()
{
m_timer = (1 - TIMEOUT_SMOOTHER) * m_timer + (TIMEOUT_SMOOTHER) * m_rtt * (TIMEOUT_RATIO);
}
double
DataPath::getRtt()
{
return m_rtt;
}
double
DataPath::getAverageRtt()
{
return m_averageRtt;
}
double
DataPath::getRttMax()
{
return m_rttMax;
}
double
DataPath::getRttMin()
{
return m_rttMin;
}
unsigned
DataPath::getSampleValue()
{
return m_samples;
}
unsigned
DataPath::getRttQueueSize()
{
return m_rttSamples.get<byArrival>().size();
}
void
DataPath::updateDropProb()
{
m_dropProb = 0.0;
if (getSampleValue() == getRttQueueSize()) {
if (m_rttMax == m_rttMin)
m_dropProb = m_pMin;
else
m_dropProb = m_pMin + m_dropFactor * (m_rtt - m_rttMin) / (m_rttMax - m_rttMin);
}
}
double
DataPath::getMicroSeconds(struct timeval time)
{
return (double) (time.tv_sec) * 1000000 + (double) (time.tv_usec);
}
void
DataPath::setAlpha(double alpha)
{
if(alpha >= 0 && alpha <= 1)
m_alpha = alpha;
}
} // namespace ndn
| 5,257 | 23.342593 | 106 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/rate-estimation.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Jacques Samain <[email protected]>
*/
#include "rate-estimation.hpp"
namespace ndn {
Variables::Variables () :
alpha(0.0),
avgWin(0.0),
avgRtt(0.0),
rtt(0.0),
instantaneousThroughput(0.0),
winChange(0.0),
batchingStatus(0),
isRunning(false),
winCurrent(0.0),
isBusy(false)
{}
void* Timer(void* data)
{
Variables * m_variables = (Variables*) data;
double datRtt, myAvgWin, myAvgRtt;
int myWinChange, myBatchingParam, maxPacketSize;
timeval now;
while(m_variables->isBusy)
{}
m_variables->isBusy = true;
datRtt = m_variables->rtt;
m_variables->isBusy = false;
while(m_variables->isRunning)
{
usleep(KV * datRtt);
while(m_variables->isBusy)
{}
m_variables->isBusy = true;
datRtt = m_variables->rtt;
myAvgWin = m_variables->avgWin;
myAvgRtt = m_variables->avgRtt;
myWinChange = m_variables->winChange;
myBatchingParam = m_variables->batchingStatus;
maxPacketSize = m_variables->maxPacketSize;
m_variables->avgRtt = m_variables->rtt;
m_variables->avgWin = 0;
m_variables->winChange = 0;
m_variables->batchingStatus = 1;
m_variables->isBusy = false;
if(myBatchingParam == 0 || myWinChange == 0)
continue;
if(m_variables->instantaneousThroughput == 0)
m_variables->instantaneousThroughput = (myAvgWin * 8.0 * maxPacketSize * 1000000.0 / (1.0 * myWinChange)) / (myAvgRtt / (1.0 * myBatchingParam));
m_variables->instantaneousThroughput = m_variables->alpha * m_variables->instantaneousThroughput + (1 - m_variables->alpha) * ( (myAvgWin * 8.0 * maxPacketSize * 1000000.0 / (1.0 * myWinChange)) / (myAvgRtt / (1.0 * myBatchingParam) ) );
gettimeofday(&now, 0);
// printf("time: %f instantaneous: %f\n", DataPath::getMicroSeconds(now), m_variables->instantaneousThroughput);
// fflush(stdout);
}
}
InterRttEstimator::InterRttEstimator(Variables *var)
{
this->m_variables = var;
this->ThreadisRunning = false;
this->myTh = NULL;
gettimeofday(&(this->m_variables->begin), 0);
}
void InterRttEstimator::onRttUpdate(double rtt) {
while(m_variables->isBusy)
{}
m_variables->isBusy = true;
m_variables->rtt = rtt;
m_variables->batchingStatus++;
m_variables->avgRtt += rtt;
m_variables->isBusy = false;
if(!ThreadisRunning)
{
myTh = (pthread_t*)malloc(sizeof(pthread_t));
if (!myTh)
{
std::cerr << "Error allocating thread." << std::endl;
myTh = NULL;
}
if(int err = pthread_create(myTh, NULL, ndn::Timer, (void*)this->m_variables))
{
std::cerr << "Error creating the thread" << std::endl;
myTh = NULL;
}
ThreadisRunning = true;
}
}
void InterRttEstimator::onWindowIncrease(double winCurrent) {
timeval end;
gettimeofday(&end, 0);
double delay = DataPath::getMicroSeconds(end) - DataPath::getMicroSeconds(this->m_variables->begin);
while(m_variables->isBusy)
{}
m_variables->isBusy = true;
m_variables->avgWin += this->m_variables->winCurrent * delay;
m_variables->winCurrent = winCurrent;
m_variables->winChange += delay;
m_variables->isBusy = false;
gettimeofday(&(this->m_variables->begin), 0);
}
void InterRttEstimator::onWindowDecrease(double winCurrent) {
timeval end;
gettimeofday(&end, 0);
double delay = DataPath::getMicroSeconds(end) - DataPath::getMicroSeconds(this->m_variables->begin);
while(m_variables->isBusy)
{}
m_variables->isBusy = true;
m_variables->avgWin += this->m_variables->winCurrent * delay;
m_variables->winCurrent = winCurrent;
m_variables->winChange += delay;
m_variables->isBusy = false;
gettimeofday(&(this->m_variables->begin), 0);
}
SimpleEstimator::SimpleEstimator(Variables *var, int param)
{
this->m_variables = var;
this->batchingParam = param;
gettimeofday(&(this->m_variables->begin), 0);
}
void SimpleEstimator::onDataReceived(int packetSize)
{
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
this->m_variables->avgWin += packetSize;
this->m_variables->isBusy = false;
}
void SimpleEstimator::onRttUpdate(double rtt)
{
int nbrOfPackets = 0;
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
this->m_variables->batchingStatus++;
nbrOfPackets = this->m_variables->batchingStatus;
this->m_variables->isBusy = false;
if(nbrOfPackets == this->batchingParam)
{
timeval end;
gettimeofday(&end, 0);
double delay = DataPath::getMicroSeconds(end) - DataPath::getMicroSeconds(this->m_variables->begin);
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
float inst = this->m_variables->instantaneousThroughput;
double alpha = this->m_variables->alpha;
int maxPacketSize = this->m_variables->maxPacketSize;
double sizeTotal = this->m_variables->avgWin; //Here we use avgWin to store the total size downloaded during the time span of nbrOfPackets
this->m_variables->isBusy = false;
//Assuming all packets carry maxPacketSize bytes of data (8*maxPacketSize bits); 1000000 factor to convert us to seconds
if(inst)
{
inst = alpha * inst + (1 - alpha) * (sizeTotal * 8 * 1000000.0 / (delay));
}
else
inst = sizeTotal * 8 * 1000000.0 / (delay);
timeval now;
gettimeofday(&now, 0);
//printf("time: %f, instantaneous: %f\n", DataPath::getMicroSeconds(now), inst);
//fflush(stdout);
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
this->m_variables->batchingStatus = 0;
this->m_variables->instantaneousThroughput = inst;
this->m_variables->avgWin = 0.0;
this->m_variables->isBusy = false;
gettimeofday(&(this->m_variables->begin),0);
}
}
BatchingPacketsEstimator::BatchingPacketsEstimator(Variables *var, int param)
{
this->m_variables = var;
this->batchingParam = param;
gettimeofday(&(this->m_variables->begin), 0);
}
void BatchingPacketsEstimator::onRttUpdate(double rtt)
{
int nbrOfPackets = 0;
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
this->m_variables->batchingStatus++;
this->m_variables->avgRtt += rtt;
nbrOfPackets = this->m_variables->batchingStatus;
this->m_variables->isBusy = false;
if(nbrOfPackets == this->batchingParam)
{
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
double inst = this->m_variables->instantaneousThroughput;
double alpha = this->m_variables->alpha;
double myAvgWin = m_variables->avgWin;
double myAvgRtt = m_variables->avgRtt;
double myWinChange = m_variables->winChange;
int maxPacketSize = m_variables->maxPacketSize;
this->m_variables->isBusy = false;
if(inst == 0)
inst = (myAvgWin * 8.0 * maxPacketSize * 1000000.0 / (1.0 * myWinChange)) / (myAvgRtt / (1.0 * nbrOfPackets));
else
inst = alpha * inst + (1 - alpha) * ((myAvgWin * 8.0 * maxPacketSize * 1000000.0 / (1.0 * myWinChange)) / (myAvgRtt / (1.0 * nbrOfPackets)));
timeval now;
gettimeofday(&now, 0);
//printf("time: %f, instantaneous: %f\n", DataPath::getMicroSeconds(now), inst);
//fflush(stdout);
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
this->m_variables->batchingStatus = 0;
this->m_variables->avgWin = 0;
this->m_variables->avgRtt = 0;
this->m_variables->winChange = 0;
this->m_variables->instantaneousThroughput = inst;
this->m_variables->isBusy = false;
}
}
void BatchingPacketsEstimator::onWindowIncrease(double winCurrent) {
timeval end;
gettimeofday(&end, 0);
double delay = DataPath::getMicroSeconds(end) - DataPath::getMicroSeconds(this->m_variables->begin);
while(m_variables->isBusy)
{}
m_variables->isBusy = true;
m_variables->avgWin += this->m_variables->winCurrent * delay;
m_variables->winCurrent = winCurrent;
m_variables->winChange += delay;
m_variables->isBusy = false;
gettimeofday(&(this->m_variables->begin), 0);
}
void BatchingPacketsEstimator::onWindowDecrease(double winCurrent) {
timeval end;
gettimeofday(&end, 0);
double delay = DataPath::getMicroSeconds(end) - DataPath::getMicroSeconds(this->m_variables->begin);
while(m_variables->isBusy)
{}
m_variables->isBusy = true;
m_variables->avgWin += this->m_variables->winCurrent * delay;
m_variables->winCurrent = winCurrent;
m_variables->winChange += delay;
m_variables->isBusy = false;
gettimeofday(&(this->m_variables->begin), 0);
}
}
| 10,083 | 32.280528 | 254 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/ndn-icp-download.cpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Luca Muscariello <[email protected]>
* @author Zeng Xuan <[email protected]>
* @author Mauro Sardara <[email protected]>
* @author Michele Papalini <[email protected]>
*
*/
#include "ndn-icp-download.hpp"
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/chrono/include.hpp>
#include <math.h>
#include "log/log.h"
#include <map> //for mapping the starttime to the name
#define BOOST_THREAD_PROVIDES_FUTURE
#include <boost/thread.hpp>
#include <boost/thread/future.hpp>
namespace ndn {
NdnIcpDownload::NdnIcpDownload(unsigned int pipe_size,
unsigned int initial_window,
unsigned int gamma,
double beta,
bool allowStale,
unsigned int lifetime_ms)
: m_unversioned(false)
, m_maxWindow(pipe_size)
, m_pMin(P_MIN)
, m_finalChunk(UINT_MAX)
, m_samples(SAMPLES)
, m_gamma(gamma)
, m_beta(beta)
, m_allowStale(allowStale)
, m_defaulInterestLifeTime(time::milliseconds(lifetime_ms))
, m_isOutputEnabled(false)
, m_isPathReportEnabled(false)
, m_winPending(0)
, m_winCurrent(initial_window)
, m_initialWindow(initial_window)
, m_firstInFlight(0)
, m_outOfOrderCount(0)
, m_nextPendingInterest(0)
, m_finalSlot(UINT_MAX)
, m_interestsSent(0)
, m_packetsDelivered(0)
, m_rawBytesDataDelivered(0)
, m_bytesDataDelivered(0)
, m_isAbortModeEnabled(false)
, m_winRetransmissions(0)
, m_downloadCompleted(false)
, m_retxLimit(0)
, m_isSending(false)
, m_nTimeouts(0)
, m_curPath(nullptr)
, m_statistics(true)
, m_observed(false)
, c_observed(false)
, m_averageWin(initial_window)
, m_set_interest_filter(false)
, m_observer(NULL)
, c_observer(NULL)
, maxPacketSize(0) {
this->m_variables = new Variables();
m_variables->alpha = ALPHA;
m_variables->avgWin = 0.0;
m_variables->avgRtt = 0.0;
m_variables->rtt = 0.0;
m_variables->instantaneousThroughput = 0.0;
m_variables->winChange = 0;
m_variables->batchingStatus = 0;
m_variables->isRunning = true;
m_variables->isBusy = false;
m_variables->maxPacketSize;
windowFile = fopen ("/cwindow","w");
//this->ndnIcpDownloadRateEstimator = new InterRttEstimator(this->m_variables);
this->ndnIcpDownloadRateEstimator = new SimpleEstimator(this->m_variables, BATCH);
//this->ndnIcpDownloadRateEstimator = new BatchingPacketsEstimator(this->m_variables, BATCH);
m_dataName = Name();
srand(std::time(NULL));
std::cout << "reception buffer size #" << RECEPTION_BUFFER << std::endl;
}
void NdnIcpDownload::addObserver(NdnIcpDownloadObserver* obs)
{
this->m_observer = obs;
this->m_observed = true;
}
void NdnIcpDownload::addObserver(ChunktimeObserver* obs)
{
this->c_observer = obs;
this->c_observed = true;
}
void NdnIcpDownload::setAlpha(double alpha)
{
if(alpha >= 0 && alpha <= 1)
m_variables->alpha = alpha;
}
void
NdnIcpDownload::setCurrentPath(shared_ptr<DataPath> path)
{
m_curPath = path;
m_savedPath = path;
}
void
NdnIcpDownload::setStatistics(bool value)
{
m_statistics = value;
}
void
NdnIcpDownload::setUnversioned(bool value)
{
m_unversioned = value;
}
void
NdnIcpDownload::setMaxRetries(unsigned max_retries)
{
m_retxLimit = max_retries;
}
void
NdnIcpDownload::insertToPathTable(std::string key, shared_ptr<DataPath> path)
{
if (m_pathTable.find(key) == m_pathTable.end()) {
m_pathTable[key] = path;
}
else {
std::cerr << "ERROR: failed to insert path to path table, the path entry already exists" << std::endl;
}
}
void
NdnIcpDownload::controlStatsReporter()
{
struct timeval now;
gettimeofday(&now, 0);
fprintf(stdout,
"[Control Stats Report]: "
"Time %ld.%06d [usec] ndn-icp-download: "
"Interests Sent: %ld, Received: %ld, Timeouts: %ld, "
"Current Window: %f, Interest pending (inside the window): %u, Interest Received (inside the window): %u, "
"Interest received out of order: %u\n",
(long) now.tv_sec,
(unsigned) now.tv_usec,
m_interestsSent,
m_packetsDelivered,
m_nTimeouts,
m_winCurrent,
m_winPending,
m_outOfOrderCount);
}
void
NdnIcpDownload::printSummary()
{
const char *expid;
const char *dlm = " ";
expid = getenv("NDN_EXPERIMENT_ID");
if (expid == NULL)
expid = dlm = "";
double elapsed = 0.0;
double rate = 0.0;
double goodput = 0.0;
gettimeofday(&m_stopTimeValue, 0);
elapsed = (double) (long) (m_stopTimeValue.tv_sec - m_startTimeValue.tv_sec);
elapsed += ((int) m_stopTimeValue.tv_usec - (int) m_startTimeValue.tv_usec) / 1000000.0;
if (elapsed > 0.00001) {
rate = m_bytesDataDelivered * 8 / elapsed / 1000000;
goodput = m_rawBytesDataDelivered * 8 / elapsed / 1000000;
}
fprintf(stdout,
"%ld.%06u ndn-icp-download[%d]: %s%s "
"%ld bytes transferred (filesize: %ld [bytes]) in %.6f seconds. "
"Rate: %6f [Mbps] Goodput: %6f [Mbps] Timeouts: %ld \n",
(long) m_stopTimeValue.tv_sec,
(unsigned) m_stopTimeValue.tv_usec,
(int) getpid(),
expid,
dlm,
m_bytesDataDelivered,
m_rawBytesDataDelivered,
elapsed,
rate,
goodput,
m_nTimeouts
);
if (m_isPathReportEnabled) {
// Print number of paths in the transmission process, excluding the default path
std::cout << "Number of paths in the path table: " <<
(m_pathTable.size() - 1) << std::endl;
int i = 0;
BOOST_FOREACH(HashTableForPath::value_type kv, m_pathTable) {
if (kv.first.length() <= 1) {
i++;
std::cout << "[Path " << i << "]\n" << "ID : " <<
(int) *(reinterpret_cast<const unsigned char *>(kv.first.data())) << "\n";
kv.second->pathReporter();
}
}
}
}
void
NdnIcpDownload::setLastTimeOutToNow()
{
gettimeofday(&m_lastTimeout, 0);
}
void
NdnIcpDownload::setStartTimeToNow()
{
gettimeofday(&m_startTimeValue, 0);
}
void
NdnIcpDownload::enableOutput()
{
m_isOutputEnabled = true;
}
void
NdnIcpDownload::enablePathReport()
{
m_isPathReportEnabled = true;
}
void
NdnIcpDownload::updateRTT(uint64_t slot)
{
if (!m_curPath)
throw std::runtime_error("ERROR: no current path found, exit");
else {
double rtt;
struct timeval now;
gettimeofday(&now, 0);
const timeval &sendTime = m_outOfOrderInterests[slot].getSendTime();
rtt = DataPath::getMicroSeconds(now) - DataPath::getMicroSeconds(sendTime);
ndnIcpDownloadRateEstimator->onRttUpdate(rtt);
m_curPath->insertNewRtt(rtt, m_winCurrent, &m_averageWin);
m_curPath->smoothTimer();
}
}
void
NdnIcpDownload::increaseWindow()
{
if ((unsigned) m_winCurrent < m_maxWindow)
m_winCurrent += (double) m_gamma/m_winCurrent;
//fprintf(pFile, "%6f\n", m_winCurrent);
ndnIcpDownloadRateEstimator->onWindowIncrease(m_winCurrent);
}
void
NdnIcpDownload::decreaseWindow()
{
m_winCurrent = m_winCurrent * m_beta;
if (m_winCurrent < m_initialWindow)
m_winCurrent = m_initialWindow;
//fprintf(pFile, "%6f\n", m_winCurrent);
ndnIcpDownloadRateEstimator->onWindowDecrease(m_winCurrent);
}
void
NdnIcpDownload::RAQM()
{
if (!m_curPath) {
std::cerr << "ERROR: no current path found, exit" << std::endl;
exit(EXIT_FAILURE);
}
else {
// Change drop probability according to RTT statistics
m_curPath->updateDropProb();
if (rand() % 10000 <= m_curPath->getDropProb() * 10000) //TODO, INFO this seems to cause low bw in docker setting, investigate
decreaseWindow();
}
}
void
NdnIcpDownload::afterDataReception(uint64_t slot)
{
// Update win counters
m_winPending--;
increaseWindow();
updateRTT(slot);
// Set drop probablility and window size accordingly
RAQM();
}
void
NdnIcpDownload::onData(const Data &data)
{
sec seconds = boost::chrono::nanoseconds(timer.elapsed().wall);
fprintf(windowFile, "%6f,%6f\n", seconds, m_winCurrent);
const ndn::name::Component &finalBlockId = data.getMetaInfo().getFinalBlockId();
if (finalBlockId.isSegment() && finalBlockId.toSegment() < this->m_finalChunk) {
this->m_finalChunk = finalBlockId.toSegment();
this->m_finalChunk++;
}
const Block &content = data.getContent();
const Name &name = data.getName();
std::string nameAsString = name.toUri();
int seq = name[-1].toSegment();
uint64_t slot = seq % RECEPTION_BUFFER;
size_t dataSize = content.value_size(); //= max. 1400 Bytes = 1.4 kB = 11200 Bits = 11.2 kBits
if(seq == (m_finalChunk -1))
this->m_downloadCompleted = true;
//check if we got a M-flaged interest for this data
NackSet::iterator it = m_nackSet.find(seq);
if(it != m_nackSet.end()){
m_nackSet.erase(it);
}
size_t packetSize = data.wireEncode().size();
ndnIcpDownloadRateEstimator->onDataReceived((int)packetSize);
if((int) packetSize > this->maxPacketSize)
{
this->maxPacketSize = (int)packetSize;
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
this->m_variables->maxPacketSize = this->maxPacketSize;
this->m_variables->isBusy = false;
}
if (m_isAbortModeEnabled) {
if (m_winRetransmissions > 0 && m_outOfOrderInterests[slot].getRetxCount() >= 2) // ??
m_winRetransmissions--;
}
if (m_isOutputEnabled) {
std::cout << "data received, seq number #" << seq << std::endl;
std::cout.write(reinterpret_cast<const char *>(content.value()), content.value_size());
}
GOT_HERE();
#ifdef PATH_LABELLING
ndn::Block pathIdBlock = data.getPathId();
if(pathIdBlock.empty())
{
std::cerr<< "[ERROR]: Path ID lost in the transmission.";
exit(EXIT_FAILURE);
}
unsigned char pathId = *(data.getPathId().value());
#else
unsigned char pathId = 0;
#endif
std::string pathIdString(1, pathId);
if (m_pathTable.find(pathIdString) == m_pathTable.end()) {
if (m_curPath) {
// Create a new path with some default param
if (m_pathTable.empty()) {
std::cerr << "No path initialized for path table, error could be in default path initialization." <<
std::endl;
exit(EXIT_FAILURE);
}
else {
// Initiate the new path default param
shared_ptr<DataPath> newPath = make_shared<DataPath>(*(m_pathTable.at(DEFAULT_PATH_ID)));
// Insert the new path into hash table
m_pathTable[pathIdString] = newPath;
}
}
else {
std::cerr << "UNEXPECTED ERROR: when running,current path not found." << std::endl;
exit(EXIT_FAILURE);
}
}
m_curPath = m_pathTable[pathIdString];
// Update measurements for path
m_curPath->updateReceivedStats(packetSize, dataSize);
unsigned int nextSlot = m_nextPendingInterest % RECEPTION_BUFFER;
if (nextSlot > m_firstInFlight && (slot > nextSlot || slot < m_firstInFlight)) {
std::cout << "out of window data received at # " << slot << std::endl;
return;
}
if (nextSlot < m_firstInFlight && (slot > nextSlot && slot < m_firstInFlight)) {
std::cout << "out of window data received at # " << slot << std::endl;
return;
}
if (seq == (m_finalChunk - 1)) {
m_finalSlot = slot;
GOT_HERE();
}
if (slot != m_firstInFlight) {
// Out of order data received, save it for later.
//std::cout << "out of order count " << m_outOfOrderCount << std::endl;
if (!m_outOfOrderInterests[slot].checkIfDataIsReceived()) {
GOT_HERE();
m_outOfOrderCount++; // todo Rename it
m_outOfOrderInterests[slot].addRawData(data);
m_outOfOrderInterests[slot].markAsReceived(true);
afterDataReception(slot);
if(c_observed)
this->speed_chunk = c_observer->onDataReceived(data);
if(m_observed)
{
if(this->speed_chunk > 0)
m_observer->notifyChunkStats(nameAsString, this->speed_chunk); // logging the throughput on chunk level
} else
std::cout<<"NOT OBSERVED! (M) \t";
}
}
else {
// In order data arrived
assert(!m_outOfOrderInterests[slot].checkIfDataIsReceived());
m_packetsDelivered++;
m_rawBytesDataDelivered += dataSize;
m_bytesDataDelivered += packetSize;
// Save data to the reception buffer
this->m_recBuffer->insert(m_recBuffer->end(),
reinterpret_cast<const char *>(content.value()),
reinterpret_cast<const char *>(content.value()) + content.value_size());
if(c_observed)
this->speed_chunk = c_observer->onDataReceived(data);
if(m_observed)
{
if(this->speed_chunk > 0)
m_observer->notifyChunkStats(nameAsString, this->speed_chunk); // logging the throughput on chunk level
} else
std::cout<<"NOT OBSERVED! (M) \t";
afterDataReception(slot);
slot = (slot + 1) % RECEPTION_BUFFER;
m_firstInFlight = slot;
if (slot >= m_finalSlot && m_outOfOrderCount == 0) {
m_face.removeAllPendingInterests();
m_winPending = 0;
return;
}
/*
* Consume out-of-order pkts already received until there is a hole
*/
while (m_outOfOrderCount > 0 && m_outOfOrderInterests[slot].checkIfDataIsReceived()) {
m_packetsDelivered++;
m_rawBytesDataDelivered += m_outOfOrderInterests[slot].getRawDataSize();
m_bytesDataDelivered += m_outOfOrderInterests[slot].getPacketSize();
this->m_recBuffer->insert(m_recBuffer->end(),
m_outOfOrderInterests[slot].getRawData(),
m_outOfOrderInterests[slot].getRawData() +
m_outOfOrderInterests[slot].getRawDataSize());
if (slot >= m_finalSlot) {
GOT_HERE();
m_face.removeAllPendingInterests();
m_winPending = 0;
m_outOfOrderInterests[slot].removeRawData();
m_outOfOrderInterests[slot].markAsReceived(false);
m_firstInFlight = (slot + 1) % RECEPTION_BUFFER;
m_outOfOrderCount--;
return;
}
m_outOfOrderInterests[slot].removeRawData();
m_outOfOrderInterests[slot].markAsReceived(false);
slot = (slot + 1) % RECEPTION_BUFFER;
m_firstInFlight = slot;
m_outOfOrderCount--;
}
}
boost::async(boost::bind(&ndn::NdnIcpDownload::scheduleNextPacket,this));
}
void
NdnIcpDownload::onInterest(const Interest &interest) {
bool mobility = false; //interest.get_MobilityLossFlag();
if(mobility){ //MLDR M-flaged interest
const Name &name = interest.getName();
uint64_t segment = name[-1].toSegment();
timeval now;
gettimeofday(&now, 0);
std::cout << (long) now.tv_sec << "." << (unsigned) now.tv_usec << " ndn-icp-download: M-Interest " <<
segment << " " << interest.getName() << "\n";
NackSet::iterator it = m_nackSet.find(segment);
if(it == m_nackSet.end()){
m_nackSet.insert(segment);
}
}
}
void
NdnIcpDownload::onNack(const Interest &nack){
timeval now;
gettimeofday(&now, 0);
std::cout << (long) now.tv_sec << "." << (unsigned) now.tv_usec << " ndn-icp-download: NACK " << nack.getName() << "\n";
boost::asio::io_service m_io;
boost::asio::deadline_timer t(m_io, boost::posix_time::seconds(1));
t.async_wait([=] (const boost::system::error_code e) {if (e != boost::asio::error::operation_aborted) onTimeout(nack);});
m_io.run();
}
void
NdnIcpDownload::scheduleNextPacket()
{
if (!m_dataName.empty() && m_winPending < (unsigned) m_winCurrent && m_nextPendingInterest < m_finalChunk && !m_isSending)
sendPacket();
//else(scheduleNextPacket());
}
void
NdnIcpDownload::sendPacket()
{
m_isSending = true;
uint64_t seq;
uint64_t slot;
seq = m_nextPendingInterest++;
slot = seq % RECEPTION_BUFFER;
assert(!m_outOfOrderInterests[slot].checkIfDataIsReceived());
struct timeval now;
gettimeofday(&now, 0);
m_outOfOrderInterests[slot].setSendTime(now).markAsReceived(false);
// Make a proper interest
Interest interest;
interest.setName(Name(m_dataName).appendSegment(seq));
interest.setInterestLifetime(m_defaulInterestLifeTime);
interest.setMustBeFresh(m_allowStale);
interest.setChildSelector(1);
m_face.expressInterest(interest,
bind(&NdnIcpDownload::onData, this, _2),
bind(&NdnIcpDownload::onNack, this, _1),
bind(&NdnIcpDownload::onTimeout, this, _1));
if(c_observed)
c_observer->onInterestSent(interest);
m_interestsSent++;
m_winPending++;
assert(m_outOfOrderCount < RECEPTION_BUFFER);
m_isSending = false;
scheduleNextPacket();
}
void
NdnIcpDownload::reInitialize()
{
m_finalChunk = UINT_MAX;
m_firstDataName.clear();
m_dataName.clear();
m_firstInFlight = 0;
m_outOfOrderCount = 0;
m_nextPendingInterest = 0;
m_finalSlot = UINT_MAX;
m_interestsSent = 0;
m_packetsDelivered = 0;
m_rawBytesDataDelivered = 0;
m_bytesDataDelivered = 0;
m_isAbortModeEnabled = false;
m_winRetransmissions = 0;
m_downloadCompleted = false;
m_retxLimit = 0;
m_isSending = false;
m_nTimeouts = 0;
m_variables->batchingStatus = 0;
m_variables->avgWin = 0;
}
void
NdnIcpDownload::resetRAAQM()
{
m_winPending = 0;
m_winCurrent = m_initialWindow;
m_averageWin = m_winCurrent;
m_curPath = m_savedPath;
m_pathTable.clear();
this->insertToPathTable(DEFAULT_PATH_ID, m_savedPath);
}
void
NdnIcpDownload::onTimeout(const Interest &interest)
{
if (!m_curPath) {
throw std::runtime_error("ERROR: when timed-out no current path found, exit");
}
const Name &name = interest.getName();
uint64_t timedOutSegment;
if (name[-1].isSegment())
timedOutSegment = name[-1].toSegment();
else
timedOutSegment = 0;
uint64_t slot = timedOutSegment % RECEPTION_BUFFER;
// Check if it the asked data exist
if (timedOutSegment >= m_finalChunk)
return;
// Check if data is received
if (m_outOfOrderInterests[slot].checkIfDataIsReceived())
return;
// Check whether we reached the retransmission limit
if (m_retxLimit != 0 && m_outOfOrderInterests[slot].getRetxCount() >= m_retxLimit)
throw std::runtime_error("ERROR: Download failed.");
NackSet::iterator it = m_nackSet.find(timedOutSegment);
if(it != m_nackSet.end()){
std::cout << "erase the nack from the list, do not decrease the window, seq: " << timedOutSegment << std::endl;
m_nackSet.erase(it);
}else{
//std::cout << "Decrease the window because the timeout happened" << timedOutSegment << std::endl;
decreaseWindow();
}
//m_outOfOrderInterests[slot].markAsReceived(false);
timeval now;
gettimeofday(&now, 0);
m_outOfOrderInterests[slot].setSendTime(now);
m_outOfOrderInterests[slot].markAsReceived(false);
if (m_isAbortModeEnabled) {
if (m_outOfOrderInterests[slot].getRetxCount() == 1)
m_winRetransmissions++;
if (m_winRetransmissions >= m_winCurrent)
throw std::runtime_error("Error: full window of interests timed out, application aborted");
}
// Retransmit the interest
Interest newInterest = interest;
// Since we made a copy, we need to refresh interest nonce otherwise it could be considered as a looped interest by NFD.
newInterest.refreshNonce();
newInterest.setInterestLifetime(m_defaulInterestLifeTime);
// Re-express interest
m_face.expressInterest(newInterest,
bind(&NdnIcpDownload::onData, this, _2),
bind(&NdnIcpDownload::onNack, this, _1),
bind(&NdnIcpDownload::onTimeout, this, _1));
m_outOfOrderInterests[slot].increaseRetxCount();
m_interestsSent++;
m_nTimeouts++;
gettimeofday(&m_lastTimeout, 0);
std::cout << (long) now.tv_sec << "." << (unsigned) now.tv_usec << " ndn-icp-download: timeout on " <<
timedOutSegment << " " << newInterest.getName() << "\n";
}
void
NdnIcpDownload::onFirstData(const Data &data)
{
const Name &name = data.getName();
Name first_copy = m_firstDataName;
if (name.size() == m_firstDataName.size() + 1)
m_dataName = Name(first_copy.append(name[-1]));
else if (name.size() == m_firstDataName.size() + 2)
m_dataName = Name(first_copy.append(name[-2]));
else {
std::cerr << "ERROR: Wrong number of components." << std::endl;
return;
}
//boost::async(boost::bind(&ndn::NdnIcpDownload::askFirst,this));
//scheduleNextPacket();
}
void
NdnIcpDownload::askFirst()
{
Interest interest;
interest.setName(Name(m_firstDataName));
interest.setInterestLifetime(m_defaulInterestLifeTime);
interest.setMustBeFresh(true);
interest.setChildSelector(1);
m_face.expressInterest(interest,
bind(&NdnIcpDownload::onFirstData, this, _2),
bind(&NdnIcpDownload::onNack, this, _1),
bind(&NdnIcpDownload::onTimeout, this, _1));
//scheduleNextPacket();
boost::async(boost::bind(&ndn::NdnIcpDownload::scheduleNextPacket,this));
}
bool
NdnIcpDownload::download(std::string name, std::vector<char> *rec_buffer, int initial_chunk, int n_chunk)
{
gettimeofday(&(m_variables->begin),0);
if ((Name(name) != Name(m_firstDataName) && !m_firstDataName.empty()) || initial_chunk > -1)
this->reInitialize();
if(!m_set_interest_filter){
InterestFilter intFilter(name);
m_face.setInterestFilter(intFilter, bind(&NdnIcpDownload::onInterest, this, _2));
m_set_interest_filter = true;
}
if (initial_chunk > -1) {
this->m_nextPendingInterest = (unsigned int)initial_chunk;
this->m_firstInFlight = (unsigned int)initial_chunk;
}
if (m_unversioned)
m_dataName = name;
else
this->m_firstDataName = name;
this->m_recBuffer = rec_buffer;
this->m_finalSlot = UINT_MAX;
if (n_chunk != -1 && m_finalChunk != UINT_MAX) {
m_finalChunk += n_chunk;
this->sendPacket();
}
else if (n_chunk != -1 && m_finalChunk == UINT_MAX) {
m_finalChunk = n_chunk + this->m_nextPendingInterest;
if (m_unversioned)
this->sendPacket();
else
this->askFirst();
}
else {
if (m_unversioned)
this->sendPacket();
else
this->askFirst();
}
m_face.processEvents();
if (m_packetsDelivered == 0) {
std::cerr << "NDN-ICP-DOWNLOAD: no data found: " << std::endl << m_dataName.toUri();
throw std::runtime_error("No data found");
}
if (m_nextPendingInterest <= m_finalChunk)
m_face.processEvents();
if (m_downloadCompleted) {
if (m_statistics)
//controlStatsReporter();
printSummary();
if(m_observed)
m_observer->notifyStats(m_variables->instantaneousThroughput, m_curPath->getAverageRtt());
this->reInitialize();
return true;
}
else
return false;
}
}
| 28,249 | 32.913565 | 138 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/ndn-icp-download.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Luca Muscariello <[email protected]>
* @author Zeng Xuan <[email protected]>
* @author Mauro Sardara <[email protected]>
* @author Michele Papalini <[email protected]>
*
*/
#ifndef NDN_ICP_DOWNLOAD_H
#define NDN_ICP_DOWNLOAD_H
#include <unistd.h>
#include <chrono>
#include <boost/timer/timer.hpp>
#include <stdio.h>
#include "chunktimeObserver.hpp"
#include "rate-estimation.hpp"
/**
* Default values for the protocol. They could be overwritten by the values provided by the application.
*/
#define RECEPTION_BUFFER 128000
#define DEFAULT_PATH_ID "default_path"
#define MAX_WINDOW (RECEPTION_BUFFER - 1)
#define MAX_SEQUENCE_NUMBER 1000
#define P_MIN 0.00001
#define P_MIN_STRING "0.00001"
#define DROP_FACTOR 0.02
#define DROP_FACTOR_STRING "0.02"
#define BETA 0.5
#define BETA_STRING "0.5"
#define GAMMA 1
/*
* Size of RTT sample queue. RAQM Window adaptation starts only if this queue is full.
* Until it is full, Interests are sent one per Data Packet
*/
#define SAMPLES 30
#define ALLOW_STALE false
#define DEFAULT_INTEREST_TIMEOUT 1000000 // microsecond (us)
#define MAX_INTEREST_LIFETIME_MS 10000 // millisecond (ms)
#define CHUNK_SIZE 1024
#define RATE_SAMPLES 4096 //number of packets on which rate is calculated
#define PATH_REP_INTVL 2000000
#define QUEUE_CAP 200
#define THRESHOLD 0.9
#define ALPHA 0.8
#define GOT_HERE() ((void)(__LINE__))
using duration_in_seconds = std::chrono::duration<double, std::ratio<1,1> >;
namespace ndn {
//Allow to have an observer of the downloading and can be notified of the DL speed
class NdnIcpDownloadObserver
{
public:
virtual ~NdnIcpDownloadObserver(){};
virtual void notifyStats(double WinSize, double RTT) = 0;
virtual void notifyChunkStats(std::string chunkName, double chunkThroughput) = 0; //for measurement on chunk-level logging
};
class NdnIcpDownload
{
public:
NdnIcpDownload(unsigned int pipe_size,
unsigned int initial_window,
unsigned int gamma,
double beta,
bool allowStale,
unsigned int lifetime_ms);
~NdnIcpDownload() {m_variables->isRunning = false;};
/**
* @brief Set the start time of the download to now.
*/
void
setStartTimeToNow();
/**
* @brief Set the time of the last timeout to now.
*/
void
setLastTimeOutToNow();
/**
* @brief Enable output during the download
*/
void
enableOutput();
/**
* @brief Enable the software to print per-path statistics at the end of the download
*/
void
enablePathReport();
/*
* @brief Set the default path
* @param path the current DataPath
*/
void
setCurrentPath(shared_ptr<DataPath> path);
/**
* @brief Report statistics regarding the congestion control algorithm
*/
void
controlStatsReporter();
/**
* Print a summary regarding the statistics of the download
*/
void
printSummary();
/**
* @brief Reset the congestion window to the initial values
*/
void
resetRAAQM();
/**
* @brief Enable the automatic print of al the statistics at the end of the download
* @param value true for enabling statistics, false otherwise
*/
void
setStatistics(bool value);
/**
* @brief Enable the download of unversioned data
* @param value true for enabling unversioned data, false otherwise
*/
void
setUnversioned(bool value);
/**
* @brief Set the number of tries before exiting from the program due to data unavailability
* @param max_retries is the max number of retries
*/
void
setMaxRetries(unsigned max_retries);
/**
* @brief Function for starting the download
* @param name is the ICN name of the content
* @param rec_buffer is a pointer to the buffer that is going to be filled with the downloaded data
* @param initial_chunk is the first chunk of the download. initial_chunk = -1 means start from the beginning
* @param n_chunk indicates how many chunk retrieve after initial_chunk. Default behavior: download the whole file.
*/
bool
download(std::string name, std::vector<char> *rec_buffer, int initial_chunk = -1, int n_chunk = -1);
/**
* @brief Insert new data path to the path table
* @param key The identifier of the path
* @param path The DataPath itself
*/
void
insertToPathTable(std::string key, shared_ptr<DataPath> path);
/**
* @brief To add an observer on the downloader
* @param obs an instance of NdnIcpDownloadObserver
*/
void
addObserver(NdnIcpDownloadObserver* obs);
/**
* @brief To add an observer on the downloader
* @param obs an instance of ChunktimeObserver
*/
void
addObserver(ChunktimeObserver* obs);
/**
*/
void
setAlpha(double alpha);
private:
/**
* @brief Update the RTT status after a data packet at slot is received. Also update the m_timer for the current path.
* @param slot the corresponding slot of the received data packet.
*/
void
updateRTT(uint64_t slot);
/**
* @brief Update the window size
*/
void
increaseWindow();
/**
* @brief Decrease the window size
*/
void
decreaseWindow();
/**
* @brief Re-initialize the download indexes, but keep the current RAAQM parameters such as samples and window size
*/
void
reInitialize();
/**
* @brief Send an interest with the name specified in download
*/
void
sendPacket();
/**
* @brief Schedule the sending of a new packet
*/
void
scheduleNextPacket();
/*
* @brief Update drop probability and modify curwindow accordingly.
*/
void
RAQM();
/**
* @brief Update statistics and congestion control protocol parameters
* @param slot is the received data slot
*/
void
afterDataReception(uint64_t slot);
/**
* @brief Ask first interest. Used just for versioned data.
*/
void
askFirst();
/**
* @brief Callback for process the incoming data
* @param data is the data block received
*/
void
onData(const Data &data);
/**
* @brief Callback for process incoming interest (used by MLDR for M-flaged interest)
* @param interest is the interes block received
*/
void
onInterest(const Interest &interest);
/*
* @brief Callback for process incoming nacks
* @param nack is the nack block received
*/
void
onNack(const Interest &nack);
/**
* @brief Callback for fist content received. Used just for versioned data.
* @param data is the data block received
*/
void
onFirstData(const Data &data);
/**
* @brief Callback that re-express the interest after a timeout
*/
void
onTimeout(const Interest &interest);
/**
* The name of the content
*/
Name m_dataName;
/**
* The name of the first content (just for versioned data)
*/
Name m_firstDataName;
/*
* Flag specifying if downloading unversioned data or not
*/
bool m_unversioned;
/**
* Max value of the window of interests
*/
unsigned m_maxWindow;
/**
* Minimum drop probability
*/
double m_pMin;
/**
* Final chunk number
*/
uint64_t m_finalChunk;
/**
* Number of samples to be considered for the protocol computations
*/
unsigned int m_samples;
/**
* Additive window increment value
*/
const unsigned int m_gamma;
/**
* Multiplicative window decrement value
*/
const double m_beta;
/**
* Allow the download of unfresh contents
*/
bool m_allowStale;
/**
* Default lifetime for the interests
*/
const time::milliseconds m_defaulInterestLifeTime;
/**
* Enable output for debugging purposes
*/
bool m_isOutputEnabled;
/**
* Enable path report at the end of the download
*/
bool m_isPathReportEnabled; //set to false by default
/**
* Number of pending interests inside the current window
*/
unsigned m_winPending; // Number of pending interest
/**
* Current size of the windows
*/
double m_winCurrent;
/**
* Initial value of the window, to be used if the application wants to reset the RAAQM parameters
*/
double m_initialWindow;
/**
* First pending interest
*/
uint64_t m_firstInFlight;
/**
* Total count of pending interests
*/
unsigned m_outOfOrderCount;
/**
* Next interest to be sent
*/
unsigned m_nextPendingInterest;
/**
* Position in the reception buffer of the final chunk
*/
uint64_t m_finalSlot;
/**
* Total number of interests sent. Kept just for statistic purposes.
*/
intmax_t m_interestsSent;
/**
* Total number of packets sent. Kept just for statistic purposes.
*/
intmax_t m_packetsDelivered;
/**
* Total number of bytes received, including headers. Kept just for statistic purposes.
*/
intmax_t m_rawBytesDataDelivered;
/**
* Total number of bytes received, without considering headers. Kept just for statistic purposes.
*/
intmax_t m_bytesDataDelivered;
/**
*
*/
bool m_isAbortModeEnabled;
/**
* Number of retransmitted interests in the window
*/
unsigned m_winRetransmissions;
/**
* Flag indicating whether the download terminated or not
*/
bool m_downloadCompleted;
/**
* Number of times an interest can be retransmitted
*/
unsigned m_retxLimit;
/**
* Flag indicating whether the library is downloading or not
*/
bool m_isSending;
/**
* Total number of interest timeouts. Kept just for statistic purposes.
*/
intmax_t m_nTimeouts;
/**
* Current download path
*/
shared_ptr<DataPath> m_curPath;
/**
* Initial path. Stored for resetting RAAQM
*/
shared_ptr<DataPath> m_savedPath;
/**
* Flag indicating whether print statistics at he end or not
*/
bool m_statistics;
/**
* Flag indicating if there is an observer or not.
*/
bool m_observed;
bool c_observed;
/**
* Start time of the download. Kept just for measurements.
*/
struct timeval m_startTimeValue;
/**
* End time of the download. Kept just for measurements.
*/
struct timeval m_stopTimeValue;
/**
* Timestamp of the last interest timeout
*/
struct timeval m_lastTimeout;
double m_averageWin;
/**
* Hash table for path: each entry is a pair path ID(key) - path object
*
*/
typedef boost::unordered_map<std::string, shared_ptr<DataPath>> HashTableForPath;
HashTableForPath m_pathTable;
/**
* Buffer storing the data received out of order
*/
PendingInterest m_outOfOrderInterests[RECEPTION_BUFFER];
/**
* The buffer provided by the application where storing the downloaded data
*/
std::vector<char> *m_recBuffer;
/**
* The local face used for forwarding interests to the local forwarder and viceversa
*/
Face m_face;
/**
* Set for M-flaged interests (used by MLDR)
*/
typedef std::set<uint64_t> NackSet;
NackSet m_nackSet;
bool m_set_interest_filter;
/**
* Observer, NULL if none
*/
NdnIcpDownloadObserver * m_observer;
ChunktimeObserver * c_observer;
NdnIcpDownloadRateEstimator *ndnIcpDownloadRateEstimator;
Variables *m_variables;
int maxPacketSize;
uint64_t cumulativeBytesReceived;
double dnltime_chunk;
double speed_chunk;
FILE * windowFile;
typedef boost::chrono::duration<double> sec; // seconds, stored with a double
boost::timer::cpu_timer timer;
};//end class NdnIcpDownload
} // namespace ndn
#endif //NDN_ICP_DOWNLOAD_H
| 13,152 | 23.312384 | 130 |
hpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/log/log.h
|
#ifndef LOGDEFINITIONFILE__H
#define LOGDEFINITIONFILE__H
//#define LOG_BUILD
#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#include <stdlib.h>
#include <iostream>
#include <unistd.h>
#include <chrono>
#include <ratio>
#ifdef LOG_BUILD
//Logging time is done here
//format of the logging would be: "[timestamp_since_start(in seconds)] logging message"
using duration_in_seconds = std::chrono::duration<double, std::ratio<1,1> >;
namespace sampleplayer
{
namespace log
{
extern std::chrono::time_point<std::chrono::system_clock> m_start_time;
extern int flushThreshold;
extern char *loggingBuffer;
extern int loggingPosition;
extern pthread_mutex_t logMutex;
extern pthread_cond_t loggingCond;
extern pthread_t * logTh;
extern const char* logFile;
extern void Init();
extern void Stop();
extern void* LogStart(void * data);
extern void Start(const char* data);
}
}
//We need this to flush the log after the video ends (or when the user stops the video)
#define FlushLog() do { sampleplayer::log::Stop(); \
pthread_join(*(sampleplayer::log::logTh), NULL); \
sampleplayer::log::Start(sampleplayer::log::logFile); \
} while(0)
#define L(...) do { double now = std::chrono::duration_cast<duration_in_seconds>(std::chrono::system_clock::now() - sampleplayer::log::m_start_time).count();\
pthread_mutex_lock(&(sampleplayer::log::logMutex)); \
sampleplayer::log::loggingPosition += sprintf(sampleplayer::log::loggingBuffer + sampleplayer::log::loggingPosition, "[%f]", now); \
sampleplayer::log::loggingPosition += sprintf(sampleplayer::log::loggingBuffer + sampleplayer::log::loggingPosition, __VA_ARGS__); \
pthread_cond_broadcast(&(sampleplayer::log::loggingCond)); \
pthread_mutex_unlock(&(sampleplayer::log::logMutex)); \
} while(0)
#else
#define FlushLog() do {} while(0)
#define L(...) do {} while(0)
#endif //LOG_BUILD
#endif //LOGDEFINITIONFILE__H
| 1,965 | 31.229508 | 159 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/.waf-tools/default-compiler-flags.py
|
# -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
from waflib import Logs, Configure
def options(opt):
opt.add_option('--debug', '--with-debug', action='store_true', default=False, dest='debug',
help='''Compile in debugging mode without optimizations (-O0 or -Og)''')
def configure(conf):
areCustomCxxflagsPresent = (len(conf.env.CXXFLAGS) > 0)
defaultFlags = ["-D__STDC_CONSTANT_MACROS", "-D__STDC_LIMIT_MACROS", "-std=c++11", "-fpermissive", "march=native", "-pedantic", "-Wall"]
if conf.options.debug:
conf.define('_DEBUG', 1)
defaultFlags += ['-O0',
'-Og', # gcc >= 4.8
'-g3',
'-fcolor-diagnostics', # clang
'-fdiagnostics-color', # gcc >= 4.9
'-Wno-error=maybe-uninitialized',
'ggdb',
]
if areCustomCxxflagsPresent:
missingFlags = [x for x in defaultFlags if x not in conf.env.CXXFLAGS]
if len(missingFlags) > 0:
Logs.warn("Selected debug mode, but CXXFLAGS is set to a custom value '%s'"
% " ".join(conf.env.CXXFLAGS))
Logs.warn("Default flags '%s' are not activated" % " ".join(missingFlags))
else:
conf.add_supported_cxxflags(defaultFlags)
else:
defaultFlags += ["-O3", "-g"]
if not areCustomCxxflagsPresent:
conf.add_supported_cxxflags(defaultFlags)
# clang on OSX < 10.9 by default uses gcc's libstdc++, which is not C++11 compatible
#conf.add_supported_linkflags(['-stdlib=libc++'])
conf.add_supported_linkflags(['-std=c++11'])
@Configure.conf
def add_supported_cxxflags(self, cxxflags):
"""
Check which cxxflags are supported by compiler and add them to env.CXXFLAGS variable
"""
self.start_msg('Checking supported CXXFLAGS')
supportedFlags = []
for flag in cxxflags:
if self.check_cxx(cxxflags=['-Werror', flag], mandatory=False):
supportedFlags += [flag]
self.end_msg(' '.join(supportedFlags))
self.env.CXXFLAGS = supportedFlags + self.env.CXXFLAGS
@Configure.conf
def add_supported_linkflags(self, linkflags):
"""
Check which linkflags are supported by compiler and add them to env.LINKFLAGS variable
"""
self.start_msg('Checking supported LINKFLAGS')
supportedFlags = []
for flag in linkflags:
if self.check_cxx(linkflags=['-Werror', flag], mandatory=False):
supportedFlags += [flag]
self.end_msg(' '.join(supportedFlags))
self.env.LINKFLAGS = supportedFlags + self.env.LINKFLAGS
| 2,723 | 38.478261 | 140 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/.waf-tools/boost.py
|
#!/usr/bin/env python
# encoding: utf-8
#
# partially based on boost.py written by Gernot Vormayr
# written by Ruediger Sonderfeld <[email protected]>, 2008
# modified by Bjoern Michaelsen, 2008
# modified by Luca Fossati, 2008
# rewritten for waf 1.5.1, Thomas Nagy, 2008
# rewritten for waf 1.6.2, Sylvain Rouquette, 2011
'''
This is an extra tool, not bundled with the default waf binary.
To add the boost tool to the waf file:
$ ./waf-light --tools=compat15,boost
or, if you have waf >= 1.6.2
$ ./waf update --files=boost
When using this tool, the wscript will look like:
def options(opt):
opt.load('compiler_cxx boost')
def configure(conf):
conf.load('compiler_cxx boost')
conf.check_boost(lib='system filesystem')
def build(bld):
bld(source='main.cpp', target='app', use='BOOST')
Options are generated, in order to specify the location of boost includes/libraries.
The `check_boost` configuration function allows to specify the used boost libraries.
It can also provide default arguments to the --boost-static and --boost-mt command-line arguments.
Everything will be packaged together in a BOOST component that you can use.
When using MSVC, a lot of compilation flags need to match your BOOST build configuration:
- you may have to add /EHsc to your CXXFLAGS or define boost::throw_exception if BOOST_NO_EXCEPTIONS is defined.
Errors: C4530
- boost libraries will try to be smart and use the (pretty but often not useful) auto-linking feature of MSVC
So before calling `conf.check_boost` you might want to disabling by adding:
conf.env.DEFINES_BOOST += ['BOOST_ALL_NO_LIB']
Errors:
- boost might also be compiled with /MT, which links the runtime statically.
If you have problems with redefined symbols,
self.env['DEFINES_%s' % var] += ['BOOST_ALL_NO_LIB']
self.env['CXXFLAGS_%s' % var] += ['/MD', '/EHsc']
Passing `--boost-linkage_autodetect` might help ensuring having a correct linkage in some basic cases.
'''
import sys
import re
from waflib import Utils, Logs, Errors
from waflib.Configure import conf
BOOST_LIBS = ['/usr/lib', '/usr/local/lib', '/opt/local/lib', '/sw/lib', '/lib', '/usr/lib/x86_64-linux-gnu', '/usr/lib/i386-linux-gnu', '/usr/local/ndn/lib']
BOOST_INCLUDES = ['/usr/include', '/usr/local/include', '/opt/local/include', '/sw/include', '/usr/local/ndn/include']
BOOST_VERSION_FILE = 'boost/version.hpp'
BOOST_VERSION_CODE = '''
#include <iostream>
#include <boost/version.hpp>
int main() { std::cout << BOOST_LIB_VERSION << ":" << BOOST_VERSION << std::endl; }
'''
BOOST_SYSTEM_CODE = '''
#include <boost/system/error_code.hpp>
int main() { boost::system::error_code c; }
'''
BOOST_THREAD_CODE = '''
#include <boost/thread.hpp>
int main() { boost::thread t; }
'''
# toolsets from {boost_dir}/tools/build/v2/tools/common.jam
PLATFORM = Utils.unversioned_sys_platform()
detect_intel = lambda env: (PLATFORM == 'win32') and 'iw' or 'il'
detect_clang = lambda env: (PLATFORM == 'darwin') and 'clang-darwin' or 'clang'
detect_mingw = lambda env: (re.search('MinGW', env.CXX[0])) and 'mgw' or 'gcc'
BOOST_TOOLSETS = {
'borland': 'bcb',
'clang': detect_clang,
'como': 'como',
'cw': 'cw',
'darwin': 'xgcc',
'edg': 'edg',
'g++': detect_mingw,
'gcc': detect_mingw,
'icpc': detect_intel,
'intel': detect_intel,
'kcc': 'kcc',
'kylix': 'bck',
'mipspro': 'mp',
'mingw': 'mgw',
'msvc': 'vc',
'qcc': 'qcc',
'sun': 'sw',
'sunc++': 'sw',
'tru64cxx': 'tru',
'vacpp': 'xlc'
}
def options(opt):
opt = opt.add_option_group('Boost Options')
opt.add_option('--boost-includes', type='string',
default='', dest='boost_includes',
help='''path to the directory where the boost includes are, e.g., /path/to/boost_1_55_0/stage/include''')
opt.add_option('--boost-libs', type='string',
default='', dest='boost_libs',
help='''path to the directory where the boost libs are, e.g., /path/to/boost_1_55_0/stage/lib''')
opt.add_option('--boost-static', action='store_true',
default=False, dest='boost_static',
help='link with static boost libraries (.lib/.a)')
opt.add_option('--boost-mt', action='store_true',
default=False, dest='boost_mt',
help='select multi-threaded libraries')
opt.add_option('--boost-abi', type='string', default='', dest='boost_abi',
help='''select libraries with tags (dgsyp, d for debug), see doc Boost, Getting Started, chapter 6.1''')
opt.add_option('--boost-linkage_autodetect', action="store_true", dest='boost_linkage_autodetect',
help="auto-detect boost linkage options (don't get used to it / might break other stuff)")
opt.add_option('--boost-toolset', type='string',
default='', dest='boost_toolset',
help='force a toolset e.g. msvc, vc90, gcc, mingw, mgw45 (default: auto)')
py_version = '%d%d' % (sys.version_info[0], sys.version_info[1])
opt.add_option('--boost-python', type='string',
default=py_version, dest='boost_python',
help='select the lib python with this version (default: %s)' % py_version)
@conf
def __boost_get_version_file(self, d):
dnode = self.root.find_dir(d)
if dnode:
return dnode.find_node(BOOST_VERSION_FILE)
return None
@conf
def boost_get_version(self, d):
"""silently retrieve the boost version number"""
node = self.__boost_get_version_file(d)
if node:
try:
txt = node.read()
except (OSError, IOError):
Logs.error("Could not read the file %r" % node.abspath())
else:
re_but1 = re.compile('^#define\\s+BOOST_LIB_VERSION\\s+"(.+)"', re.M)
m1 = re_but1.search(txt)
re_but2 = re.compile('^#define\\s+BOOST_VERSION\\s+(\\d+)', re.M)
m2 = re_but2.search(txt)
if m1 and m2:
return (m1.group(1), m2.group(1))
return self.check_cxx(fragment=BOOST_VERSION_CODE, includes=[d], execute=True, define_ret=True).split(":")
@conf
def boost_get_includes(self, *k, **kw):
includes = k and k[0] or kw.get('includes', None)
if includes and self.__boost_get_version_file(includes):
return includes
for d in Utils.to_list(self.environ.get('INCLUDE', '')) + BOOST_INCLUDES:
if self.__boost_get_version_file(d):
return d
if includes:
self.end_msg('headers not found in %s' % includes)
self.fatal('The configuration failed')
else:
self.end_msg('headers not found, please provide a --boost-includes argument (see help)')
self.fatal('The configuration failed')
@conf
def boost_get_toolset(self, cc):
toolset = cc
if not cc:
build_platform = Utils.unversioned_sys_platform()
if build_platform in BOOST_TOOLSETS:
cc = build_platform
else:
cc = self.env.CXX_NAME
if cc in BOOST_TOOLSETS:
toolset = BOOST_TOOLSETS[cc]
return isinstance(toolset, str) and toolset or toolset(self.env)
@conf
def __boost_get_libs_path(self, *k, **kw):
''' return the lib path and all the files in it '''
if 'files' in kw:
return self.root.find_dir('.'), Utils.to_list(kw['files'])
libs = k and k[0] or kw.get('libs', None)
if libs:
path = self.root.find_dir(libs)
files = path.ant_glob('*boost_*')
if not libs or not files:
for d in Utils.to_list(self.environ.get('LIB', [])) + BOOST_LIBS:
path = self.root.find_dir(d)
if path:
files = path.ant_glob('*boost_*')
if files:
break
path = self.root.find_dir(d + '64')
if path:
files = path.ant_glob('*boost_*')
if files:
break
if not path:
if libs:
self.end_msg('libs not found in %s' % libs)
self.fatal('The configuration failed')
else:
self.end_msg('libs not found, please provide a --boost-libs argument (see help)')
self.fatal('The configuration failed')
self.to_log('Found the boost path in %r with the libraries:' % path)
for x in files:
self.to_log(' %r' % x)
return path, files
@conf
def boost_get_libs(self, *k, **kw):
'''
return the lib path and the required libs
according to the parameters
'''
path, files = self.__boost_get_libs_path(**kw)
t = []
if kw.get('mt', False):
t.append('mt')
if kw.get('abi', None):
t.append(kw['abi'])
tags = t and '(-%s)+' % '-'.join(t) or ''
toolset = self.boost_get_toolset(kw.get('toolset', ''))
toolset_pat = '(-%s[0-9]{0,3})+' % toolset
version = '(-%s)+' % self.env.BOOST_VERSION
def find_lib(re_lib, files):
for file in files:
if re_lib.search(file.name):
self.to_log('Found boost lib %s' % file)
return file
return None
def format_lib_name(name):
if name.startswith('lib') and self.env.CC_NAME != 'msvc':
name = name[3:]
return name[:name.rfind('.')]
libs = []
for lib in Utils.to_list(k and k[0] or kw.get('lib', None)):
py = (lib == 'python') and '(-py%s)+' % kw['python'] or ''
# Trying libraries, from most strict match to least one
for pattern in ['boost_%s%s%s%s%s' % (lib, toolset_pat, tags, py, version),
'boost_%s%s%s%s' % (lib, tags, py, version),
'boost_%s%s%s' % (lib, tags, version),
# Give up trying to find the right version
'boost_%s%s%s%s' % (lib, toolset_pat, tags, py),
'boost_%s%s%s' % (lib, tags, py),
'boost_%s%s' % (lib, tags)]:
self.to_log('Trying pattern %s' % pattern)
file = find_lib(re.compile(pattern), files)
if file:
libs.append(format_lib_name(file.name))
break
else:
self.end_msg('lib %s not found in %s' % (lib, path.abspath()))
self.fatal('The configuration failed')
return path.abspath(), libs
@conf
def check_boost(self, *k, **kw):
"""
Initialize boost libraries to be used.
Keywords: you can pass the same parameters as with the command line (without "--boost-").
Note that the command line has the priority, and should preferably be used.
"""
if not self.env['CXX']:
self.fatal('load a c++ compiler first, conf.load("compiler_cxx")')
params = {'lib': k and k[0] or kw.get('lib', None)}
for key, value in self.options.__dict__.items():
if not key.startswith('boost_'):
continue
key = key[len('boost_'):]
params[key] = value and value or kw.get(key, '')
var = kw.get('uselib_store', 'BOOST')
self.start_msg('Checking boost includes')
self.env['INCLUDES_%s' % var] = inc = self.boost_get_includes(**params)
versions = self.boost_get_version(inc)
self.env.BOOST_VERSION = versions[0]
self.env.BOOST_VERSION_NUMBER = int(versions[1])
self.end_msg("%d.%d.%d" % (int(versions[1]) / 100000,
int(versions[1]) / 100 % 1000,
int(versions[1]) % 100))
if Logs.verbose:
Logs.pprint('CYAN', ' path : %s' % self.env['INCLUDES_%s' % var])
if not params['lib']:
return
self.start_msg('Checking boost libs')
suffix = params.get('static', None) and 'ST' or ''
path, libs = self.boost_get_libs(**params)
self.env['%sLIBPATH_%s' % (suffix, var)] = [path]
self.env['%sLIB_%s' % (suffix, var)] = libs
self.end_msg('ok')
if Logs.verbose:
Logs.pprint('CYAN', ' path : %s' % path)
Logs.pprint('CYAN', ' libs : %s' % libs)
def try_link():
if 'system' in params['lib']:
self.check_cxx(
fragment=BOOST_SYSTEM_CODE,
use=var,
execute=False,
)
if 'thread' in params['lib']:
self.check_cxx(
fragment=BOOST_THREAD_CODE,
use=var,
execute=False,
)
if params.get('linkage_autodetect', False):
self.start_msg("Attempting to detect boost linkage flags")
toolset = self.boost_get_toolset(kw.get('toolset', ''))
if toolset in ['vc']:
# disable auto-linking feature, causing error LNK1181
# because the code wants to be linked against
self.env['DEFINES_%s' % var] += ['BOOST_ALL_NO_LIB']
# if no dlls are present, we guess the .lib files are not stubs
has_dlls = False
for x in Utils.listdir(path):
if x.endswith(self.env.cxxshlib_PATTERN % ''):
has_dlls = True
break
if not has_dlls:
self.env['STLIBPATH_%s' % var] = [path]
self.env['STLIB_%s' % var] = libs
del self.env['LIB_%s' % var]
del self.env['LIBPATH_%s' % var]
# we attempt to play with some known-to-work CXXFLAGS combinations
for cxxflags in (['/MD', '/EHsc'], []):
self.env.stash()
self.env["CXXFLAGS_%s" % var] += cxxflags
try:
try_link()
self.end_msg("ok: winning cxxflags combination: %s" % (self.env["CXXFLAGS_%s" % var]))
e = None
break
except Errors.ConfigurationError as exc:
self.env.revert()
e = exc
if e is not None:
self.end_msg("Could not auto-detect boost linking flags combination, you may report it to boost.py author", ex=e)
self.fatal('The configuration failed')
else:
self.end_msg("Boost linkage flags auto-detection not implemented (needed ?) for this toolchain")
self.fatal('The configuration failed')
else:
self.start_msg('Checking for boost linkage')
try:
try_link()
except Errors.ConfigurationError as e:
self.end_msg("Could not link against boost libraries using supplied options")
self.fatal('The configuration failed')
self.end_msg('ok')
| 14,617 | 37.569921 | 158 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/old.md
|
# libdash
libdash is the **official reference software of the ISO/IEC MPEG-DASH standard** and is an open-source library that provides an object orient (OO) interface to the MPEG-DASH standard, developed by [bitmovin](http://www.bitmovin.com).
## by bitmovin
<a href="https://www.bitmovin.com"><img src="https://cloudfront.bitmovin.com/wp-content/uploads/2014/11/Logo-bitmovin.jpg" width="400px"/></a>
Video encoding 100x faster than any other encoding service
Your videos play everywhere with low startup delay, no buffering and in the highest quality
### NETFLIX GRADE QUALITY
Encode your content with the same technology as Netflix and YouTube in a way that it plays everywhere with low startup delay and no buffering. bitcodin encodes your content 100x faster than any other competitor while providing such a high quality output.
### API & DOCUMENTATION
bitcodin is a powerful cloud encoding tool for developers built by developers. The bitcodin API is available in our developer section including comprehensive documentation and API client for different programming languages such as Java, JavaScript, Ruby, Python, PHP, NodeJS, etc.
### HTML5 ADAPTIVE STREAMING
bitcodin enables HTML5 adaptive streaming with MPEG-DASH native in your browser with no need for plugins like Flash or Silverlight. Due to the native integration with the browser it is possible to play back very high resolutions such as 4K or very high framrates like 60fps.
## Features
* Cross platform build system based on cmake that includes Windows, Linux and Mac.
* Open source available and licensed under the LGPL.
* Comprehensive doxygen documentation
* Implements the full MPEG-DASH standard according to ISO/IEC 23009-1, Information Technology Dynamic Adaptive Streaming over HTTP (DASH) Part 1: Media Presentation Description and Segment Formats
* Handles the download and xml parsing of the MPD. Based on that it provides an OO based interface to the MPD.
* Media elements, e.g., SegmentURL, SegmentTemplate, etc., are downloadable in that OO based structure and can be downloaded through libdash, which internally uses libcurl.
* Therefore basically all protocols that libcurl supports, e.g., HTTP, FTP, etc. are supported by libdash.
* However it also provides a configurable download interface, which enables the use of external connections that can be implemented by the user of the library for the download of media segments.
* The use of such external connections will be shown in the libdash_networkpart_test project which is part of libdash solution and also part of the cross platform cmake system and therefore usable on Windows, Linux and Mac.
* The project contains a QT-based sample multimedia player that is based on ffmpeg which uses libdash for the playback of one of our dataset MPDs.
* The development is based on Windows, therefore the code contains a VS10 solution with additional tests and the sample multimedia player.
## Professional Services
In addition to the public available open source resources and the mailing list support, we provide professional development and integration services, consulting, high-quality streaming componentes/logics, relicensing of libdash etc. based on your individual needs. Feel free to contact us via [email protected] so we can discuss your requirements and provide you an offer.
## bitdash - Advanced MPEG-DASH Clients
On top of libdash, we provide our [bitdash adaptation framework] (http://www.bitmovin.com), which significantely boosts the streaming performance of MPEG-DASH. It enables up to 100 % higher media throughput than Apple HLS, and 50 % more than Microsoft Smooth Streaming. Additionally it comes together with streaming management functionalities, oscillation prevention mechanisms, DRM key management, multi-source (multi-CDN) support, and much more. It targets embedded platforms such as smartphones, TV-Sets, Set-Top Boxes, etc. and is available on any platform, including Windows, Linux, Mac, Android, etc. Furthermore, we've implementations for HTML5 (MSE) as well as Adobe Flash
Please do not heasitate and contact [email protected] to get further information on [bitdash] (http://www.bitmovin.com/)!
## Architecture
<p align="justify">The general architecture of MPEG-DASH is depicted in the figure below where the orange parts are standardized, i.e., the MPD and segment formats. The delivery of the MPD, the control heuristics and the media player itself, are depicted in blue in the figure. These parts are not standardized and allow the differentiation of industry solutions due to the performance or different features that can be integrated at that level. libdash is also depicted in blue and encapsulates the MPD parsing and HTTP part, which will be handled by the library. Therefore the library provides interfaces for the DASH Streaming Control and the Media Player to access MPDs and downloadable media segments. The download order of such media segments will not be handled by the library this is left to the DASH Streaming Control, which is an own component in this architecture but it could also be included in the Media Player.
</p>
<p align="justify">
In a typical deployment, a DASH server provides segments in several bitrates and resolutions. The client initially receives the MPD through libdash which provides a convenient object orient interface to that MPD. The MPD contains the temporal relationships for the various qualities and segments. Based on that information the client can download individual media segments through libdash at any point in time. Therefore varying bandwidth conditions can be handled by switching to the corresponding quality level at segment boundaries in order to provide a smooth streaming experience. This adaptation is not part of libdash and the MPEG-DASH standard and will be left to the application which is using libdash.
</p>
## Documentation
The doxygen documentation availalbe in the repo.
## Sources and Binaries
You can find the latest sources and binaries on github.
## How to use
### Windows
1. Download the tarball or clone the repository from github (git://github.com/bitmovin/libdash.git)
2. Open the libdash.sln with Visual Studio 2010
3. Build the solution
4. After that all files will be provided in the bin folder
5. You can test the library with the sampleplayer.exe. This application simply downloads the lowest representation of one of our dataset MPDs.
### Ubuntu 12.04
1. sudo apt-get install git-core build-essential cmake libxml2-dev libcurl4-openssl-dev
2. git clone git://github.com/bitmovin/libdash.git
3. cd libdash/libdash
4. mkdir build
5. cd build
6. cmake ../
7. make
8. cd bin
9. The library and a simple test of the network part of the library should be available now. You can test the network part of the library with
10. ./libdash_networpart_test
#### QTSamplePlayer
Prerequisite: libdash must be built as described in the previous section.
1. sudo apt-add-repository ppa:ubuntu-sdk-team/ppa
2. sudo apt-add-repository ppa:canonical-qt5-edgers/qt5-proper
3. sudo apt-get update
4. sudo apt-get install qtmultimedia5-dev qtbase5-dev libqt5widgets5 libqt5core5a libqt5gui5 libqt5multimedia5 libqt5multimediawidgets5 libqt5opengl5 libav-tools libavcodec-dev libavdevice-dev libavfilter-dev libavformat-dev libavutil-dev libpostproc-dev libswscale-dev libqt5multimedia5-plugins libavresample-dev
5. cd libdash/libdash/qtsampleplayer
6. mkdir build
7. cd build
8. wget http://www.cmake.org/files/v2.8/cmake-2.8.11.2-Linux-i386.sh
9. chmod a+x cmake-2.8.11.2-Linux-i386.sh
10. ./cmake-2.8.11.2-Linux-i386.sh
11. ./cmake-2.8.11.2-Linux-i386/bin/cmake ../
12. make
13. ./qtsampleplayer
## License
libdash is open source available and licensed under LGPL:
“This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA“
As libdash is licensed under LGPL, changes to the library have to be published again to the open-source project. As many user and companies do not want to publish their specific changes, libdash can be also relicensed to a commercial license on request. Please contact [email protected] to provide you an offer.
## Acknowledgements
We specially want to thank our passionate developers at [bitmovin](http://www.bitmovin.com) as well as the researchers at the [Institute of Information Technology](http://www-itec.aau.at/dash/) (ITEC) from the Alpen Adria Universitaet Klagenfurt (AAU)!
Furthermore we want to thank the [Netidee](http://www.netidee.at) initiative from the [Internet Foundation Austria](http://www.nic.at/ipa) for partially funding the open source development of libdash.

## Citation of libdash
We kindly ask you to refer the following paper in any publication mentioning libdash:
Christopher Mueller, Stefan Lederer, Joerg Poecher, and Christian Timmerer, “libdash – An Open Source Software Library for the MPEG-DASH Standard”, in Proceedings of the IEEE International Conference on Multimedia and Expo 2013, San Jose, USA, July, 2013
| 9,678 | 78.336066 | 925 |
md
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/README.md
|
# libdash
libdash is the **official reference software of the ISO/IEC MPEG-DASH standard** and is an open-source library that provides an object orient (OO) interface to the MPEG-DASH standard, developed by [bitmovin](http://www.bitmovin.com).
## by bitmovin
<a href="https://www.bitmovin.com"><img src="https://cloudfront.bitmovin.com/wp-content/uploads/2014/11/Logo-bitmovin.jpg" width="400px"/></a>
## Documentation
The doxygen documentation availalbe in the repo.
## Sources and Binaries
You can find the latest sources and binaries on github.
## How to use
### Ubuntu 16.04
1. sudo apt-get install git-core build-essential cmake libxml2-dev libcurl4-openssl-dev
3. cd ndn-dash/libdash
4. mkdir build
5. cd build
6. cmake ../
7. make
#### QTSamplePlayer
Prerequisite: libdash must be built as described in the previous section.
1. sudo apt-get install qtmultimedia5-dev qtbase5-dev libqt5widgets5 libqt5core5a libqt5gui5 libqt5multimedia5 libqt5multimediawidgets5 libqt5opengl5 libav-tools libavcodec-dev libavdevice-dev libavfilter-dev libavformat-dev libavutil-dev libpostproc-dev libswscale-dev libqt5multimedia5-plugins libavresample-dev
2bis. sudo apt-get install ndn-icp-download
3. cd ndn-dash/libdash/qtsampleplayer
4. mkdir build
5. cd build
6. cmake ../ (if this doesn't succeed, try with cmake ../ -DLIBAV_ROOT_DIR=/usr/lib)
7. make
8. ./qtsampleplayer
##Usage with headless mode
./qtsampleplayer -nohead -u url [-nr alpha] [-n] [-r alpha] [-b B1 Bmax]
-u: to indicate the url to download the MPD file.
-n: indicate NDN download.
-nr: indicate NDN download and usage of NDN-based rate estimation with an EWMA of parameter alpha, 0 <= alpha < 1.
-r: indicate Rate-based adaptation with a parameter of alpha. 0 <= alpha < 1.
-b: indicate Buffer-based adaptation (BBA-0) with parameters B1 and Bmax.
## License
libdash is open source available and licensed under LGPL:
“This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA“
As libdash is licensed under LGPL, changes to the library have to be published again to the open-source project. As many user and companies do not want to publish their specific changes, libdash can be also relicensed to a commercial license on request. Please contact [email protected] to provide you an offer.
## Acknowledgements
We specially want to thank our passionate developers at [bitmovin](http://www.bitmovin.com) as well as the researchers at the [Institute of Information Technology](http://www-itec.aau.at/dash/) (ITEC) from the Alpen Adria Universitaet Klagenfurt (AAU)!
Furthermore we want to thank the [Netidee](http://www.netidee.at) initiative from the [Internet Foundation Austria](http://www.nic.at/ipa) for partially funding the open source development of libdash.

## Citation of libdash
We kindly ask you to refer the following paper in any publication mentioning libdash:
Christopher Mueller, Stefan Lederer, Joerg Poecher, and Christian Timmerer, “libdash – An Open Source Software Library for the MPEG-DASH Standard”, in Proceedings of the IEEE International Conference on Multimedia and Expo 2013, San Jose, USA, July, 2013
| 3,847 | 51.712329 | 313 |
md
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/libcurl/include/curl/multi.h
|
#ifndef __CURL_MULTI_H
#define __CURL_MULTI_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2012, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
This is an "external" header file. Don't give away any internals here!
GOALS
o Enable a "pull" interface. The application that uses libcurl decides where
and when to ask libcurl to get/send data.
o Enable multiple simultaneous transfers in the same thread without making it
complicated for the application.
o Enable the application to select() on its own file descriptors and curl's
file descriptors simultaneous easily.
*/
/*
* This header file should not really need to include "curl.h" since curl.h
* itself includes this file and we expect user applications to do #include
* <curl/curl.h> without the need for especially including multi.h.
*
* For some reason we added this include here at one point, and rather than to
* break existing (wrongly written) libcurl applications, we leave it as-is
* but with this warning attached.
*/
#include "curl.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void CURLM;
typedef enum {
CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or
curl_multi_socket*() soon */
CURLM_OK,
CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */
CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */
CURLM_OUT_OF_MEMORY, /* if you ever get this, you're in deep sh*t */
CURLM_INTERNAL_ERROR, /* this is a libcurl bug */
CURLM_BAD_SOCKET, /* the passed in socket argument did not match */
CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */
CURLM_LAST
} CURLMcode;
/* just to make code nicer when using curl_multi_socket() you can now check
for CURLM_CALL_MULTI_SOCKET too in the same style it works for
curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */
#define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM
typedef enum {
CURLMSG_NONE, /* first, not used */
CURLMSG_DONE, /* This easy handle has completed. 'result' contains
the CURLcode of the transfer */
CURLMSG_LAST /* last, not used */
} CURLMSG;
struct CURLMsg {
CURLMSG msg; /* what this message means */
CURL *easy_handle; /* the handle it concerns */
union {
void *whatever; /* message-specific data */
CURLcode result; /* return code for transfer */
} data;
};
typedef struct CURLMsg CURLMsg;
/* Based on poll(2) structure and values.
* We don't use pollfd and POLL* constants explicitly
* to cover platforms without poll(). */
#define CURL_WAIT_POLLIN 0x0001
#define CURL_WAIT_POLLPRI 0x0002
#define CURL_WAIT_POLLOUT 0x0004
struct curl_waitfd {
curl_socket_t fd;
short events;
short revents; /* not supported yet */
};
/*
* Name: curl_multi_init()
*
* Desc: inititalize multi-style curl usage
*
* Returns: a new CURLM handle to use in all 'curl_multi' functions.
*/
CURL_EXTERN CURLM *curl_multi_init(void);
/*
* Name: curl_multi_add_handle()
*
* Desc: add a standard curl handle to the multi stack
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *multi_handle,
CURL *curl_handle);
/*
* Name: curl_multi_remove_handle()
*
* Desc: removes a curl handle from the multi stack again
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *multi_handle,
CURL *curl_handle);
/*
* Name: curl_multi_fdset()
*
* Desc: Ask curl for its fd_set sets. The app can use these to select() or
* poll() on. We want curl_multi_perform() called as soon as one of
* them are ready.
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *multi_handle,
fd_set *read_fd_set,
fd_set *write_fd_set,
fd_set *exc_fd_set,
int *max_fd);
/*
* Name: curl_multi_wait()
*
* Desc: Poll on all fds within a CURLM set as well as any
* additional fds passed to the function.
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_wait(CURLM *multi_handle,
struct curl_waitfd extra_fds[],
unsigned int extra_nfds,
int timeout_ms,
int *ret);
/*
* Name: curl_multi_perform()
*
* Desc: When the app thinks there's data available for curl it calls this
* function to read/write whatever there is right now. This returns
* as soon as the reads and writes are done. This function does not
* require that there actually is data available for reading or that
* data can be written, it can be called just in case. It returns
* the number of handles that still transfer data in the second
* argument's integer-pointer.
*
* Returns: CURLMcode type, general multi error code. *NOTE* that this only
* returns errors etc regarding the whole multi stack. There might
* still have occurred problems on invidual transfers even when this
* returns OK.
*/
CURL_EXTERN CURLMcode curl_multi_perform(CURLM *multi_handle,
int *running_handles);
/*
* Name: curl_multi_cleanup()
*
* Desc: Cleans up and removes a whole multi stack. It does not free or
* touch any individual easy handles in any way. We need to define
* in what state those handles will be if this function is called
* in the middle of a transfer.
*
* Returns: CURLMcode type, general multi error code.
*/
CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle);
/*
* Name: curl_multi_info_read()
*
* Desc: Ask the multi handle if there's any messages/informationals from
* the individual transfers. Messages include informationals such as
* error code from the transfer or just the fact that a transfer is
* completed. More details on these should be written down as well.
*
* Repeated calls to this function will return a new struct each
* time, until a special "end of msgs" struct is returned as a signal
* that there is no more to get at this point.
*
* The data the returned pointer points to will not survive calling
* curl_multi_cleanup().
*
* The 'CURLMsg' struct is meant to be very simple and only contain
* very basic informations. If more involved information is wanted,
* we will provide the particular "transfer handle" in that struct
* and that should/could/would be used in subsequent
* curl_easy_getinfo() calls (or similar). The point being that we
* must never expose complex structs to applications, as then we'll
* undoubtably get backwards compatibility problems in the future.
*
* Returns: A pointer to a filled-in struct, or NULL if it failed or ran out
* of structs. It also writes the number of messages left in the
* queue (after this read) in the integer the second argument points
* to.
*/
CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *multi_handle,
int *msgs_in_queue);
/*
* Name: curl_multi_strerror()
*
* Desc: The curl_multi_strerror function may be used to turn a CURLMcode
* value into the equivalent human readable error string. This is
* useful for printing meaningful error messages.
*
* Returns: A pointer to a zero-terminated error message.
*/
CURL_EXTERN const char *curl_multi_strerror(CURLMcode);
/*
* Name: curl_multi_socket() and
* curl_multi_socket_all()
*
* Desc: An alternative version of curl_multi_perform() that allows the
* application to pass in one of the file descriptors that have been
* detected to have "action" on them and let libcurl perform.
* See man page for details.
*/
#define CURL_POLL_NONE 0
#define CURL_POLL_IN 1
#define CURL_POLL_OUT 2
#define CURL_POLL_INOUT 3
#define CURL_POLL_REMOVE 4
#define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD
#define CURL_CSELECT_IN 0x01
#define CURL_CSELECT_OUT 0x02
#define CURL_CSELECT_ERR 0x04
typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */
curl_socket_t s, /* socket */
int what, /* see above */
void *userp, /* private callback
pointer */
void *socketp); /* private socket
pointer */
/*
* Name: curl_multi_timer_callback
*
* Desc: Called by libcurl whenever the library detects a change in the
* maximum number of milliseconds the app is allowed to wait before
* curl_multi_socket() or curl_multi_perform() must be called
* (to allow libcurl's timed events to take place).
*
* Returns: The callback should return zero.
*/
typedef int (*curl_multi_timer_callback)(CURLM *multi, /* multi handle */
long timeout_ms, /* see above */
void *userp); /* private callback
pointer */
CURL_EXTERN CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s,
int *running_handles);
CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *multi_handle,
curl_socket_t s,
int ev_bitmask,
int *running_handles);
CURL_EXTERN CURLMcode curl_multi_socket_all(CURLM *multi_handle,
int *running_handles);
#ifndef CURL_ALLOW_OLD_MULTI_SOCKET
/* This macro below was added in 7.16.3 to push users who recompile to use
the new curl_multi_socket_action() instead of the old curl_multi_socket()
*/
#define curl_multi_socket(x,y,z) curl_multi_socket_action(x,y,0,z)
#endif
/*
* Name: curl_multi_timeout()
*
* Desc: Returns the maximum number of milliseconds the app is allowed to
* wait before curl_multi_socket() or curl_multi_perform() must be
* called (to allow libcurl's timed events to take place).
*
* Returns: CURLM error code.
*/
CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *multi_handle,
long *milliseconds);
#undef CINIT /* re-using the same name as in curl.h */
#ifdef CURL_ISOCPP
#define CINIT(name,type,num) CURLMOPT_ ## name = CURLOPTTYPE_ ## type + num
#else
/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */
#define LONG CURLOPTTYPE_LONG
#define OBJECTPOINT CURLOPTTYPE_OBJECTPOINT
#define FUNCTIONPOINT CURLOPTTYPE_FUNCTIONPOINT
#define OFF_T CURLOPTTYPE_OFF_T
#define CINIT(name,type,number) CURLMOPT_/**/name = type + number
#endif
typedef enum {
/* This is the socket callback function pointer */
CINIT(SOCKETFUNCTION, FUNCTIONPOINT, 1),
/* This is the argument passed to the socket callback */
CINIT(SOCKETDATA, OBJECTPOINT, 2),
/* set to 1 to enable pipelining for this multi handle */
CINIT(PIPELINING, LONG, 3),
/* This is the timer callback function pointer */
CINIT(TIMERFUNCTION, FUNCTIONPOINT, 4),
/* This is the argument passed to the timer callback */
CINIT(TIMERDATA, OBJECTPOINT, 5),
/* maximum number of entries in the connection cache */
CINIT(MAXCONNECTS, LONG, 6),
CURLMOPT_LASTENTRY /* the last unused */
} CURLMoption;
/*
* Name: curl_multi_setopt()
*
* Desc: Sets options for the multi handle.
*
* Returns: CURLM error code.
*/
CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *multi_handle,
CURLMoption option, ...);
/*
* Name: curl_multi_assign()
*
* Desc: This function sets an association in the multi handle between the
* given socket and a private pointer of the application. This is
* (only) useful for curl_multi_socket uses.
*
* Returns: CURLM error code.
*/
CURL_EXTERN CURLMcode curl_multi_assign(CURLM *multi_handle,
curl_socket_t sockfd, void *sockp);
#ifdef __cplusplus
} /* end of extern "C" */
#endif
#endif
| 13,836 | 36.096515 | 79 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/libcurl/include/curl/curlbuild.h
|
#ifndef __CURL_CURLBUILD_H
#define __CURL_CURLBUILD_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2010, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* ================================================================ */
/* NOTES FOR CONFIGURE CAPABLE SYSTEMS */
/* ================================================================ */
/*
* NOTE 1:
* -------
*
* See file include/curl/curlbuild.h.in, run configure, and forget
* that this file exists it is only used for non-configure systems.
* But you can keep reading if you want ;-)
*
*/
/* ================================================================ */
/* NOTES FOR NON-CONFIGURE SYSTEMS */
/* ================================================================ */
/*
* NOTE 1:
* -------
*
* Nothing in this file is intended to be modified or adjusted by the
* curl library user nor by the curl library builder.
*
* If you think that something actually needs to be changed, adjusted
* or fixed in this file, then, report it on the libcurl development
* mailing list: http://cool.haxx.se/mailman/listinfo/curl-library/
*
* Try to keep one section per platform, compiler and architecture,
* otherwise, if an existing section is reused for a different one and
* later on the original is adjusted, probably the piggybacking one can
* be adversely changed.
*
* In order to differentiate between platforms/compilers/architectures
* use only compiler built in predefined preprocessor symbols.
*
* This header file shall only export symbols which are 'curl' or 'CURL'
* prefixed, otherwise public name space would be polluted.
*
* NOTE 2:
* -------
*
* For any given platform/compiler curl_off_t must be typedef'ed to a
* 64-bit wide signed integral data type. The width of this data type
* must remain constant and independent of any possible large file
* support settings.
*
* As an exception to the above, curl_off_t shall be typedef'ed to a
* 32-bit wide signed integral data type if there is no 64-bit type.
*
* As a general rule, curl_off_t shall not be mapped to off_t. This
* rule shall only be violated if off_t is the only 64-bit data type
* available and the size of off_t is independent of large file support
* settings. Keep your build on the safe side avoiding an off_t gating.
* If you have a 64-bit off_t then take for sure that another 64-bit
* data type exists, dig deeper and you will find it.
*
* NOTE 3:
* -------
*
* Right now you might be staring at file include/curl/curlbuild.h.dist or
* at file include/curl/curlbuild.h, this is due to the following reason:
* file include/curl/curlbuild.h.dist is renamed to include/curl/curlbuild.h
* when the libcurl source code distribution archive file is created.
*
* File include/curl/curlbuild.h.dist is not included in the distribution
* archive. File include/curl/curlbuild.h is not present in the git tree.
*
* The distributed include/curl/curlbuild.h file is only intended to be used
* on systems which can not run the also distributed configure script.
*
* On systems capable of running the configure script, the configure process
* will overwrite the distributed include/curl/curlbuild.h file with one that
* is suitable and specific to the library being configured and built, which
* is generated from the include/curl/curlbuild.h.in template file.
*
* If you check out from git on a non-configure platform, you must run the
* appropriate buildconf* script to set up curlbuild.h and other local files.
*
*/
/* ================================================================ */
/* DEFINITION OF THESE SYMBOLS SHALL NOT TAKE PLACE ANYWHERE ELSE */
/* ================================================================ */
#ifdef CURL_SIZEOF_LONG
# error "CURL_SIZEOF_LONG shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SIZEOF_LONG_already_defined
#endif
#ifdef CURL_TYPEOF_CURL_SOCKLEN_T
# error "CURL_TYPEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_already_defined
#endif
#ifdef CURL_SIZEOF_CURL_SOCKLEN_T
# error "CURL_SIZEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_already_defined
#endif
#ifdef CURL_TYPEOF_CURL_OFF_T
# error "CURL_TYPEOF_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_already_defined
#endif
#ifdef CURL_FORMAT_CURL_OFF_T
# error "CURL_FORMAT_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_already_defined
#endif
#ifdef CURL_FORMAT_CURL_OFF_TU
# error "CURL_FORMAT_CURL_OFF_TU shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_already_defined
#endif
#ifdef CURL_FORMAT_OFF_T
# error "CURL_FORMAT_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_FORMAT_OFF_T_already_defined
#endif
#ifdef CURL_SIZEOF_CURL_OFF_T
# error "CURL_SIZEOF_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_already_defined
#endif
#ifdef CURL_SUFFIX_CURL_OFF_T
# error "CURL_SUFFIX_CURL_OFF_T shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_already_defined
#endif
#ifdef CURL_SUFFIX_CURL_OFF_TU
# error "CURL_SUFFIX_CURL_OFF_TU shall not be defined except in curlbuild.h"
Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_already_defined
#endif
/* ================================================================ */
/* EXTERNAL INTERFACE SETTINGS FOR NON-CONFIGURE SYSTEMS ONLY */
/* ================================================================ */
#if defined(__DJGPP__) || defined(__GO32__)
# if defined(__DJGPP__) && (__DJGPP__ > 1)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# else
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__SALFORDC__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__BORLANDC__)
# if (__BORLANDC__ < 0x520)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# else
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_FORMAT_OFF_T "%I64d"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T i64
# define CURL_SUFFIX_CURL_OFF_TU ui64
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__TURBOC__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__WATCOMC__)
# if defined(__386__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_FORMAT_OFF_T "%I64d"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T i64
# define CURL_SUFFIX_CURL_OFF_TU ui64
# else
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__POCC__)
# if (__POCC__ < 280)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# elif defined(_MSC_VER)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_FORMAT_OFF_T "%I64d"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T i64
# define CURL_SUFFIX_CURL_OFF_TU ui64
# else
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__LCC__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__SYMBIAN32__)
# if defined(__EABI__) /* Treat all ARM compilers equally */
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(__CW32__)
# pragma longlong on
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(__VC32__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__MWERKS__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(_WIN32_WCE)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_FORMAT_OFF_T "%I64d"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T i64
# define CURL_SUFFIX_CURL_OFF_TU ui64
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__MINGW32__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_FORMAT_OFF_T "%I64d"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__VMS)
# if defined(__VAX)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# else
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
#elif defined(__OS400__)
# if defined(__ILEC400__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
# endif
#elif defined(__MVS__)
# if defined(__IBMC__) || defined(__IBMCPP__)
# if defined(_ILP32)
# define CURL_SIZEOF_LONG 4
# elif defined(_LP64)
# define CURL_SIZEOF_LONG 8
# endif
# if defined(_LONG_LONG)
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(_LP64)
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# else
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
# endif
#elif defined(__370__)
# if defined(__IBMC__) || defined(__IBMCPP__)
# if defined(_ILP32)
# define CURL_SIZEOF_LONG 4
# elif defined(_LP64)
# define CURL_SIZEOF_LONG 8
# endif
# if defined(_LONG_LONG)
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(_LP64)
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# else
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
# endif
#elif defined(TPF)
# define CURL_SIZEOF_LONG 8
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
/* ===================================== */
/* KEEP MSVC THE PENULTIMATE ENTRY */
/* ===================================== */
#elif defined(_MSC_VER)
# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T __int64
# define CURL_FORMAT_CURL_OFF_T "I64d"
# define CURL_FORMAT_CURL_OFF_TU "I64u"
# define CURL_FORMAT_OFF_T "%I64d"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T i64
# define CURL_SUFFIX_CURL_OFF_TU ui64
# else
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 4
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T int
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
/* ===================================== */
/* KEEP GENERIC GCC THE LAST ENTRY */
/* ===================================== */
#elif defined(__GNUC__)
# if defined(__i386__) || defined(__ppc__)
# define CURL_SIZEOF_LONG 4
# define CURL_TYPEOF_CURL_OFF_T long long
# define CURL_FORMAT_CURL_OFF_T "lld"
# define CURL_FORMAT_CURL_OFF_TU "llu"
# define CURL_FORMAT_OFF_T "%lld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T LL
# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(__x86_64__) || defined(__ppc64__)
# define CURL_SIZEOF_LONG 8
# define CURL_TYPEOF_CURL_OFF_T long
# define CURL_FORMAT_CURL_OFF_T "ld"
# define CURL_FORMAT_CURL_OFF_TU "lu"
# define CURL_FORMAT_OFF_T "%ld"
# define CURL_SIZEOF_CURL_OFF_T 8
# define CURL_SUFFIX_CURL_OFF_T L
# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
# define CURL_SIZEOF_CURL_SOCKLEN_T 4
# define CURL_PULL_SYS_TYPES_H 1
# define CURL_PULL_SYS_SOCKET_H 1
#else
# error "Unknown non-configure build target!"
Error Compilation_aborted_Unknown_non_configure_build_target
#endif
/* CURL_PULL_SYS_TYPES_H is defined above when inclusion of header file */
/* sys/types.h is required here to properly make type definitions below. */
#ifdef CURL_PULL_SYS_TYPES_H
# include <sys/types.h>
#endif
/* CURL_PULL_SYS_SOCKET_H is defined above when inclusion of header file */
/* sys/socket.h is required here to properly make type definitions below. */
#ifdef CURL_PULL_SYS_SOCKET_H
# include <sys/socket.h>
#endif
/* Data type definition of curl_socklen_t. */
#ifdef CURL_TYPEOF_CURL_SOCKLEN_T
typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t;
#endif
/* Data type definition of curl_off_t. */
#ifdef CURL_TYPEOF_CURL_OFF_T
typedef CURL_TYPEOF_CURL_OFF_T curl_off_t;
#endif
#endif /* __CURL_CURLBUILD_H */
| 22,192 | 37.001712 | 80 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/libcurl/include/curl/curl.h
|
#ifndef __CURL_CURL_H
#define __CURL_CURL_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2012, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
* If you have libcurl problems, all docs and details are found here:
* http://curl.haxx.se/libcurl/
*
* curl-library mailing list subscription and unsubscription web interface:
* http://cool.haxx.se/mailman/listinfo/curl-library/
*/
#include "curlver.h" /* libcurl version defines */
#include "curlbuild.h" /* libcurl build definitions */
#include "curlrules.h" /* libcurl rules enforcement */
/*
* Define WIN32 when build target is Win32 API
*/
#if (defined(_WIN32) || defined(__WIN32__)) && \
!defined(WIN32) && !defined(__SYMBIAN32__)
#define WIN32
#endif
#include <stdio.h>
#include <limits.h>
#if defined(__FreeBSD__) && (__FreeBSD__ >= 2)
/* Needed for __FreeBSD_version symbol definition */
#include <osreldate.h>
#endif
/* The include stuff here below is mainly for time_t! */
#include <sys/types.h>
#include <time.h>
#if defined(WIN32) && !defined(_WIN32_WCE) && !defined(__CYGWIN__)
#if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H) || defined(__LWIP_OPT_H__))
/* The check above prevents the winsock2 inclusion if winsock.h already was
included, since they can't co-exist without problems */
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#endif
/* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish
libc5-based Linux systems. Only include it on systems that are known to
require it! */
#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \
defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \
defined(ANDROID) || defined(__ANDROID__) || \
(defined(__FreeBSD_version) && (__FreeBSD_version < 800000))
#include <sys/select.h>
#endif
#if !defined(WIN32) && !defined(_WIN32_WCE)
#include <sys/socket.h>
#endif
#if !defined(WIN32) && !defined(__WATCOMC__) && !defined(__VXWORKS__)
#include <sys/time.h>
#endif
#ifdef __BEOS__
#include <support/SupportDefs.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef void CURL;
/*
* Decorate exportable functions for Win32 and Symbian OS DLL linking.
* This avoids using a .def file for building libcurl.dll.
*/
#if (defined(WIN32) || defined(_WIN32) || defined(__SYMBIAN32__)) && \
!defined(CURL_STATICLIB)
#if defined(BUILDING_LIBCURL)
#define CURL_EXTERN __declspec(dllexport)
#else
#define CURL_EXTERN __declspec(dllimport)
#endif
#else
#ifdef CURL_HIDDEN_SYMBOLS
/*
* This definition is used to make external definitions visible in the
* shared library when symbols are hidden by default. It makes no
* difference when compiling applications whether this is set or not,
* only when compiling the library.
*/
#define CURL_EXTERN CURL_EXTERN_SYMBOL
#else
#define CURL_EXTERN
#endif
#endif
#ifndef curl_socket_typedef
/* socket typedef */
#if defined(WIN32) && !defined(__LWIP_OPT_H__)
typedef SOCKET curl_socket_t;
#define CURL_SOCKET_BAD INVALID_SOCKET
#else
typedef int curl_socket_t;
#define CURL_SOCKET_BAD -1
#endif
#define curl_socket_typedef
#endif /* curl_socket_typedef */
struct curl_httppost {
struct curl_httppost *next; /* next entry in the list */
char *name; /* pointer to allocated name */
long namelength; /* length of name length */
char *contents; /* pointer to allocated data contents */
long contentslength; /* length of contents field */
char *buffer; /* pointer to allocated buffer contents */
long bufferlength; /* length of buffer field */
char *contenttype; /* Content-Type */
struct curl_slist* contentheader; /* list of extra headers for this form */
struct curl_httppost *more; /* if one field name has more than one
file, this link should link to following
files */
long flags; /* as defined below */
#define HTTPPOST_FILENAME (1<<0) /* specified content is a file name */
#define HTTPPOST_READFILE (1<<1) /* specified content is a file name */
#define HTTPPOST_PTRNAME (1<<2) /* name is only stored pointer
do not free in formfree */
#define HTTPPOST_PTRCONTENTS (1<<3) /* contents is only stored pointer
do not free in formfree */
#define HTTPPOST_BUFFER (1<<4) /* upload file from buffer */
#define HTTPPOST_PTRBUFFER (1<<5) /* upload file from pointer contents */
#define HTTPPOST_CALLBACK (1<<6) /* upload file contents by using the
regular read callback to get the data
and pass the given pointer as custom
pointer */
char *showfilename; /* The file name to show. If not set, the
actual file name will be used (if this
is a file part) */
void *userp; /* custom pointer used for
HTTPPOST_CALLBACK posts */
};
typedef int (*curl_progress_callback)(void *clientp,
double dltotal,
double dlnow,
double ultotal,
double ulnow);
#ifndef CURL_MAX_WRITE_SIZE
/* Tests have proven that 20K is a very bad buffer size for uploads on
Windows, while 16K for some odd reason performed a lot better.
We do the ifndef check to allow this value to easier be changed at build
time for those who feel adventurous. The practical minimum is about
400 bytes since libcurl uses a buffer of this size as a scratch area
(unrelated to network send operations). */
#define CURL_MAX_WRITE_SIZE 16384
#endif
#ifndef CURL_MAX_HTTP_HEADER
/* The only reason to have a max limit for this is to avoid the risk of a bad
server feeding libcurl with a never-ending header that will cause reallocs
infinitely */
#define CURL_MAX_HTTP_HEADER (100*1024)
#endif
/* This is a magic return code for the write callback that, when returned,
will signal libcurl to pause receiving on the current transfer. */
#define CURL_WRITEFUNC_PAUSE 0x10000001
typedef size_t (*curl_write_callback)(char *buffer,
size_t size,
size_t nitems,
void *outstream);
/* enumeration of file types */
typedef enum {
CURLFILETYPE_FILE = 0,
CURLFILETYPE_DIRECTORY,
CURLFILETYPE_SYMLINK,
CURLFILETYPE_DEVICE_BLOCK,
CURLFILETYPE_DEVICE_CHAR,
CURLFILETYPE_NAMEDPIPE,
CURLFILETYPE_SOCKET,
CURLFILETYPE_DOOR, /* is possible only on Sun Solaris now */
CURLFILETYPE_UNKNOWN /* should never occur */
} curlfiletype;
#define CURLFINFOFLAG_KNOWN_FILENAME (1<<0)
#define CURLFINFOFLAG_KNOWN_FILETYPE (1<<1)
#define CURLFINFOFLAG_KNOWN_TIME (1<<2)
#define CURLFINFOFLAG_KNOWN_PERM (1<<3)
#define CURLFINFOFLAG_KNOWN_UID (1<<4)
#define CURLFINFOFLAG_KNOWN_GID (1<<5)
#define CURLFINFOFLAG_KNOWN_SIZE (1<<6)
#define CURLFINFOFLAG_KNOWN_HLINKCOUNT (1<<7)
/* Content of this structure depends on information which is known and is
achievable (e.g. by FTP LIST parsing). Please see the url_easy_setopt(3) man
page for callbacks returning this structure -- some fields are mandatory,
some others are optional. The FLAG field has special meaning. */
struct curl_fileinfo {
char *filename;
curlfiletype filetype;
time_t time;
unsigned int perm;
int uid;
int gid;
curl_off_t size;
long int hardlinks;
struct {
/* If some of these fields is not NULL, it is a pointer to b_data. */
char *time;
char *perm;
char *user;
char *group;
char *target; /* pointer to the target filename of a symlink */
} strings;
unsigned int flags;
/* used internally */
char * b_data;
size_t b_size;
size_t b_used;
};
/* return codes for CURLOPT_CHUNK_BGN_FUNCTION */
#define CURL_CHUNK_BGN_FUNC_OK 0
#define CURL_CHUNK_BGN_FUNC_FAIL 1 /* tell the lib to end the task */
#define CURL_CHUNK_BGN_FUNC_SKIP 2 /* skip this chunk over */
/* if splitting of data transfer is enabled, this callback is called before
download of an individual chunk started. Note that parameter "remains" works
only for FTP wildcard downloading (for now), otherwise is not used */
typedef long (*curl_chunk_bgn_callback)(const void *transfer_info,
void *ptr,
int remains);
/* return codes for CURLOPT_CHUNK_END_FUNCTION */
#define CURL_CHUNK_END_FUNC_OK 0
#define CURL_CHUNK_END_FUNC_FAIL 1 /* tell the lib to end the task */
/* If splitting of data transfer is enabled this callback is called after
download of an individual chunk finished.
Note! After this callback was set then it have to be called FOR ALL chunks.
Even if downloading of this chunk was skipped in CHUNK_BGN_FUNC.
This is the reason why we don't need "transfer_info" parameter in this
callback and we are not interested in "remains" parameter too. */
typedef long (*curl_chunk_end_callback)(void *ptr);
/* return codes for FNMATCHFUNCTION */
#define CURL_FNMATCHFUNC_MATCH 0 /* string corresponds to the pattern */
#define CURL_FNMATCHFUNC_NOMATCH 1 /* pattern doesn't match the string */
#define CURL_FNMATCHFUNC_FAIL 2 /* an error occurred */
/* callback type for wildcard downloading pattern matching. If the
string matches the pattern, return CURL_FNMATCHFUNC_MATCH value, etc. */
typedef int (*curl_fnmatch_callback)(void *ptr,
const char *pattern,
const char *string);
/* These are the return codes for the seek callbacks */
#define CURL_SEEKFUNC_OK 0
#define CURL_SEEKFUNC_FAIL 1 /* fail the entire transfer */
#define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking can't be done, so
libcurl might try other means instead */
typedef int (*curl_seek_callback)(void *instream,
curl_off_t offset,
int origin); /* 'whence' */
/* This is a return code for the read callback that, when returned, will
signal libcurl to immediately abort the current transfer. */
#define CURL_READFUNC_ABORT 0x10000000
/* This is a return code for the read callback that, when returned, will
signal libcurl to pause sending data on the current transfer. */
#define CURL_READFUNC_PAUSE 0x10000001
typedef size_t (*curl_read_callback)(char *buffer,
size_t size,
size_t nitems,
void *instream);
typedef enum {
CURLSOCKTYPE_IPCXN, /* socket created for a specific IP connection */
CURLSOCKTYPE_ACCEPT, /* socket created by accept() call */
CURLSOCKTYPE_LAST /* never use */
} curlsocktype;
/* The return code from the sockopt_callback can signal information back
to libcurl: */
#define CURL_SOCKOPT_OK 0
#define CURL_SOCKOPT_ERROR 1 /* causes libcurl to abort and return
CURLE_ABORTED_BY_CALLBACK */
#define CURL_SOCKOPT_ALREADY_CONNECTED 2
typedef int (*curl_sockopt_callback)(void *clientp,
curl_socket_t curlfd,
curlsocktype purpose);
struct curl_sockaddr {
int family;
int socktype;
int protocol;
unsigned int addrlen; /* addrlen was a socklen_t type before 7.18.0 but it
turned really ugly and painful on the systems that
lack this type */
struct sockaddr addr;
};
typedef curl_socket_t
(*curl_opensocket_callback)(void *clientp,
curlsocktype purpose,
struct curl_sockaddr *address);
typedef int
(*curl_closesocket_callback)(void *clientp, curl_socket_t item);
typedef enum {
CURLIOE_OK, /* I/O operation successful */
CURLIOE_UNKNOWNCMD, /* command was unknown to callback */
CURLIOE_FAILRESTART, /* failed to restart the read */
CURLIOE_LAST /* never use */
} curlioerr;
typedef enum {
CURLIOCMD_NOP, /* no operation */
CURLIOCMD_RESTARTREAD, /* restart the read stream from start */
CURLIOCMD_LAST /* never use */
} curliocmd;
typedef curlioerr (*curl_ioctl_callback)(CURL *handle,
int cmd,
void *clientp);
/*
* The following typedef's are signatures of malloc, free, realloc, strdup and
* calloc respectively. Function pointers of these types can be passed to the
* curl_global_init_mem() function to set user defined memory management
* callback routines.
*/
typedef void *(*curl_malloc_callback)(size_t size);
typedef void (*curl_free_callback)(void *ptr);
typedef void *(*curl_realloc_callback)(void *ptr, size_t size);
typedef char *(*curl_strdup_callback)(const char *str);
typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size);
/* the kind of data that is passed to information_callback*/
typedef enum {
CURLINFO_TEXT = 0,
CURLINFO_HEADER_IN, /* 1 */
CURLINFO_HEADER_OUT, /* 2 */
CURLINFO_DATA_IN, /* 3 */
CURLINFO_DATA_OUT, /* 4 */
CURLINFO_SSL_DATA_IN, /* 5 */
CURLINFO_SSL_DATA_OUT, /* 6 */
CURLINFO_END
} curl_infotype;
typedef int (*curl_debug_callback)
(CURL *handle, /* the handle/transfer this concerns */
curl_infotype type, /* what kind of data */
char *data, /* points to the data */
size_t size, /* size of the data pointed to */
void *userptr); /* whatever the user please */
/* All possible error codes from all sorts of curl functions. Future versions
may return other values, stay prepared.
Always add new return codes last. Never *EVER* remove any. The return
codes must remain the same!
*/
typedef enum {
CURLE_OK = 0,
CURLE_UNSUPPORTED_PROTOCOL, /* 1 */
CURLE_FAILED_INIT, /* 2 */
CURLE_URL_MALFORMAT, /* 3 */
CURLE_NOT_BUILT_IN, /* 4 - [was obsoleted in August 2007 for
7.17.0, reused in April 2011 for 7.21.5] */
CURLE_COULDNT_RESOLVE_PROXY, /* 5 */
CURLE_COULDNT_RESOLVE_HOST, /* 6 */
CURLE_COULDNT_CONNECT, /* 7 */
CURLE_FTP_WEIRD_SERVER_REPLY, /* 8 */
CURLE_REMOTE_ACCESS_DENIED, /* 9 a service was denied by the server
due to lack of access - when login fails
this is not returned. */
CURLE_FTP_ACCEPT_FAILED, /* 10 - [was obsoleted in April 2006 for
7.15.4, reused in Dec 2011 for 7.24.0]*/
CURLE_FTP_WEIRD_PASS_REPLY, /* 11 */
CURLE_FTP_ACCEPT_TIMEOUT, /* 12 - timeout occurred accepting server
[was obsoleted in August 2007 for 7.17.0,
reused in Dec 2011 for 7.24.0]*/
CURLE_FTP_WEIRD_PASV_REPLY, /* 13 */
CURLE_FTP_WEIRD_227_FORMAT, /* 14 */
CURLE_FTP_CANT_GET_HOST, /* 15 */
CURLE_OBSOLETE16, /* 16 - NOT USED */
CURLE_FTP_COULDNT_SET_TYPE, /* 17 */
CURLE_PARTIAL_FILE, /* 18 */
CURLE_FTP_COULDNT_RETR_FILE, /* 19 */
CURLE_OBSOLETE20, /* 20 - NOT USED */
CURLE_QUOTE_ERROR, /* 21 - quote command failure */
CURLE_HTTP_RETURNED_ERROR, /* 22 */
CURLE_WRITE_ERROR, /* 23 */
CURLE_OBSOLETE24, /* 24 - NOT USED */
CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */
CURLE_READ_ERROR, /* 26 - couldn't open/read from file */
CURLE_OUT_OF_MEMORY, /* 27 */
/* Note: CURLE_OUT_OF_MEMORY may sometimes indicate a conversion error
instead of a memory allocation error if CURL_DOES_CONVERSIONS
is defined
*/
CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */
CURLE_OBSOLETE29, /* 29 - NOT USED */
CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */
CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */
CURLE_OBSOLETE32, /* 32 - NOT USED */
CURLE_RANGE_ERROR, /* 33 - RANGE "command" didn't work */
CURLE_HTTP_POST_ERROR, /* 34 */
CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */
CURLE_BAD_DOWNLOAD_RESUME, /* 36 - couldn't resume download */
CURLE_FILE_COULDNT_READ_FILE, /* 37 */
CURLE_LDAP_CANNOT_BIND, /* 38 */
CURLE_LDAP_SEARCH_FAILED, /* 39 */
CURLE_OBSOLETE40, /* 40 - NOT USED */
CURLE_FUNCTION_NOT_FOUND, /* 41 */
CURLE_ABORTED_BY_CALLBACK, /* 42 */
CURLE_BAD_FUNCTION_ARGUMENT, /* 43 */
CURLE_OBSOLETE44, /* 44 - NOT USED */
CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */
CURLE_OBSOLETE46, /* 46 - NOT USED */
CURLE_TOO_MANY_REDIRECTS , /* 47 - catch endless re-direct loops */
CURLE_UNKNOWN_OPTION, /* 48 - User specified an unknown option */
CURLE_TELNET_OPTION_SYNTAX , /* 49 - Malformed telnet option */
CURLE_OBSOLETE50, /* 50 - NOT USED */
CURLE_PEER_FAILED_VERIFICATION, /* 51 - peer's certificate or fingerprint
wasn't verified fine */
CURLE_GOT_NOTHING, /* 52 - when this is a specific error */
CURLE_SSL_ENGINE_NOTFOUND, /* 53 - SSL crypto engine not found */
CURLE_SSL_ENGINE_SETFAILED, /* 54 - can not set SSL crypto engine as
default */
CURLE_SEND_ERROR, /* 55 - failed sending network data */
CURLE_RECV_ERROR, /* 56 - failure in receiving network data */
CURLE_OBSOLETE57, /* 57 - NOT IN USE */
CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */
CURLE_SSL_CIPHER, /* 59 - couldn't use specified cipher */
CURLE_SSL_CACERT, /* 60 - problem with the CA cert (path?) */
CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized/bad encoding */
CURLE_LDAP_INVALID_URL, /* 62 - Invalid LDAP URL */
CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */
CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */
CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind
that failed */
CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialise ENGINE */
CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not
accepted and we failed to login */
CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */
CURLE_TFTP_PERM, /* 69 - permission problem on server */
CURLE_REMOTE_DISK_FULL, /* 70 - out of disk space on server */
CURLE_TFTP_ILLEGAL, /* 71 - Illegal TFTP operation */
CURLE_TFTP_UNKNOWNID, /* 72 - Unknown transfer ID */
CURLE_REMOTE_FILE_EXISTS, /* 73 - File already exists */
CURLE_TFTP_NOSUCHUSER, /* 74 - No such user */
CURLE_CONV_FAILED, /* 75 - conversion failed */
CURLE_CONV_REQD, /* 76 - caller must register conversion
callbacks using curl_easy_setopt options
CURLOPT_CONV_FROM_NETWORK_FUNCTION,
CURLOPT_CONV_TO_NETWORK_FUNCTION, and
CURLOPT_CONV_FROM_UTF8_FUNCTION */
CURLE_SSL_CACERT_BADFILE, /* 77 - could not load CACERT file, missing
or wrong format */
CURLE_REMOTE_FILE_NOT_FOUND, /* 78 - remote file not found */
CURLE_SSH, /* 79 - error from the SSH layer, somewhat
generic so the error message will be of
interest when this has happened */
CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL
connection */
CURLE_AGAIN, /* 81 - socket is not ready for send/recv,
wait till it's ready and try again (Added
in 7.18.2) */
CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or
wrong format (Added in 7.19.0) */
CURLE_SSL_ISSUER_ERROR, /* 83 - Issuer check failed. (Added in
7.19.0) */
CURLE_FTP_PRET_FAILED, /* 84 - a PRET command failed */
CURLE_RTSP_CSEQ_ERROR, /* 85 - mismatch of RTSP CSeq numbers */
CURLE_RTSP_SESSION_ERROR, /* 86 - mismatch of RTSP Session Ids */
CURLE_FTP_BAD_FILE_LIST, /* 87 - unable to parse FTP file list */
CURLE_CHUNK_FAILED, /* 88 - chunk callback reported error */
CURL_LAST /* never use! */
} CURLcode;
#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
the obsolete stuff removed! */
/* Previously obsoletes error codes re-used in 7.24.0 */
#define CURLE_OBSOLETE10 CURLE_FTP_ACCEPT_FAILED
#define CURLE_OBSOLETE12 CURLE_FTP_ACCEPT_TIMEOUT
/* compatibility with older names */
#define CURLOPT_ENCODING CURLOPT_ACCEPT_ENCODING
/* The following were added in 7.21.5, April 2011 */
#define CURLE_UNKNOWN_TELNET_OPTION CURLE_UNKNOWN_OPTION
/* The following were added in 7.17.1 */
/* These are scheduled to disappear by 2009 */
#define CURLE_SSL_PEER_CERTIFICATE CURLE_PEER_FAILED_VERIFICATION
/* The following were added in 7.17.0 */
/* These are scheduled to disappear by 2009 */
#define CURLE_OBSOLETE CURLE_OBSOLETE50 /* no one should be using this! */
#define CURLE_BAD_PASSWORD_ENTERED CURLE_OBSOLETE46
#define CURLE_BAD_CALLING_ORDER CURLE_OBSOLETE44
#define CURLE_FTP_USER_PASSWORD_INCORRECT CURLE_OBSOLETE10
#define CURLE_FTP_CANT_RECONNECT CURLE_OBSOLETE16
#define CURLE_FTP_COULDNT_GET_SIZE CURLE_OBSOLETE32
#define CURLE_FTP_COULDNT_SET_ASCII CURLE_OBSOLETE29
#define CURLE_FTP_WEIRD_USER_REPLY CURLE_OBSOLETE12
#define CURLE_FTP_WRITE_ERROR CURLE_OBSOLETE20
#define CURLE_LIBRARY_NOT_FOUND CURLE_OBSOLETE40
#define CURLE_MALFORMAT_USER CURLE_OBSOLETE24
#define CURLE_SHARE_IN_USE CURLE_OBSOLETE57
#define CURLE_URL_MALFORMAT_USER CURLE_NOT_BUILT_IN
#define CURLE_FTP_ACCESS_DENIED CURLE_REMOTE_ACCESS_DENIED
#define CURLE_FTP_COULDNT_SET_BINARY CURLE_FTP_COULDNT_SET_TYPE
#define CURLE_FTP_QUOTE_ERROR CURLE_QUOTE_ERROR
#define CURLE_TFTP_DISKFULL CURLE_REMOTE_DISK_FULL
#define CURLE_TFTP_EXISTS CURLE_REMOTE_FILE_EXISTS
#define CURLE_HTTP_RANGE_ERROR CURLE_RANGE_ERROR
#define CURLE_FTP_SSL_FAILED CURLE_USE_SSL_FAILED
/* The following were added earlier */
#define CURLE_OPERATION_TIMEOUTED CURLE_OPERATION_TIMEDOUT
#define CURLE_HTTP_NOT_FOUND CURLE_HTTP_RETURNED_ERROR
#define CURLE_HTTP_PORT_FAILED CURLE_INTERFACE_FAILED
#define CURLE_FTP_COULDNT_STOR_FILE CURLE_UPLOAD_FAILED
#define CURLE_FTP_PARTIAL_FILE CURLE_PARTIAL_FILE
#define CURLE_FTP_BAD_DOWNLOAD_RESUME CURLE_BAD_DOWNLOAD_RESUME
/* This was the error code 50 in 7.7.3 and a few earlier versions, this
is no longer used by libcurl but is instead #defined here only to not
make programs break */
#define CURLE_ALREADY_COMPLETE 99999
#endif /*!CURL_NO_OLDIES*/
/* This prototype applies to all conversion callbacks */
typedef CURLcode (*curl_conv_callback)(char *buffer, size_t length);
typedef CURLcode (*curl_ssl_ctx_callback)(CURL *curl, /* easy handle */
void *ssl_ctx, /* actually an
OpenSSL SSL_CTX */
void *userptr);
typedef enum {
CURLPROXY_HTTP = 0, /* added in 7.10, new in 7.19.4 default is to use
CONNECT HTTP/1.1 */
CURLPROXY_HTTP_1_0 = 1, /* added in 7.19.4, force to use CONNECT
HTTP/1.0 */
CURLPROXY_SOCKS4 = 4, /* support added in 7.15.2, enum existed already
in 7.10 */
CURLPROXY_SOCKS5 = 5, /* added in 7.10 */
CURLPROXY_SOCKS4A = 6, /* added in 7.18.0 */
CURLPROXY_SOCKS5_HOSTNAME = 7 /* Use the SOCKS5 protocol but pass along the
host name rather than the IP address. added
in 7.18.0 */
} curl_proxytype; /* this enum was added in 7.10 */
/*
* Bitmasks for CURLOPT_HTTPAUTH and CURLOPT_PROXYAUTH options:
*
* CURLAUTH_NONE - No HTTP authentication
* CURLAUTH_BASIC - HTTP Basic authentication (default)
* CURLAUTH_DIGEST - HTTP Digest authentication
* CURLAUTH_GSSNEGOTIATE - HTTP GSS-Negotiate authentication
* CURLAUTH_NTLM - HTTP NTLM authentication
* CURLAUTH_DIGEST_IE - HTTP Digest authentication with IE flavour
* CURLAUTH_NTLM_WB - HTTP NTLM authentication delegated to winbind helper
* CURLAUTH_ONLY - Use together with a single other type to force no
* authentication or just that single type
* CURLAUTH_ANY - All fine types set
* CURLAUTH_ANYSAFE - All fine types except Basic
*/
#define CURLAUTH_NONE ((unsigned long)0)
#define CURLAUTH_BASIC (((unsigned long)1)<<0)
#define CURLAUTH_DIGEST (((unsigned long)1)<<1)
#define CURLAUTH_GSSNEGOTIATE (((unsigned long)1)<<2)
#define CURLAUTH_NTLM (((unsigned long)1)<<3)
#define CURLAUTH_DIGEST_IE (((unsigned long)1)<<4)
#define CURLAUTH_NTLM_WB (((unsigned long)1)<<5)
#define CURLAUTH_ONLY (((unsigned long)1)<<31)
#define CURLAUTH_ANY (~CURLAUTH_DIGEST_IE)
#define CURLAUTH_ANYSAFE (~(CURLAUTH_BASIC|CURLAUTH_DIGEST_IE))
#define CURLSSH_AUTH_ANY ~0 /* all types supported by the server */
#define CURLSSH_AUTH_NONE 0 /* none allowed, silly but complete */
#define CURLSSH_AUTH_PUBLICKEY (1<<0) /* public/private key files */
#define CURLSSH_AUTH_PASSWORD (1<<1) /* password */
#define CURLSSH_AUTH_HOST (1<<2) /* host key files */
#define CURLSSH_AUTH_KEYBOARD (1<<3) /* keyboard interactive */
#define CURLSSH_AUTH_AGENT (1<<4) /* agent (ssh-agent, pageant...) */
#define CURLSSH_AUTH_DEFAULT CURLSSH_AUTH_ANY
#define CURLGSSAPI_DELEGATION_NONE 0 /* no delegation (default) */
#define CURLGSSAPI_DELEGATION_POLICY_FLAG (1<<0) /* if permitted by policy */
#define CURLGSSAPI_DELEGATION_FLAG (1<<1) /* delegate always */
#define CURL_ERROR_SIZE 256
struct curl_khkey {
const char *key; /* points to a zero-terminated string encoded with base64
if len is zero, otherwise to the "raw" data */
size_t len;
enum type {
CURLKHTYPE_UNKNOWN,
CURLKHTYPE_RSA1,
CURLKHTYPE_RSA,
CURLKHTYPE_DSS
} keytype;
};
/* this is the set of return values expected from the curl_sshkeycallback
callback */
enum curl_khstat {
CURLKHSTAT_FINE_ADD_TO_FILE,
CURLKHSTAT_FINE,
CURLKHSTAT_REJECT, /* reject the connection, return an error */
CURLKHSTAT_DEFER, /* do not accept it, but we can't answer right now so
this causes a CURLE_DEFER error but otherwise the
connection will be left intact etc */
CURLKHSTAT_LAST /* not for use, only a marker for last-in-list */
};
/* this is the set of status codes pass in to the callback */
enum curl_khmatch {
CURLKHMATCH_OK, /* match */
CURLKHMATCH_MISMATCH, /* host found, key mismatch! */
CURLKHMATCH_MISSING, /* no matching host/key found */
CURLKHMATCH_LAST /* not for use, only a marker for last-in-list */
};
typedef int
(*curl_sshkeycallback) (CURL *easy, /* easy handle */
const struct curl_khkey *knownkey, /* known */
const struct curl_khkey *foundkey, /* found */
enum curl_khmatch, /* libcurl's view on the keys */
void *clientp); /* custom pointer passed from app */
/* parameter for the CURLOPT_USE_SSL option */
typedef enum {
CURLUSESSL_NONE, /* do not attempt to use SSL */
CURLUSESSL_TRY, /* try using SSL, proceed anyway otherwise */
CURLUSESSL_CONTROL, /* SSL for the control connection or fail */
CURLUSESSL_ALL, /* SSL for all communication or fail */
CURLUSESSL_LAST /* not an option, never use */
} curl_usessl;
/* Definition of bits for the CURLOPT_SSL_OPTIONS argument: */
/* - ALLOW_BEAST tells libcurl to allow the BEAST SSL vulnerability in the
name of improving interoperability with older servers. Some SSL libraries
have introduced work-arounds for this flaw but those work-arounds sometimes
make the SSL communication fail. To regain functionality with those broken
servers, a user can this way allow the vulnerability back. */
#define CURLSSLOPT_ALLOW_BEAST (1<<0)
#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
the obsolete stuff removed! */
/* Backwards compatibility with older names */
/* These are scheduled to disappear by 2009 */
#define CURLFTPSSL_NONE CURLUSESSL_NONE
#define CURLFTPSSL_TRY CURLUSESSL_TRY
#define CURLFTPSSL_CONTROL CURLUSESSL_CONTROL
#define CURLFTPSSL_ALL CURLUSESSL_ALL
#define CURLFTPSSL_LAST CURLUSESSL_LAST
#define curl_ftpssl curl_usessl
#endif /*!CURL_NO_OLDIES*/
/* parameter for the CURLOPT_FTP_SSL_CCC option */
typedef enum {
CURLFTPSSL_CCC_NONE, /* do not send CCC */
CURLFTPSSL_CCC_PASSIVE, /* Let the server initiate the shutdown */
CURLFTPSSL_CCC_ACTIVE, /* Initiate the shutdown */
CURLFTPSSL_CCC_LAST /* not an option, never use */
} curl_ftpccc;
/* parameter for the CURLOPT_FTPSSLAUTH option */
typedef enum {
CURLFTPAUTH_DEFAULT, /* let libcurl decide */
CURLFTPAUTH_SSL, /* use "AUTH SSL" */
CURLFTPAUTH_TLS, /* use "AUTH TLS" */
CURLFTPAUTH_LAST /* not an option, never use */
} curl_ftpauth;
/* parameter for the CURLOPT_FTP_CREATE_MISSING_DIRS option */
typedef enum {
CURLFTP_CREATE_DIR_NONE, /* do NOT create missing dirs! */
CURLFTP_CREATE_DIR, /* (FTP/SFTP) if CWD fails, try MKD and then CWD
again if MKD succeeded, for SFTP this does
similar magic */
CURLFTP_CREATE_DIR_RETRY, /* (FTP only) if CWD fails, try MKD and then CWD
again even if MKD failed! */
CURLFTP_CREATE_DIR_LAST /* not an option, never use */
} curl_ftpcreatedir;
/* parameter for the CURLOPT_FTP_FILEMETHOD option */
typedef enum {
CURLFTPMETHOD_DEFAULT, /* let libcurl pick */
CURLFTPMETHOD_MULTICWD, /* single CWD operation for each path part */
CURLFTPMETHOD_NOCWD, /* no CWD at all */
CURLFTPMETHOD_SINGLECWD, /* one CWD to full dir, then work on file */
CURLFTPMETHOD_LAST /* not an option, never use */
} curl_ftpmethod;
/* CURLPROTO_ defines are for the CURLOPT_*PROTOCOLS options */
#define CURLPROTO_HTTP (1<<0)
#define CURLPROTO_HTTPS (1<<1)
#define CURLPROTO_FTP (1<<2)
#define CURLPROTO_FTPS (1<<3)
#define CURLPROTO_SCP (1<<4)
#define CURLPROTO_SFTP (1<<5)
#define CURLPROTO_TELNET (1<<6)
#define CURLPROTO_LDAP (1<<7)
#define CURLPROTO_LDAPS (1<<8)
#define CURLPROTO_DICT (1<<9)
#define CURLPROTO_FILE (1<<10)
#define CURLPROTO_TFTP (1<<11)
#define CURLPROTO_IMAP (1<<12)
#define CURLPROTO_IMAPS (1<<13)
#define CURLPROTO_POP3 (1<<14)
#define CURLPROTO_POP3S (1<<15)
#define CURLPROTO_SMTP (1<<16)
#define CURLPROTO_SMTPS (1<<17)
#define CURLPROTO_RTSP (1<<18)
#define CURLPROTO_RTMP (1<<19)
#define CURLPROTO_RTMPT (1<<20)
#define CURLPROTO_RTMPE (1<<21)
#define CURLPROTO_RTMPTE (1<<22)
#define CURLPROTO_RTMPS (1<<23)
#define CURLPROTO_RTMPTS (1<<24)
#define CURLPROTO_GOPHER (1<<25)
#define CURLPROTO_ALL (~0) /* enable everything */
/* long may be 32 or 64 bits, but we should never depend on anything else
but 32 */
#define CURLOPTTYPE_LONG 0
#define CURLOPTTYPE_OBJECTPOINT 10000
#define CURLOPTTYPE_FUNCTIONPOINT 20000
#define CURLOPTTYPE_OFF_T 30000
/* name is uppercase CURLOPT_<name>,
type is one of the defined CURLOPTTYPE_<type>
number is unique identifier */
#ifdef CINIT
#undef CINIT
#endif
#ifdef CURL_ISOCPP
#define CINIT(na,t,nu) CURLOPT_ ## na = CURLOPTTYPE_ ## t + nu
#else
/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */
#define LONG CURLOPTTYPE_LONG
#define OBJECTPOINT CURLOPTTYPE_OBJECTPOINT
#define FUNCTIONPOINT CURLOPTTYPE_FUNCTIONPOINT
#define OFF_T CURLOPTTYPE_OFF_T
#define CINIT(name,type,number) CURLOPT_/**/name = type + number
#endif
/*
* This macro-mania below setups the CURLOPT_[what] enum, to be used with
* curl_easy_setopt(). The first argument in the CINIT() macro is the [what]
* word.
*/
typedef enum {
/* This is the FILE * or void * the regular output should be written to. */
CINIT(FILE, OBJECTPOINT, 1),
/* The full URL to get/put */
CINIT(URL, OBJECTPOINT, 2),
/* Port number to connect to, if other than default. */
CINIT(PORT, LONG, 3),
/* Name of proxy to use. */
CINIT(PROXY, OBJECTPOINT, 4),
/* "name:password" to use when fetching. */
CINIT(USERPWD, OBJECTPOINT, 5),
/* "name:password" to use with proxy. */
CINIT(PROXYUSERPWD, OBJECTPOINT, 6),
/* Range to get, specified as an ASCII string. */
CINIT(RANGE, OBJECTPOINT, 7),
/* not used */
/* Specified file stream to upload from (use as input): */
CINIT(INFILE, OBJECTPOINT, 9),
/* Buffer to receive error messages in, must be at least CURL_ERROR_SIZE
* bytes big. If this is not used, error messages go to stderr instead: */
CINIT(ERRORBUFFER, OBJECTPOINT, 10),
/* Function that will be called to store the output (instead of fwrite). The
* parameters will use fwrite() syntax, make sure to follow them. */
CINIT(WRITEFUNCTION, FUNCTIONPOINT, 11),
/* Function that will be called to read the input (instead of fread). The
* parameters will use fread() syntax, make sure to follow them. */
CINIT(READFUNCTION, FUNCTIONPOINT, 12),
/* Time-out the read operation after this amount of seconds */
CINIT(TIMEOUT, LONG, 13),
/* If the CURLOPT_INFILE is used, this can be used to inform libcurl about
* how large the file being sent really is. That allows better error
* checking and better verifies that the upload was successful. -1 means
* unknown size.
*
* For large file support, there is also a _LARGE version of the key
* which takes an off_t type, allowing platforms with larger off_t
* sizes to handle larger files. See below for INFILESIZE_LARGE.
*/
CINIT(INFILESIZE, LONG, 14),
/* POST static input fields. */
CINIT(POSTFIELDS, OBJECTPOINT, 15),
/* Set the referrer page (needed by some CGIs) */
CINIT(REFERER, OBJECTPOINT, 16),
/* Set the FTP PORT string (interface name, named or numerical IP address)
Use i.e '-' to use default address. */
CINIT(FTPPORT, OBJECTPOINT, 17),
/* Set the User-Agent string (examined by some CGIs) */
CINIT(USERAGENT, OBJECTPOINT, 18),
/* If the download receives less than "low speed limit" bytes/second
* during "low speed time" seconds, the operations is aborted.
* You could i.e if you have a pretty high speed connection, abort if
* it is less than 2000 bytes/sec during 20 seconds.
*/
/* Set the "low speed limit" */
CINIT(LOW_SPEED_LIMIT, LONG, 19),
/* Set the "low speed time" */
CINIT(LOW_SPEED_TIME, LONG, 20),
/* Set the continuation offset.
*
* Note there is also a _LARGE version of this key which uses
* off_t types, allowing for large file offsets on platforms which
* use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE.
*/
CINIT(RESUME_FROM, LONG, 21),
/* Set cookie in request: */
CINIT(COOKIE, OBJECTPOINT, 22),
/* This points to a linked list of headers, struct curl_slist kind */
CINIT(HTTPHEADER, OBJECTPOINT, 23),
/* This points to a linked list of post entries, struct curl_httppost */
CINIT(HTTPPOST, OBJECTPOINT, 24),
/* name of the file keeping your private SSL-certificate */
CINIT(SSLCERT, OBJECTPOINT, 25),
/* password for the SSL or SSH private key */
CINIT(KEYPASSWD, OBJECTPOINT, 26),
/* send TYPE parameter? */
CINIT(CRLF, LONG, 27),
/* send linked-list of QUOTE commands */
CINIT(QUOTE, OBJECTPOINT, 28),
/* send FILE * or void * to store headers to, if you use a callback it
is simply passed to the callback unmodified */
CINIT(WRITEHEADER, OBJECTPOINT, 29),
/* point to a file to read the initial cookies from, also enables
"cookie awareness" */
CINIT(COOKIEFILE, OBJECTPOINT, 31),
/* What version to specifically try to use.
See CURL_SSLVERSION defines below. */
CINIT(SSLVERSION, LONG, 32),
/* What kind of HTTP time condition to use, see defines */
CINIT(TIMECONDITION, LONG, 33),
/* Time to use with the above condition. Specified in number of seconds
since 1 Jan 1970 */
CINIT(TIMEVALUE, LONG, 34),
/* 35 = OBSOLETE */
/* Custom request, for customizing the get command like
HTTP: DELETE, TRACE and others
FTP: to use a different list command
*/
CINIT(CUSTOMREQUEST, OBJECTPOINT, 36),
/* HTTP request, for odd commands like DELETE, TRACE and others */
CINIT(STDERR, OBJECTPOINT, 37),
/* 38 is not used */
/* send linked-list of post-transfer QUOTE commands */
CINIT(POSTQUOTE, OBJECTPOINT, 39),
CINIT(WRITEINFO, OBJECTPOINT, 40), /* DEPRECATED, do not use! */
CINIT(VERBOSE, LONG, 41), /* talk a lot */
CINIT(HEADER, LONG, 42), /* throw the header out too */
CINIT(NOPROGRESS, LONG, 43), /* shut off the progress meter */
CINIT(NOBODY, LONG, 44), /* use HEAD to get http document */
CINIT(FAILONERROR, LONG, 45), /* no output on http error codes >= 300 */
CINIT(UPLOAD, LONG, 46), /* this is an upload */
CINIT(POST, LONG, 47), /* HTTP POST method */
CINIT(DIRLISTONLY, LONG, 48), /* bare names when listing directories */
CINIT(APPEND, LONG, 50), /* Append instead of overwrite on upload! */
/* Specify whether to read the user+password from the .netrc or the URL.
* This must be one of the CURL_NETRC_* enums below. */
CINIT(NETRC, LONG, 51),
CINIT(FOLLOWLOCATION, LONG, 52), /* use Location: Luke! */
CINIT(TRANSFERTEXT, LONG, 53), /* transfer data in text/ASCII format */
CINIT(PUT, LONG, 54), /* HTTP PUT */
/* 55 = OBSOLETE */
/* Function that will be called instead of the internal progress display
* function. This function should be defined as the curl_progress_callback
* prototype defines. */
CINIT(PROGRESSFUNCTION, FUNCTIONPOINT, 56),
/* Data passed to the progress callback */
CINIT(PROGRESSDATA, OBJECTPOINT, 57),
/* We want the referrer field set automatically when following locations */
CINIT(AUTOREFERER, LONG, 58),
/* Port of the proxy, can be set in the proxy string as well with:
"[host]:[port]" */
CINIT(PROXYPORT, LONG, 59),
/* size of the POST input data, if strlen() is not good to use */
CINIT(POSTFIELDSIZE, LONG, 60),
/* tunnel non-http operations through a HTTP proxy */
CINIT(HTTPPROXYTUNNEL, LONG, 61),
/* Set the interface string to use as outgoing network interface */
CINIT(INTERFACE, OBJECTPOINT, 62),
/* Set the krb4/5 security level, this also enables krb4/5 awareness. This
* is a string, 'clear', 'safe', 'confidential' or 'private'. If the string
* is set but doesn't match one of these, 'private' will be used. */
CINIT(KRBLEVEL, OBJECTPOINT, 63),
/* Set if we should verify the peer in ssl handshake, set 1 to verify. */
CINIT(SSL_VERIFYPEER, LONG, 64),
/* The CApath or CAfile used to validate the peer certificate
this option is used only if SSL_VERIFYPEER is true */
CINIT(CAINFO, OBJECTPOINT, 65),
/* 66 = OBSOLETE */
/* 67 = OBSOLETE */
/* Maximum number of http redirects to follow */
CINIT(MAXREDIRS, LONG, 68),
/* Pass a long set to 1 to get the date of the requested document (if
possible)! Pass a zero to shut it off. */
CINIT(FILETIME, LONG, 69),
/* This points to a linked list of telnet options */
CINIT(TELNETOPTIONS, OBJECTPOINT, 70),
/* Max amount of cached alive connections */
CINIT(MAXCONNECTS, LONG, 71),
CINIT(CLOSEPOLICY, LONG, 72), /* DEPRECATED, do not use! */
/* 73 = OBSOLETE */
/* Set to explicitly use a new connection for the upcoming transfer.
Do not use this unless you're absolutely sure of this, as it makes the
operation slower and is less friendly for the network. */
CINIT(FRESH_CONNECT, LONG, 74),
/* Set to explicitly forbid the upcoming transfer's connection to be re-used
when done. Do not use this unless you're absolutely sure of this, as it
makes the operation slower and is less friendly for the network. */
CINIT(FORBID_REUSE, LONG, 75),
/* Set to a file name that contains random data for libcurl to use to
seed the random engine when doing SSL connects. */
CINIT(RANDOM_FILE, OBJECTPOINT, 76),
/* Set to the Entropy Gathering Daemon socket pathname */
CINIT(EGDSOCKET, OBJECTPOINT, 77),
/* Time-out connect operations after this amount of seconds, if connects are
OK within this time, then fine... This only aborts the connect phase. */
CINIT(CONNECTTIMEOUT, LONG, 78),
/* Function that will be called to store headers (instead of fwrite). The
* parameters will use fwrite() syntax, make sure to follow them. */
CINIT(HEADERFUNCTION, FUNCTIONPOINT, 79),
/* Set this to force the HTTP request to get back to GET. Only really usable
if POST, PUT or a custom request have been used first.
*/
CINIT(HTTPGET, LONG, 80),
/* Set if we should verify the Common name from the peer certificate in ssl
* handshake, set 1 to check existence, 2 to ensure that it matches the
* provided hostname. */
CINIT(SSL_VERIFYHOST, LONG, 81),
/* Specify which file name to write all known cookies in after completed
operation. Set file name to "-" (dash) to make it go to stdout. */
CINIT(COOKIEJAR, OBJECTPOINT, 82),
/* Specify which SSL ciphers to use */
CINIT(SSL_CIPHER_LIST, OBJECTPOINT, 83),
/* Specify which HTTP version to use! This must be set to one of the
CURL_HTTP_VERSION* enums set below. */
CINIT(HTTP_VERSION, LONG, 84),
/* Specifically switch on or off the FTP engine's use of the EPSV command. By
default, that one will always be attempted before the more traditional
PASV command. */
CINIT(FTP_USE_EPSV, LONG, 85),
/* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */
CINIT(SSLCERTTYPE, OBJECTPOINT, 86),
/* name of the file keeping your private SSL-key */
CINIT(SSLKEY, OBJECTPOINT, 87),
/* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */
CINIT(SSLKEYTYPE, OBJECTPOINT, 88),
/* crypto engine for the SSL-sub system */
CINIT(SSLENGINE, OBJECTPOINT, 89),
/* set the crypto engine for the SSL-sub system as default
the param has no meaning...
*/
CINIT(SSLENGINE_DEFAULT, LONG, 90),
/* Non-zero value means to use the global dns cache */
CINIT(DNS_USE_GLOBAL_CACHE, LONG, 91), /* DEPRECATED, do not use! */
/* DNS cache timeout */
CINIT(DNS_CACHE_TIMEOUT, LONG, 92),
/* send linked-list of pre-transfer QUOTE commands */
CINIT(PREQUOTE, OBJECTPOINT, 93),
/* set the debug function */
CINIT(DEBUGFUNCTION, FUNCTIONPOINT, 94),
/* set the data for the debug function */
CINIT(DEBUGDATA, OBJECTPOINT, 95),
/* mark this as start of a cookie session */
CINIT(COOKIESESSION, LONG, 96),
/* The CApath directory used to validate the peer certificate
this option is used only if SSL_VERIFYPEER is true */
CINIT(CAPATH, OBJECTPOINT, 97),
/* Instruct libcurl to use a smaller receive buffer */
CINIT(BUFFERSIZE, LONG, 98),
/* Instruct libcurl to not use any signal/alarm handlers, even when using
timeouts. This option is useful for multi-threaded applications.
See libcurl-the-guide for more background information. */
CINIT(NOSIGNAL, LONG, 99),
/* Provide a CURLShare for mutexing non-ts data */
CINIT(SHARE, OBJECTPOINT, 100),
/* indicates type of proxy. accepted values are CURLPROXY_HTTP (default),
CURLPROXY_SOCKS4, CURLPROXY_SOCKS4A and CURLPROXY_SOCKS5. */
CINIT(PROXYTYPE, LONG, 101),
/* Set the Accept-Encoding string. Use this to tell a server you would like
the response to be compressed. Before 7.21.6, this was known as
CURLOPT_ENCODING */
CINIT(ACCEPT_ENCODING, OBJECTPOINT, 102),
/* Set pointer to private data */
CINIT(PRIVATE, OBJECTPOINT, 103),
/* Set aliases for HTTP 200 in the HTTP Response header */
CINIT(HTTP200ALIASES, OBJECTPOINT, 104),
/* Continue to send authentication (user+password) when following locations,
even when hostname changed. This can potentially send off the name
and password to whatever host the server decides. */
CINIT(UNRESTRICTED_AUTH, LONG, 105),
/* Specifically switch on or off the FTP engine's use of the EPRT command (
it also disables the LPRT attempt). By default, those ones will always be
attempted before the good old traditional PORT command. */
CINIT(FTP_USE_EPRT, LONG, 106),
/* Set this to a bitmask value to enable the particular authentications
methods you like. Use this in combination with CURLOPT_USERPWD.
Note that setting multiple bits may cause extra network round-trips. */
CINIT(HTTPAUTH, LONG, 107),
/* Set the ssl context callback function, currently only for OpenSSL ssl_ctx
in second argument. The function must be matching the
curl_ssl_ctx_callback proto. */
CINIT(SSL_CTX_FUNCTION, FUNCTIONPOINT, 108),
/* Set the userdata for the ssl context callback function's third
argument */
CINIT(SSL_CTX_DATA, OBJECTPOINT, 109),
/* FTP Option that causes missing dirs to be created on the remote server.
In 7.19.4 we introduced the convenience enums for this option using the
CURLFTP_CREATE_DIR prefix.
*/
CINIT(FTP_CREATE_MISSING_DIRS, LONG, 110),
/* Set this to a bitmask value to enable the particular authentications
methods you like. Use this in combination with CURLOPT_PROXYUSERPWD.
Note that setting multiple bits may cause extra network round-trips. */
CINIT(PROXYAUTH, LONG, 111),
/* FTP option that changes the timeout, in seconds, associated with
getting a response. This is different from transfer timeout time and
essentially places a demand on the FTP server to acknowledge commands
in a timely manner. */
CINIT(FTP_RESPONSE_TIMEOUT, LONG, 112),
#define CURLOPT_SERVER_RESPONSE_TIMEOUT CURLOPT_FTP_RESPONSE_TIMEOUT
/* Set this option to one of the CURL_IPRESOLVE_* defines (see below) to
tell libcurl to resolve names to those IP versions only. This only has
affect on systems with support for more than one, i.e IPv4 _and_ IPv6. */
CINIT(IPRESOLVE, LONG, 113),
/* Set this option to limit the size of a file that will be downloaded from
an HTTP or FTP server.
Note there is also _LARGE version which adds large file support for
platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */
CINIT(MAXFILESIZE, LONG, 114),
/* See the comment for INFILESIZE above, but in short, specifies
* the size of the file being uploaded. -1 means unknown.
*/
CINIT(INFILESIZE_LARGE, OFF_T, 115),
/* Sets the continuation offset. There is also a LONG version of this;
* look above for RESUME_FROM.
*/
CINIT(RESUME_FROM_LARGE, OFF_T, 116),
/* Sets the maximum size of data that will be downloaded from
* an HTTP or FTP server. See MAXFILESIZE above for the LONG version.
*/
CINIT(MAXFILESIZE_LARGE, OFF_T, 117),
/* Set this option to the file name of your .netrc file you want libcurl
to parse (using the CURLOPT_NETRC option). If not set, libcurl will do
a poor attempt to find the user's home directory and check for a .netrc
file in there. */
CINIT(NETRC_FILE, OBJECTPOINT, 118),
/* Enable SSL/TLS for FTP, pick one of:
CURLUSESSL_TRY - try using SSL, proceed anyway otherwise
CURLUSESSL_CONTROL - SSL for the control connection or fail
CURLUSESSL_ALL - SSL for all communication or fail
*/
CINIT(USE_SSL, LONG, 119),
/* The _LARGE version of the standard POSTFIELDSIZE option */
CINIT(POSTFIELDSIZE_LARGE, OFF_T, 120),
/* Enable/disable the TCP Nagle algorithm */
CINIT(TCP_NODELAY, LONG, 121),
/* 122 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
/* 123 OBSOLETE. Gone in 7.16.0 */
/* 124 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
/* 125 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
/* 126 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
/* 127 OBSOLETE. Gone in 7.16.0 */
/* 128 OBSOLETE. Gone in 7.16.0 */
/* When FTP over SSL/TLS is selected (with CURLOPT_USE_SSL), this option
can be used to change libcurl's default action which is to first try
"AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK
response has been received.
Available parameters are:
CURLFTPAUTH_DEFAULT - let libcurl decide
CURLFTPAUTH_SSL - try "AUTH SSL" first, then TLS
CURLFTPAUTH_TLS - try "AUTH TLS" first, then SSL
*/
CINIT(FTPSSLAUTH, LONG, 129),
CINIT(IOCTLFUNCTION, FUNCTIONPOINT, 130),
CINIT(IOCTLDATA, OBJECTPOINT, 131),
/* 132 OBSOLETE. Gone in 7.16.0 */
/* 133 OBSOLETE. Gone in 7.16.0 */
/* zero terminated string for pass on to the FTP server when asked for
"account" info */
CINIT(FTP_ACCOUNT, OBJECTPOINT, 134),
/* feed cookies into cookie engine */
CINIT(COOKIELIST, OBJECTPOINT, 135),
/* ignore Content-Length */
CINIT(IGNORE_CONTENT_LENGTH, LONG, 136),
/* Set to non-zero to skip the IP address received in a 227 PASV FTP server
response. Typically used for FTP-SSL purposes but is not restricted to
that. libcurl will then instead use the same IP address it used for the
control connection. */
CINIT(FTP_SKIP_PASV_IP, LONG, 137),
/* Select "file method" to use when doing FTP, see the curl_ftpmethod
above. */
CINIT(FTP_FILEMETHOD, LONG, 138),
/* Local port number to bind the socket to */
CINIT(LOCALPORT, LONG, 139),
/* Number of ports to try, including the first one set with LOCALPORT.
Thus, setting it to 1 will make no additional attempts but the first.
*/
CINIT(LOCALPORTRANGE, LONG, 140),
/* no transfer, set up connection and let application use the socket by
extracting it with CURLINFO_LASTSOCKET */
CINIT(CONNECT_ONLY, LONG, 141),
/* Function that will be called to convert from the
network encoding (instead of using the iconv calls in libcurl) */
CINIT(CONV_FROM_NETWORK_FUNCTION, FUNCTIONPOINT, 142),
/* Function that will be called to convert to the
network encoding (instead of using the iconv calls in libcurl) */
CINIT(CONV_TO_NETWORK_FUNCTION, FUNCTIONPOINT, 143),
/* Function that will be called to convert from UTF8
(instead of using the iconv calls in libcurl)
Note that this is used only for SSL certificate processing */
CINIT(CONV_FROM_UTF8_FUNCTION, FUNCTIONPOINT, 144),
/* if the connection proceeds too quickly then need to slow it down */
/* limit-rate: maximum number of bytes per second to send or receive */
CINIT(MAX_SEND_SPEED_LARGE, OFF_T, 145),
CINIT(MAX_RECV_SPEED_LARGE, OFF_T, 146),
/* Pointer to command string to send if USER/PASS fails. */
CINIT(FTP_ALTERNATIVE_TO_USER, OBJECTPOINT, 147),
/* callback function for setting socket options */
CINIT(SOCKOPTFUNCTION, FUNCTIONPOINT, 148),
CINIT(SOCKOPTDATA, OBJECTPOINT, 149),
/* set to 0 to disable session ID re-use for this transfer, default is
enabled (== 1) */
CINIT(SSL_SESSIONID_CACHE, LONG, 150),
/* allowed SSH authentication methods */
CINIT(SSH_AUTH_TYPES, LONG, 151),
/* Used by scp/sftp to do public/private key authentication */
CINIT(SSH_PUBLIC_KEYFILE, OBJECTPOINT, 152),
CINIT(SSH_PRIVATE_KEYFILE, OBJECTPOINT, 153),
/* Send CCC (Clear Command Channel) after authentication */
CINIT(FTP_SSL_CCC, LONG, 154),
/* Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution */
CINIT(TIMEOUT_MS, LONG, 155),
CINIT(CONNECTTIMEOUT_MS, LONG, 156),
/* set to zero to disable the libcurl's decoding and thus pass the raw body
data to the application even when it is encoded/compressed */
CINIT(HTTP_TRANSFER_DECODING, LONG, 157),
CINIT(HTTP_CONTENT_DECODING, LONG, 158),
/* Permission used when creating new files and directories on the remote
server for protocols that support it, SFTP/SCP/FILE */
CINIT(NEW_FILE_PERMS, LONG, 159),
CINIT(NEW_DIRECTORY_PERMS, LONG, 160),
/* Set the behaviour of POST when redirecting. Values must be set to one
of CURL_REDIR* defines below. This used to be called CURLOPT_POST301 */
CINIT(POSTREDIR, LONG, 161),
/* used by scp/sftp to verify the host's public key */
CINIT(SSH_HOST_PUBLIC_KEY_MD5, OBJECTPOINT, 162),
/* Callback function for opening socket (instead of socket(2)). Optionally,
callback is able change the address or refuse to connect returning
CURL_SOCKET_BAD. The callback should have type
curl_opensocket_callback */
CINIT(OPENSOCKETFUNCTION, FUNCTIONPOINT, 163),
CINIT(OPENSOCKETDATA, OBJECTPOINT, 164),
/* POST volatile input fields. */
CINIT(COPYPOSTFIELDS, OBJECTPOINT, 165),
/* set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy */
CINIT(PROXY_TRANSFER_MODE, LONG, 166),
/* Callback function for seeking in the input stream */
CINIT(SEEKFUNCTION, FUNCTIONPOINT, 167),
CINIT(SEEKDATA, OBJECTPOINT, 168),
/* CRL file */
CINIT(CRLFILE, OBJECTPOINT, 169),
/* Issuer certificate */
CINIT(ISSUERCERT, OBJECTPOINT, 170),
/* (IPv6) Address scope */
CINIT(ADDRESS_SCOPE, LONG, 171),
/* Collect certificate chain info and allow it to get retrievable with
CURLINFO_CERTINFO after the transfer is complete. (Unfortunately) only
working with OpenSSL-powered builds. */
CINIT(CERTINFO, LONG, 172),
/* "name" and "pwd" to use when fetching. */
CINIT(USERNAME, OBJECTPOINT, 173),
CINIT(PASSWORD, OBJECTPOINT, 174),
/* "name" and "pwd" to use with Proxy when fetching. */
CINIT(PROXYUSERNAME, OBJECTPOINT, 175),
CINIT(PROXYPASSWORD, OBJECTPOINT, 176),
/* Comma separated list of hostnames defining no-proxy zones. These should
match both hostnames directly, and hostnames within a domain. For
example, local.com will match local.com and www.local.com, but NOT
notlocal.com or www.notlocal.com. For compatibility with other
implementations of this, .local.com will be considered to be the same as
local.com. A single * is the only valid wildcard, and effectively
disables the use of proxy. */
CINIT(NOPROXY, OBJECTPOINT, 177),
/* block size for TFTP transfers */
CINIT(TFTP_BLKSIZE, LONG, 178),
/* Socks Service */
CINIT(SOCKS5_GSSAPI_SERVICE, OBJECTPOINT, 179),
/* Socks Service */
CINIT(SOCKS5_GSSAPI_NEC, LONG, 180),
/* set the bitmask for the protocols that are allowed to be used for the
transfer, which thus helps the app which takes URLs from users or other
external inputs and want to restrict what protocol(s) to deal
with. Defaults to CURLPROTO_ALL. */
CINIT(PROTOCOLS, LONG, 181),
/* set the bitmask for the protocols that libcurl is allowed to follow to,
as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
to be set in both bitmasks to be allowed to get redirected to. Defaults
to all protocols except FILE and SCP. */
CINIT(REDIR_PROTOCOLS, LONG, 182),
/* set the SSH knownhost file name to use */
CINIT(SSH_KNOWNHOSTS, OBJECTPOINT, 183),
/* set the SSH host key callback, must point to a curl_sshkeycallback
function */
CINIT(SSH_KEYFUNCTION, FUNCTIONPOINT, 184),
/* set the SSH host key callback custom pointer */
CINIT(SSH_KEYDATA, OBJECTPOINT, 185),
/* set the SMTP mail originator */
CINIT(MAIL_FROM, OBJECTPOINT, 186),
/* set the SMTP mail receiver(s) */
CINIT(MAIL_RCPT, OBJECTPOINT, 187),
/* FTP: send PRET before PASV */
CINIT(FTP_USE_PRET, LONG, 188),
/* RTSP request method (OPTIONS, SETUP, PLAY, etc...) */
CINIT(RTSP_REQUEST, LONG, 189),
/* The RTSP session identifier */
CINIT(RTSP_SESSION_ID, OBJECTPOINT, 190),
/* The RTSP stream URI */
CINIT(RTSP_STREAM_URI, OBJECTPOINT, 191),
/* The Transport: header to use in RTSP requests */
CINIT(RTSP_TRANSPORT, OBJECTPOINT, 192),
/* Manually initialize the client RTSP CSeq for this handle */
CINIT(RTSP_CLIENT_CSEQ, LONG, 193),
/* Manually initialize the server RTSP CSeq for this handle */
CINIT(RTSP_SERVER_CSEQ, LONG, 194),
/* The stream to pass to INTERLEAVEFUNCTION. */
CINIT(INTERLEAVEDATA, OBJECTPOINT, 195),
/* Let the application define a custom write method for RTP data */
CINIT(INTERLEAVEFUNCTION, FUNCTIONPOINT, 196),
/* Turn on wildcard matching */
CINIT(WILDCARDMATCH, LONG, 197),
/* Directory matching callback called before downloading of an
individual file (chunk) started */
CINIT(CHUNK_BGN_FUNCTION, FUNCTIONPOINT, 198),
/* Directory matching callback called after the file (chunk)
was downloaded, or skipped */
CINIT(CHUNK_END_FUNCTION, FUNCTIONPOINT, 199),
/* Change match (fnmatch-like) callback for wildcard matching */
CINIT(FNMATCH_FUNCTION, FUNCTIONPOINT, 200),
/* Let the application define custom chunk data pointer */
CINIT(CHUNK_DATA, OBJECTPOINT, 201),
/* FNMATCH_FUNCTION user pointer */
CINIT(FNMATCH_DATA, OBJECTPOINT, 202),
/* send linked-list of name:port:address sets */
CINIT(RESOLVE, OBJECTPOINT, 203),
/* Set a username for authenticated TLS */
CINIT(TLSAUTH_USERNAME, OBJECTPOINT, 204),
/* Set a password for authenticated TLS */
CINIT(TLSAUTH_PASSWORD, OBJECTPOINT, 205),
/* Set authentication type for authenticated TLS */
CINIT(TLSAUTH_TYPE, OBJECTPOINT, 206),
/* Set to 1 to enable the "TE:" header in HTTP requests to ask for
compressed transfer-encoded responses. Set to 0 to disable the use of TE:
in outgoing requests. The current default is 0, but it might change in a
future libcurl release.
libcurl will ask for the compressed methods it knows of, and if that
isn't any, it will not ask for transfer-encoding at all even if this
option is set to 1.
*/
CINIT(TRANSFER_ENCODING, LONG, 207),
/* Callback function for closing socket (instead of close(2)). The callback
should have type curl_closesocket_callback */
CINIT(CLOSESOCKETFUNCTION, FUNCTIONPOINT, 208),
CINIT(CLOSESOCKETDATA, OBJECTPOINT, 209),
/* allow GSSAPI credential delegation */
CINIT(GSSAPI_DELEGATION, LONG, 210),
/* Set the name servers to use for DNS resolution */
CINIT(DNS_SERVERS, OBJECTPOINT, 211),
/* Time-out accept operations (currently for FTP only) after this amount
of miliseconds. */
CINIT(ACCEPTTIMEOUT_MS, LONG, 212),
/* Set TCP keepalive */
CINIT(TCP_KEEPALIVE, LONG, 213),
/* non-universal keepalive knobs (Linux, AIX, HP-UX, more) */
CINIT(TCP_KEEPIDLE, LONG, 214),
CINIT(TCP_KEEPINTVL, LONG, 215),
/* Enable/disable specific SSL features with a bitmask, see CURLSSLOPT_* */
CINIT(SSL_OPTIONS, LONG, 216),
/* set the SMTP auth originator */
CINIT(MAIL_AUTH, OBJECTPOINT, 217),
CURLOPT_LASTENTRY /* the last unused */
} CURLoption;
#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
the obsolete stuff removed! */
/* Backwards compatibility with older names */
/* These are scheduled to disappear by 2011 */
/* This was added in version 7.19.1 */
#define CURLOPT_POST301 CURLOPT_POSTREDIR
/* These are scheduled to disappear by 2009 */
/* The following were added in 7.17.0 */
#define CURLOPT_SSLKEYPASSWD CURLOPT_KEYPASSWD
#define CURLOPT_FTPAPPEND CURLOPT_APPEND
#define CURLOPT_FTPLISTONLY CURLOPT_DIRLISTONLY
#define CURLOPT_FTP_SSL CURLOPT_USE_SSL
/* The following were added earlier */
#define CURLOPT_SSLCERTPASSWD CURLOPT_KEYPASSWD
#define CURLOPT_KRB4LEVEL CURLOPT_KRBLEVEL
#else
/* This is set if CURL_NO_OLDIES is defined at compile-time */
#undef CURLOPT_DNS_USE_GLOBAL_CACHE /* soon obsolete */
#endif
/* Below here follows defines for the CURLOPT_IPRESOLVE option. If a host
name resolves addresses using more than one IP protocol version, this
option might be handy to force libcurl to use a specific IP version. */
#define CURL_IPRESOLVE_WHATEVER 0 /* default, resolves addresses to all IP
versions that your system allows */
#define CURL_IPRESOLVE_V4 1 /* resolve to ipv4 addresses */
#define CURL_IPRESOLVE_V6 2 /* resolve to ipv6 addresses */
/* three convenient "aliases" that follow the name scheme better */
#define CURLOPT_WRITEDATA CURLOPT_FILE
#define CURLOPT_READDATA CURLOPT_INFILE
#define CURLOPT_HEADERDATA CURLOPT_WRITEHEADER
#define CURLOPT_RTSPHEADER CURLOPT_HTTPHEADER
/* These enums are for use with the CURLOPT_HTTP_VERSION option. */
enum {
CURL_HTTP_VERSION_NONE, /* setting this means we don't care, and that we'd
like the library to choose the best possible
for us! */
CURL_HTTP_VERSION_1_0, /* please use HTTP 1.0 in the request */
CURL_HTTP_VERSION_1_1, /* please use HTTP 1.1 in the request */
CURL_HTTP_VERSION_LAST /* *ILLEGAL* http version */
};
/*
* Public API enums for RTSP requests
*/
enum {
CURL_RTSPREQ_NONE, /* first in list */
CURL_RTSPREQ_OPTIONS,
CURL_RTSPREQ_DESCRIBE,
CURL_RTSPREQ_ANNOUNCE,
CURL_RTSPREQ_SETUP,
CURL_RTSPREQ_PLAY,
CURL_RTSPREQ_PAUSE,
CURL_RTSPREQ_TEARDOWN,
CURL_RTSPREQ_GET_PARAMETER,
CURL_RTSPREQ_SET_PARAMETER,
CURL_RTSPREQ_RECORD,
CURL_RTSPREQ_RECEIVE,
CURL_RTSPREQ_LAST /* last in list */
};
/* These enums are for use with the CURLOPT_NETRC option. */
enum CURL_NETRC_OPTION {
CURL_NETRC_IGNORED, /* The .netrc will never be read.
* This is the default. */
CURL_NETRC_OPTIONAL, /* A user:password in the URL will be preferred
* to one in the .netrc. */
CURL_NETRC_REQUIRED, /* A user:password in the URL will be ignored.
* Unless one is set programmatically, the .netrc
* will be queried. */
CURL_NETRC_LAST
};
enum {
CURL_SSLVERSION_DEFAULT,
CURL_SSLVERSION_TLSv1,
CURL_SSLVERSION_SSLv2,
CURL_SSLVERSION_SSLv3,
CURL_SSLVERSION_LAST /* never use, keep last */
};
enum CURL_TLSAUTH {
CURL_TLSAUTH_NONE,
CURL_TLSAUTH_SRP,
CURL_TLSAUTH_LAST /* never use, keep last */
};
/* symbols to use with CURLOPT_POSTREDIR.
CURL_REDIR_POST_301, CURL_REDIR_POST_302 and CURL_REDIR_POST_303
can be bitwise ORed so that CURL_REDIR_POST_301 | CURL_REDIR_POST_302
| CURL_REDIR_POST_303 == CURL_REDIR_POST_ALL */
#define CURL_REDIR_GET_ALL 0
#define CURL_REDIR_POST_301 1
#define CURL_REDIR_POST_302 2
#define CURL_REDIR_POST_303 4
#define CURL_REDIR_POST_ALL \
(CURL_REDIR_POST_301|CURL_REDIR_POST_302|CURL_REDIR_POST_303)
typedef enum {
CURL_TIMECOND_NONE,
CURL_TIMECOND_IFMODSINCE,
CURL_TIMECOND_IFUNMODSINCE,
CURL_TIMECOND_LASTMOD,
CURL_TIMECOND_LAST
} curl_TimeCond;
/* curl_strequal() and curl_strnequal() are subject for removal in a future
libcurl, see lib/README.curlx for details */
CURL_EXTERN int (curl_strequal)(const char *s1, const char *s2);
CURL_EXTERN int (curl_strnequal)(const char *s1, const char *s2, size_t n);
/* name is uppercase CURLFORM_<name> */
#ifdef CFINIT
#undef CFINIT
#endif
#ifdef CURL_ISOCPP
#define CFINIT(name) CURLFORM_ ## name
#else
/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */
#define CFINIT(name) CURLFORM_/**/name
#endif
typedef enum {
CFINIT(NOTHING), /********* the first one is unused ************/
/* */
CFINIT(COPYNAME),
CFINIT(PTRNAME),
CFINIT(NAMELENGTH),
CFINIT(COPYCONTENTS),
CFINIT(PTRCONTENTS),
CFINIT(CONTENTSLENGTH),
CFINIT(FILECONTENT),
CFINIT(ARRAY),
CFINIT(OBSOLETE),
CFINIT(FILE),
CFINIT(BUFFER),
CFINIT(BUFFERPTR),
CFINIT(BUFFERLENGTH),
CFINIT(CONTENTTYPE),
CFINIT(CONTENTHEADER),
CFINIT(FILENAME),
CFINIT(END),
CFINIT(OBSOLETE2),
CFINIT(STREAM),
CURLFORM_LASTENTRY /* the last unused */
} CURLformoption;
#undef CFINIT /* done */
/* structure to be used as parameter for CURLFORM_ARRAY */
struct curl_forms {
CURLformoption option;
const char *value;
};
/* use this for multipart formpost building */
/* Returns code for curl_formadd()
*
* Returns:
* CURL_FORMADD_OK on success
* CURL_FORMADD_MEMORY if the FormInfo allocation fails
* CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form
* CURL_FORMADD_NULL if a null pointer was given for a char
* CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed
* CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used
* CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error)
* CURL_FORMADD_MEMORY if a curl_httppost struct cannot be allocated
* CURL_FORMADD_MEMORY if some allocation for string copying failed.
* CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array
*
***************************************************************************/
typedef enum {
CURL_FORMADD_OK, /* first, no error */
CURL_FORMADD_MEMORY,
CURL_FORMADD_OPTION_TWICE,
CURL_FORMADD_NULL,
CURL_FORMADD_UNKNOWN_OPTION,
CURL_FORMADD_INCOMPLETE,
CURL_FORMADD_ILLEGAL_ARRAY,
CURL_FORMADD_DISABLED, /* libcurl was built with this disabled */
CURL_FORMADD_LAST /* last */
} CURLFORMcode;
/*
* NAME curl_formadd()
*
* DESCRIPTION
*
* Pretty advanced function for building multi-part formposts. Each invoke
* adds one part that together construct a full post. Then use
* CURLOPT_HTTPPOST to send it off to libcurl.
*/
CURL_EXTERN CURLFORMcode curl_formadd(struct curl_httppost **httppost,
struct curl_httppost **last_post,
...);
/*
* callback function for curl_formget()
* The void *arg pointer will be the one passed as second argument to
* curl_formget().
* The character buffer passed to it must not be freed.
* Should return the buffer length passed to it as the argument "len" on
* success.
*/
typedef size_t (*curl_formget_callback)(void *arg, const char *buf,
size_t len);
/*
* NAME curl_formget()
*
* DESCRIPTION
*
* Serialize a curl_httppost struct built with curl_formadd().
* Accepts a void pointer as second argument which will be passed to
* the curl_formget_callback function.
* Returns 0 on success.
*/
CURL_EXTERN int curl_formget(struct curl_httppost *form, void *arg,
curl_formget_callback append);
/*
* NAME curl_formfree()
*
* DESCRIPTION
*
* Free a multipart formpost previously built with curl_formadd().
*/
CURL_EXTERN void curl_formfree(struct curl_httppost *form);
/*
* NAME curl_getenv()
*
* DESCRIPTION
*
* Returns a malloc()'ed string that MUST be curl_free()ed after usage is
* complete. DEPRECATED - see lib/README.curlx
*/
CURL_EXTERN char *curl_getenv(const char *variable);
/*
* NAME curl_version()
*
* DESCRIPTION
*
* Returns a static ascii string of the libcurl version.
*/
CURL_EXTERN char *curl_version(void);
/*
* NAME curl_easy_escape()
*
* DESCRIPTION
*
* Escapes URL strings (converts all letters consider illegal in URLs to their
* %XX versions). This function returns a new allocated string or NULL if an
* error occurred.
*/
CURL_EXTERN char *curl_easy_escape(CURL *handle,
const char *string,
int length);
/* the previous version: */
CURL_EXTERN char *curl_escape(const char *string,
int length);
/*
* NAME curl_easy_unescape()
*
* DESCRIPTION
*
* Unescapes URL encoding in strings (converts all %XX codes to their 8bit
* versions). This function returns a new allocated string or NULL if an error
* occurred.
* Conversion Note: On non-ASCII platforms the ASCII %XX codes are
* converted into the host encoding.
*/
CURL_EXTERN char *curl_easy_unescape(CURL *handle,
const char *string,
int length,
int *outlength);
/* the previous version */
CURL_EXTERN char *curl_unescape(const char *string,
int length);
/*
* NAME curl_free()
*
* DESCRIPTION
*
* Provided for de-allocation in the same translation unit that did the
* allocation. Added in libcurl 7.10
*/
CURL_EXTERN void curl_free(void *p);
/*
* NAME curl_global_init()
*
* DESCRIPTION
*
* curl_global_init() should be invoked exactly once for each application that
* uses libcurl and before any call of other libcurl functions.
*
* This function is not thread-safe!
*/
CURL_EXTERN CURLcode curl_global_init(long flags);
/*
* NAME curl_global_init_mem()
*
* DESCRIPTION
*
* curl_global_init() or curl_global_init_mem() should be invoked exactly once
* for each application that uses libcurl. This function can be used to
* initialize libcurl and set user defined memory management callback
* functions. Users can implement memory management routines to check for
* memory leaks, check for mis-use of the curl library etc. User registered
* callback routines with be invoked by this library instead of the system
* memory management routines like malloc, free etc.
*/
CURL_EXTERN CURLcode curl_global_init_mem(long flags,
curl_malloc_callback m,
curl_free_callback f,
curl_realloc_callback r,
curl_strdup_callback s,
curl_calloc_callback c);
/*
* NAME curl_global_cleanup()
*
* DESCRIPTION
*
* curl_global_cleanup() should be invoked exactly once for each application
* that uses libcurl
*/
CURL_EXTERN void curl_global_cleanup(void);
/* linked-list structure for the CURLOPT_QUOTE option (and other) */
struct curl_slist {
char *data;
struct curl_slist *next;
};
/*
* NAME curl_slist_append()
*
* DESCRIPTION
*
* Appends a string to a linked list. If no list exists, it will be created
* first. Returns the new list, after appending.
*/
CURL_EXTERN struct curl_slist *curl_slist_append(struct curl_slist *,
const char *);
/*
* NAME curl_slist_free_all()
*
* DESCRIPTION
*
* free a previously built curl_slist.
*/
CURL_EXTERN void curl_slist_free_all(struct curl_slist *);
/*
* NAME curl_getdate()
*
* DESCRIPTION
*
* Returns the time, in seconds since 1 Jan 1970 of the time string given in
* the first argument. The time argument in the second parameter is unused
* and should be set to NULL.
*/
CURL_EXTERN time_t curl_getdate(const char *p, const time_t *unused);
/* info about the certificate chain, only for OpenSSL builds. Asked
for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */
struct curl_certinfo {
int num_of_certs; /* number of certificates with information */
struct curl_slist **certinfo; /* for each index in this array, there's a
linked list with textual information in the
format "name: value" */
};
#define CURLINFO_STRING 0x100000
#define CURLINFO_LONG 0x200000
#define CURLINFO_DOUBLE 0x300000
#define CURLINFO_SLIST 0x400000
#define CURLINFO_MASK 0x0fffff
#define CURLINFO_TYPEMASK 0xf00000
typedef enum {
CURLINFO_NONE, /* first, never use this */
CURLINFO_EFFECTIVE_URL = CURLINFO_STRING + 1,
CURLINFO_RESPONSE_CODE = CURLINFO_LONG + 2,
CURLINFO_TOTAL_TIME = CURLINFO_DOUBLE + 3,
CURLINFO_NAMELOOKUP_TIME = CURLINFO_DOUBLE + 4,
CURLINFO_CONNECT_TIME = CURLINFO_DOUBLE + 5,
CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6,
CURLINFO_SIZE_UPLOAD = CURLINFO_DOUBLE + 7,
CURLINFO_SIZE_DOWNLOAD = CURLINFO_DOUBLE + 8,
CURLINFO_SPEED_DOWNLOAD = CURLINFO_DOUBLE + 9,
CURLINFO_SPEED_UPLOAD = CURLINFO_DOUBLE + 10,
CURLINFO_HEADER_SIZE = CURLINFO_LONG + 11,
CURLINFO_REQUEST_SIZE = CURLINFO_LONG + 12,
CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG + 13,
CURLINFO_FILETIME = CURLINFO_LONG + 14,
CURLINFO_CONTENT_LENGTH_DOWNLOAD = CURLINFO_DOUBLE + 15,
CURLINFO_CONTENT_LENGTH_UPLOAD = CURLINFO_DOUBLE + 16,
CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17,
CURLINFO_CONTENT_TYPE = CURLINFO_STRING + 18,
CURLINFO_REDIRECT_TIME = CURLINFO_DOUBLE + 19,
CURLINFO_REDIRECT_COUNT = CURLINFO_LONG + 20,
CURLINFO_PRIVATE = CURLINFO_STRING + 21,
CURLINFO_HTTP_CONNECTCODE = CURLINFO_LONG + 22,
CURLINFO_HTTPAUTH_AVAIL = CURLINFO_LONG + 23,
CURLINFO_PROXYAUTH_AVAIL = CURLINFO_LONG + 24,
CURLINFO_OS_ERRNO = CURLINFO_LONG + 25,
CURLINFO_NUM_CONNECTS = CURLINFO_LONG + 26,
CURLINFO_SSL_ENGINES = CURLINFO_SLIST + 27,
CURLINFO_COOKIELIST = CURLINFO_SLIST + 28,
CURLINFO_LASTSOCKET = CURLINFO_LONG + 29,
CURLINFO_FTP_ENTRY_PATH = CURLINFO_STRING + 30,
CURLINFO_REDIRECT_URL = CURLINFO_STRING + 31,
CURLINFO_PRIMARY_IP = CURLINFO_STRING + 32,
CURLINFO_APPCONNECT_TIME = CURLINFO_DOUBLE + 33,
CURLINFO_CERTINFO = CURLINFO_SLIST + 34,
CURLINFO_CONDITION_UNMET = CURLINFO_LONG + 35,
CURLINFO_RTSP_SESSION_ID = CURLINFO_STRING + 36,
CURLINFO_RTSP_CLIENT_CSEQ = CURLINFO_LONG + 37,
CURLINFO_RTSP_SERVER_CSEQ = CURLINFO_LONG + 38,
CURLINFO_RTSP_CSEQ_RECV = CURLINFO_LONG + 39,
CURLINFO_PRIMARY_PORT = CURLINFO_LONG + 40,
CURLINFO_LOCAL_IP = CURLINFO_STRING + 41,
CURLINFO_LOCAL_PORT = CURLINFO_LONG + 42,
/* Fill in new entries below here! */
CURLINFO_LASTONE = 42
} CURLINFO;
/* CURLINFO_RESPONSE_CODE is the new name for the option previously known as
CURLINFO_HTTP_CODE */
#define CURLINFO_HTTP_CODE CURLINFO_RESPONSE_CODE
typedef enum {
CURLCLOSEPOLICY_NONE, /* first, never use this */
CURLCLOSEPOLICY_OLDEST,
CURLCLOSEPOLICY_LEAST_RECENTLY_USED,
CURLCLOSEPOLICY_LEAST_TRAFFIC,
CURLCLOSEPOLICY_SLOWEST,
CURLCLOSEPOLICY_CALLBACK,
CURLCLOSEPOLICY_LAST /* last, never use this */
} curl_closepolicy;
#define CURL_GLOBAL_SSL (1<<0)
#define CURL_GLOBAL_WIN32 (1<<1)
#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32)
#define CURL_GLOBAL_NOTHING 0
#define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL
/*****************************************************************************
* Setup defines, protos etc for the sharing stuff.
*/
/* Different data locks for a single share */
typedef enum {
CURL_LOCK_DATA_NONE = 0,
/* CURL_LOCK_DATA_SHARE is used internally to say that
* the locking is just made to change the internal state of the share
* itself.
*/
CURL_LOCK_DATA_SHARE,
CURL_LOCK_DATA_COOKIE,
CURL_LOCK_DATA_DNS,
CURL_LOCK_DATA_SSL_SESSION,
CURL_LOCK_DATA_CONNECT,
CURL_LOCK_DATA_LAST
} curl_lock_data;
/* Different lock access types */
typedef enum {
CURL_LOCK_ACCESS_NONE = 0, /* unspecified action */
CURL_LOCK_ACCESS_SHARED = 1, /* for read perhaps */
CURL_LOCK_ACCESS_SINGLE = 2, /* for write perhaps */
CURL_LOCK_ACCESS_LAST /* never use */
} curl_lock_access;
typedef void (*curl_lock_function)(CURL *handle,
curl_lock_data data,
curl_lock_access locktype,
void *userptr);
typedef void (*curl_unlock_function)(CURL *handle,
curl_lock_data data,
void *userptr);
typedef void CURLSH;
typedef enum {
CURLSHE_OK, /* all is fine */
CURLSHE_BAD_OPTION, /* 1 */
CURLSHE_IN_USE, /* 2 */
CURLSHE_INVALID, /* 3 */
CURLSHE_NOMEM, /* 4 out of memory */
CURLSHE_NOT_BUILT_IN, /* 5 feature not present in lib */
CURLSHE_LAST /* never use */
} CURLSHcode;
typedef enum {
CURLSHOPT_NONE, /* don't use */
CURLSHOPT_SHARE, /* specify a data type to share */
CURLSHOPT_UNSHARE, /* specify which data type to stop sharing */
CURLSHOPT_LOCKFUNC, /* pass in a 'curl_lock_function' pointer */
CURLSHOPT_UNLOCKFUNC, /* pass in a 'curl_unlock_function' pointer */
CURLSHOPT_USERDATA, /* pass in a user data pointer used in the lock/unlock
callback functions */
CURLSHOPT_LAST /* never use */
} CURLSHoption;
CURL_EXTERN CURLSH *curl_share_init(void);
CURL_EXTERN CURLSHcode curl_share_setopt(CURLSH *, CURLSHoption option, ...);
CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *);
/****************************************************************************
* Structures for querying information about the curl library at runtime.
*/
typedef enum {
CURLVERSION_FIRST,
CURLVERSION_SECOND,
CURLVERSION_THIRD,
CURLVERSION_FOURTH,
CURLVERSION_LAST /* never actually use this */
} CURLversion;
/* The 'CURLVERSION_NOW' is the symbolic name meant to be used by
basically all programs ever that want to get version information. It is
meant to be a built-in version number for what kind of struct the caller
expects. If the struct ever changes, we redefine the NOW to another enum
from above. */
#define CURLVERSION_NOW CURLVERSION_FOURTH
typedef struct {
CURLversion age; /* age of the returned struct */
const char *version; /* LIBCURL_VERSION */
unsigned int version_num; /* LIBCURL_VERSION_NUM */
const char *host; /* OS/host/cpu/machine when configured */
int features; /* bitmask, see defines below */
const char *ssl_version; /* human readable string */
long ssl_version_num; /* not used anymore, always 0 */
const char *libz_version; /* human readable string */
/* protocols is terminated by an entry with a NULL protoname */
const char * const *protocols;
/* The fields below this were added in CURLVERSION_SECOND */
const char *ares;
int ares_num;
/* This field was added in CURLVERSION_THIRD */
const char *libidn;
/* These field were added in CURLVERSION_FOURTH */
/* Same as '_libiconv_version' if built with HAVE_ICONV */
int iconv_ver_num;
const char *libssh_version; /* human readable string */
} curl_version_info_data;
#define CURL_VERSION_IPV6 (1<<0) /* IPv6-enabled */
#define CURL_VERSION_KERBEROS4 (1<<1) /* kerberos auth is supported */
#define CURL_VERSION_SSL (1<<2) /* SSL options are present */
#define CURL_VERSION_LIBZ (1<<3) /* libz features are present */
#define CURL_VERSION_NTLM (1<<4) /* NTLM auth is supported */
#define CURL_VERSION_GSSNEGOTIATE (1<<5) /* Negotiate auth support */
#define CURL_VERSION_DEBUG (1<<6) /* built with debug capabilities */
#define CURL_VERSION_ASYNCHDNS (1<<7) /* asynchronous dns resolves */
#define CURL_VERSION_SPNEGO (1<<8) /* SPNEGO auth */
#define CURL_VERSION_LARGEFILE (1<<9) /* supports files bigger than 2GB */
#define CURL_VERSION_IDN (1<<10) /* International Domain Names support */
#define CURL_VERSION_SSPI (1<<11) /* SSPI is supported */
#define CURL_VERSION_CONV (1<<12) /* character conversions supported */
#define CURL_VERSION_CURLDEBUG (1<<13) /* debug memory tracking supported */
#define CURL_VERSION_TLSAUTH_SRP (1<<14) /* TLS-SRP auth is supported */
#define CURL_VERSION_NTLM_WB (1<<15) /* NTLM delegating to winbind helper */
/*
* NAME curl_version_info()
*
* DESCRIPTION
*
* This function returns a pointer to a static copy of the version info
* struct. See above.
*/
CURL_EXTERN curl_version_info_data *curl_version_info(CURLversion);
/*
* NAME curl_easy_strerror()
*
* DESCRIPTION
*
* The curl_easy_strerror function may be used to turn a CURLcode value
* into the equivalent human readable error string. This is useful
* for printing meaningful error messages.
*/
CURL_EXTERN const char *curl_easy_strerror(CURLcode);
/*
* NAME curl_share_strerror()
*
* DESCRIPTION
*
* The curl_share_strerror function may be used to turn a CURLSHcode value
* into the equivalent human readable error string. This is useful
* for printing meaningful error messages.
*/
CURL_EXTERN const char *curl_share_strerror(CURLSHcode);
/*
* NAME curl_easy_pause()
*
* DESCRIPTION
*
* The curl_easy_pause function pauses or unpauses transfers. Select the new
* state by setting the bitmask, use the convenience defines below.
*
*/
CURL_EXTERN CURLcode curl_easy_pause(CURL *handle, int bitmask);
#define CURLPAUSE_RECV (1<<0)
#define CURLPAUSE_RECV_CONT (0)
#define CURLPAUSE_SEND (1<<2)
#define CURLPAUSE_SEND_CONT (0)
#define CURLPAUSE_ALL (CURLPAUSE_RECV|CURLPAUSE_SEND)
#define CURLPAUSE_CONT (CURLPAUSE_RECV_CONT|CURLPAUSE_SEND_CONT)
#ifdef __cplusplus
}
#endif
/* unfortunately, the easy.h and multi.h include files need options and info
stuff before they can be included! */
#include "easy.h" /* nothing in curl is fun without the easy stuff */
#include "multi.h"
/* the typechecker doesn't work in C++ (yet) */
#if defined(__GNUC__) && defined(__GNUC_MINOR__) && \
((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && \
!defined(__cplusplus) && !defined(CURL_DISABLE_TYPECHECK)
#include "typecheck-gcc.h"
#else
#if defined(__STDC__) && (__STDC__ >= 1)
/* This preprocessor magic that replaces a call with the exact same call is
only done to make sure application authors pass exactly three arguments
to these functions. */
#define curl_easy_setopt(handle,opt,param) curl_easy_setopt(handle,opt,param)
#define curl_easy_getinfo(handle,info,arg) curl_easy_getinfo(handle,info,arg)
#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param)
#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param)
#endif /* __STDC__ >= 1 */
#endif /* gcc >= 4.3 && !__cplusplus */
#endif /* __CURL_CURL_H */
| 83,928 | 36.585759 | 79 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/libcurl/include/curl/curlrules.h
|
#ifndef __CURL_CURLRULES_H
#define __CURL_CURLRULES_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* ================================================================ */
/* COMPILE TIME SANITY CHECKS */
/* ================================================================ */
/*
* NOTE 1:
* -------
*
* All checks done in this file are intentionally placed in a public
* header file which is pulled by curl/curl.h when an application is
* being built using an already built libcurl library. Additionally
* this file is also included and used when building the library.
*
* If compilation fails on this file it is certainly sure that the
* problem is elsewhere. It could be a problem in the curlbuild.h
* header file, or simply that you are using different compilation
* settings than those used to build the library.
*
* Nothing in this file is intended to be modified or adjusted by the
* curl library user nor by the curl library builder.
*
* Do not deactivate any check, these are done to make sure that the
* library is properly built and used.
*
* You can find further help on the libcurl development mailing list:
* http://cool.haxx.se/mailman/listinfo/curl-library/
*
* NOTE 2
* ------
*
* Some of the following compile time checks are based on the fact
* that the dimension of a constant array can not be a negative one.
* In this way if the compile time verification fails, the compilation
* will fail issuing an error. The error description wording is compiler
* dependent but it will be quite similar to one of the following:
*
* "negative subscript or subscript is too large"
* "array must have at least one element"
* "-1 is an illegal array size"
* "size of array is negative"
*
* If you are building an application which tries to use an already
* built libcurl library and you are getting this kind of errors on
* this file, it is a clear indication that there is a mismatch between
* how the library was built and how you are trying to use it for your
* application. Your already compiled or binary library provider is the
* only one who can give you the details you need to properly use it.
*/
/*
* Verify that some macros are actually defined.
*/
#ifndef CURL_SIZEOF_LONG
# error "CURL_SIZEOF_LONG definition is missing!"
Error Compilation_aborted_CURL_SIZEOF_LONG_is_missing
#endif
#ifndef CURL_TYPEOF_CURL_SOCKLEN_T
# error "CURL_TYPEOF_CURL_SOCKLEN_T definition is missing!"
Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_is_missing
#endif
#ifndef CURL_SIZEOF_CURL_SOCKLEN_T
# error "CURL_SIZEOF_CURL_SOCKLEN_T definition is missing!"
Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_is_missing
#endif
#ifndef CURL_TYPEOF_CURL_OFF_T
# error "CURL_TYPEOF_CURL_OFF_T definition is missing!"
Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_is_missing
#endif
#ifndef CURL_FORMAT_CURL_OFF_T
# error "CURL_FORMAT_CURL_OFF_T definition is missing!"
Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_is_missing
#endif
#ifndef CURL_FORMAT_CURL_OFF_TU
# error "CURL_FORMAT_CURL_OFF_TU definition is missing!"
Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_is_missing
#endif
#ifndef CURL_FORMAT_OFF_T
# error "CURL_FORMAT_OFF_T definition is missing!"
Error Compilation_aborted_CURL_FORMAT_OFF_T_is_missing
#endif
#ifndef CURL_SIZEOF_CURL_OFF_T
# error "CURL_SIZEOF_CURL_OFF_T definition is missing!"
Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_is_missing
#endif
#ifndef CURL_SUFFIX_CURL_OFF_T
# error "CURL_SUFFIX_CURL_OFF_T definition is missing!"
Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_is_missing
#endif
#ifndef CURL_SUFFIX_CURL_OFF_TU
# error "CURL_SUFFIX_CURL_OFF_TU definition is missing!"
Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_is_missing
#endif
/*
* Macros private to this header file.
*/
#define CurlchkszEQ(t, s) sizeof(t) == s ? 1 : -1
#define CurlchkszGE(t1, t2) sizeof(t1) >= sizeof(t2) ? 1 : -1
/*
* Verify that the size previously defined and expected for long
* is the same as the one reported by sizeof() at compile time.
*/
typedef char
__curl_rule_01__
[CurlchkszEQ(long, CURL_SIZEOF_LONG)];
/*
* Verify that the size previously defined and expected for
* curl_off_t is actually the the same as the one reported
* by sizeof() at compile time.
*/
typedef char
__curl_rule_02__
[CurlchkszEQ(curl_off_t, CURL_SIZEOF_CURL_OFF_T)];
/*
* Verify at compile time that the size of curl_off_t as reported
* by sizeof() is greater or equal than the one reported for long
* for the current compilation.
*/
typedef char
__curl_rule_03__
[CurlchkszGE(curl_off_t, long)];
/*
* Verify that the size previously defined and expected for
* curl_socklen_t is actually the the same as the one reported
* by sizeof() at compile time.
*/
typedef char
__curl_rule_04__
[CurlchkszEQ(curl_socklen_t, CURL_SIZEOF_CURL_SOCKLEN_T)];
/*
* Verify at compile time that the size of curl_socklen_t as reported
* by sizeof() is greater or equal than the one reported for int for
* the current compilation.
*/
typedef char
__curl_rule_05__
[CurlchkszGE(curl_socklen_t, int)];
/* ================================================================ */
/* EXTERNALLY AND INTERNALLY VISIBLE DEFINITIONS */
/* ================================================================ */
/*
* CURL_ISOCPP and CURL_OFF_T_C definitions are done here in order to allow
* these to be visible and exported by the external libcurl interface API,
* while also making them visible to the library internals, simply including
* setup.h, without actually needing to include curl.h internally.
* If some day this section would grow big enough, all this should be moved
* to its own header file.
*/
/*
* Figure out if we can use the ## preprocessor operator, which is supported
* by ISO/ANSI C and C++. Some compilers support it without setting __STDC__
* or __cplusplus so we need to carefully check for them too.
*/
#if defined(__STDC__) || defined(_MSC_VER) || defined(__cplusplus) || \
defined(__HP_aCC) || defined(__BORLANDC__) || defined(__LCC__) || \
defined(__POCC__) || defined(__SALFORDC__) || defined(__HIGHC__) || \
defined(__ILEC400__)
/* This compiler is believed to have an ISO compatible preprocessor */
#define CURL_ISOCPP
#else
/* This compiler is believed NOT to have an ISO compatible preprocessor */
#undef CURL_ISOCPP
#endif
/*
* Macros for minimum-width signed and unsigned curl_off_t integer constants.
*/
#if defined(__BORLANDC__) && (__BORLANDC__ == 0x0551)
# define __CURL_OFF_T_C_HLPR2(x) x
# define __CURL_OFF_T_C_HLPR1(x) __CURL_OFF_T_C_HLPR2(x)
# define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HLPR1(Val) ## \
__CURL_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_T)
# define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HLPR1(Val) ## \
__CURL_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_TU)
#else
# ifdef CURL_ISOCPP
# define __CURL_OFF_T_C_HLPR2(Val,Suffix) Val ## Suffix
# else
# define __CURL_OFF_T_C_HLPR2(Val,Suffix) Val/**/Suffix
# endif
# define __CURL_OFF_T_C_HLPR1(Val,Suffix) __CURL_OFF_T_C_HLPR2(Val,Suffix)
# define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_T)
# define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_TU)
#endif
/*
* Get rid of macros private to this header file.
*/
#undef CurlchkszEQ
#undef CurlchkszGE
/*
* Get rid of macros not intended to exist beyond this point.
*/
#undef CURL_PULL_WS2TCPIP_H
#undef CURL_PULL_SYS_TYPES_H
#undef CURL_PULL_SYS_SOCKET_H
#undef CURL_PULL_STDINT_H
#undef CURL_PULL_INTTYPES_H
#undef CURL_TYPEOF_CURL_SOCKLEN_T
#undef CURL_TYPEOF_CURL_OFF_T
#ifdef CURL_NO_OLDIES
#undef CURL_FORMAT_OFF_T /* not required since 7.19.0 - obsoleted in 7.20.0 */
#endif
#endif /* __CURL_CURLRULES_H */
| 8,901 | 32.977099 | 78 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/libcurl/include/curl/typecheck-gcc.h
|
#ifndef __CURL_TYPECHECK_GCC_H
#define __CURL_TYPECHECK_GCC_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2012, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* wraps curl_easy_setopt() with typechecking */
/* To add a new kind of warning, add an
* if(_curl_is_sometype_option(_curl_opt))
* if(!_curl_is_sometype(value))
* _curl_easy_setopt_err_sometype();
* block and define _curl_is_sometype_option, _curl_is_sometype and
* _curl_easy_setopt_err_sometype below
*
* NOTE: We use two nested 'if' statements here instead of the && operator, in
* order to work around gcc bug #32061. It affects only gcc 4.3.x/4.4.x
* when compiling with -Wlogical-op.
*
* To add an option that uses the same type as an existing option, you'll just
* need to extend the appropriate _curl_*_option macro
*/
#define curl_easy_setopt(handle, option, value) \
__extension__ ({ \
__typeof__ (option) _curl_opt = option; \
if(__builtin_constant_p(_curl_opt)) { \
if(_curl_is_long_option(_curl_opt)) \
if(!_curl_is_long(value)) \
_curl_easy_setopt_err_long(); \
if(_curl_is_off_t_option(_curl_opt)) \
if(!_curl_is_off_t(value)) \
_curl_easy_setopt_err_curl_off_t(); \
if(_curl_is_string_option(_curl_opt)) \
if(!_curl_is_string(value)) \
_curl_easy_setopt_err_string(); \
if(_curl_is_write_cb_option(_curl_opt)) \
if(!_curl_is_write_cb(value)) \
_curl_easy_setopt_err_write_callback(); \
if((_curl_opt) == CURLOPT_READFUNCTION) \
if(!_curl_is_read_cb(value)) \
_curl_easy_setopt_err_read_cb(); \
if((_curl_opt) == CURLOPT_IOCTLFUNCTION) \
if(!_curl_is_ioctl_cb(value)) \
_curl_easy_setopt_err_ioctl_cb(); \
if((_curl_opt) == CURLOPT_SOCKOPTFUNCTION) \
if(!_curl_is_sockopt_cb(value)) \
_curl_easy_setopt_err_sockopt_cb(); \
if((_curl_opt) == CURLOPT_OPENSOCKETFUNCTION) \
if(!_curl_is_opensocket_cb(value)) \
_curl_easy_setopt_err_opensocket_cb(); \
if((_curl_opt) == CURLOPT_PROGRESSFUNCTION) \
if(!_curl_is_progress_cb(value)) \
_curl_easy_setopt_err_progress_cb(); \
if((_curl_opt) == CURLOPT_DEBUGFUNCTION) \
if(!_curl_is_debug_cb(value)) \
_curl_easy_setopt_err_debug_cb(); \
if((_curl_opt) == CURLOPT_SSL_CTX_FUNCTION) \
if(!_curl_is_ssl_ctx_cb(value)) \
_curl_easy_setopt_err_ssl_ctx_cb(); \
if(_curl_is_conv_cb_option(_curl_opt)) \
if(!_curl_is_conv_cb(value)) \
_curl_easy_setopt_err_conv_cb(); \
if((_curl_opt) == CURLOPT_SEEKFUNCTION) \
if(!_curl_is_seek_cb(value)) \
_curl_easy_setopt_err_seek_cb(); \
if(_curl_is_cb_data_option(_curl_opt)) \
if(!_curl_is_cb_data(value)) \
_curl_easy_setopt_err_cb_data(); \
if((_curl_opt) == CURLOPT_ERRORBUFFER) \
if(!_curl_is_error_buffer(value)) \
_curl_easy_setopt_err_error_buffer(); \
if((_curl_opt) == CURLOPT_STDERR) \
if(!_curl_is_FILE(value)) \
_curl_easy_setopt_err_FILE(); \
if(_curl_is_postfields_option(_curl_opt)) \
if(!_curl_is_postfields(value)) \
_curl_easy_setopt_err_postfields(); \
if((_curl_opt) == CURLOPT_HTTPPOST) \
if(!_curl_is_arr((value), struct curl_httppost)) \
_curl_easy_setopt_err_curl_httpost(); \
if(_curl_is_slist_option(_curl_opt)) \
if(!_curl_is_arr((value), struct curl_slist)) \
_curl_easy_setopt_err_curl_slist(); \
if((_curl_opt) == CURLOPT_SHARE) \
if(!_curl_is_ptr((value), CURLSH)) \
_curl_easy_setopt_err_CURLSH(); \
} \
curl_easy_setopt(handle, _curl_opt, value); \
})
/* wraps curl_easy_getinfo() with typechecking */
/* FIXME: don't allow const pointers */
#define curl_easy_getinfo(handle, info, arg) \
__extension__ ({ \
__typeof__ (info) _curl_info = info; \
if(__builtin_constant_p(_curl_info)) { \
if(_curl_is_string_info(_curl_info)) \
if(!_curl_is_arr((arg), char *)) \
_curl_easy_getinfo_err_string(); \
if(_curl_is_long_info(_curl_info)) \
if(!_curl_is_arr((arg), long)) \
_curl_easy_getinfo_err_long(); \
if(_curl_is_double_info(_curl_info)) \
if(!_curl_is_arr((arg), double)) \
_curl_easy_getinfo_err_double(); \
if(_curl_is_slist_info(_curl_info)) \
if(!_curl_is_arr((arg), struct curl_slist *)) \
_curl_easy_getinfo_err_curl_slist(); \
} \
curl_easy_getinfo(handle, _curl_info, arg); \
})
/* TODO: typechecking for curl_share_setopt() and curl_multi_setopt(),
* for now just make sure that the functions are called with three
* arguments
*/
#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param)
#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param)
/* the actual warnings, triggered by calling the _curl_easy_setopt_err*
* functions */
/* To define a new warning, use _CURL_WARNING(identifier, "message") */
#define _CURL_WARNING(id, message) \
static void __attribute__((__warning__(message))) \
__attribute__((__unused__)) __attribute__((__noinline__)) \
id(void) { __asm__(""); }
_CURL_WARNING(_curl_easy_setopt_err_long,
"curl_easy_setopt expects a long argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_curl_off_t,
"curl_easy_setopt expects a curl_off_t argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_string,
"curl_easy_setopt expects a "
"string (char* or char[]) argument for this option"
)
_CURL_WARNING(_curl_easy_setopt_err_write_callback,
"curl_easy_setopt expects a curl_write_callback argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_read_cb,
"curl_easy_setopt expects a curl_read_callback argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_ioctl_cb,
"curl_easy_setopt expects a curl_ioctl_callback argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_sockopt_cb,
"curl_easy_setopt expects a curl_sockopt_callback argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_opensocket_cb,
"curl_easy_setopt expects a "
"curl_opensocket_callback argument for this option"
)
_CURL_WARNING(_curl_easy_setopt_err_progress_cb,
"curl_easy_setopt expects a curl_progress_callback argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_debug_cb,
"curl_easy_setopt expects a curl_debug_callback argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_ssl_ctx_cb,
"curl_easy_setopt expects a curl_ssl_ctx_callback argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_conv_cb,
"curl_easy_setopt expects a curl_conv_callback argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_seek_cb,
"curl_easy_setopt expects a curl_seek_callback argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_cb_data,
"curl_easy_setopt expects a "
"private data pointer as argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_error_buffer,
"curl_easy_setopt expects a "
"char buffer of CURL_ERROR_SIZE as argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_FILE,
"curl_easy_setopt expects a FILE* argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_postfields,
"curl_easy_setopt expects a void* or char* argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_curl_httpost,
"curl_easy_setopt expects a struct curl_httppost* argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_curl_slist,
"curl_easy_setopt expects a struct curl_slist* argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_CURLSH,
"curl_easy_setopt expects a CURLSH* argument for this option")
_CURL_WARNING(_curl_easy_getinfo_err_string,
"curl_easy_getinfo expects a pointer to char * for this info")
_CURL_WARNING(_curl_easy_getinfo_err_long,
"curl_easy_getinfo expects a pointer to long for this info")
_CURL_WARNING(_curl_easy_getinfo_err_double,
"curl_easy_getinfo expects a pointer to double for this info")
_CURL_WARNING(_curl_easy_getinfo_err_curl_slist,
"curl_easy_getinfo expects a pointer to struct curl_slist * for this info")
/* groups of curl_easy_setops options that take the same type of argument */
/* To add a new option to one of the groups, just add
* (option) == CURLOPT_SOMETHING
* to the or-expression. If the option takes a long or curl_off_t, you don't
* have to do anything
*/
/* evaluates to true if option takes a long argument */
#define _curl_is_long_option(option) \
(0 < (option) && (option) < CURLOPTTYPE_OBJECTPOINT)
#define _curl_is_off_t_option(option) \
((option) > CURLOPTTYPE_OFF_T)
/* evaluates to true if option takes a char* argument */
#define _curl_is_string_option(option) \
((option) == CURLOPT_URL || \
(option) == CURLOPT_PROXY || \
(option) == CURLOPT_INTERFACE || \
(option) == CURLOPT_NETRC_FILE || \
(option) == CURLOPT_USERPWD || \
(option) == CURLOPT_USERNAME || \
(option) == CURLOPT_PASSWORD || \
(option) == CURLOPT_PROXYUSERPWD || \
(option) == CURLOPT_PROXYUSERNAME || \
(option) == CURLOPT_PROXYPASSWORD || \
(option) == CURLOPT_NOPROXY || \
(option) == CURLOPT_ACCEPT_ENCODING || \
(option) == CURLOPT_REFERER || \
(option) == CURLOPT_USERAGENT || \
(option) == CURLOPT_COOKIE || \
(option) == CURLOPT_COOKIEFILE || \
(option) == CURLOPT_COOKIEJAR || \
(option) == CURLOPT_COOKIELIST || \
(option) == CURLOPT_FTPPORT || \
(option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \
(option) == CURLOPT_FTP_ACCOUNT || \
(option) == CURLOPT_RANGE || \
(option) == CURLOPT_CUSTOMREQUEST || \
(option) == CURLOPT_SSLCERT || \
(option) == CURLOPT_SSLCERTTYPE || \
(option) == CURLOPT_SSLKEY || \
(option) == CURLOPT_SSLKEYTYPE || \
(option) == CURLOPT_KEYPASSWD || \
(option) == CURLOPT_SSLENGINE || \
(option) == CURLOPT_CAINFO || \
(option) == CURLOPT_CAPATH || \
(option) == CURLOPT_RANDOM_FILE || \
(option) == CURLOPT_EGDSOCKET || \
(option) == CURLOPT_SSL_CIPHER_LIST || \
(option) == CURLOPT_KRBLEVEL || \
(option) == CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 || \
(option) == CURLOPT_SSH_PUBLIC_KEYFILE || \
(option) == CURLOPT_SSH_PRIVATE_KEYFILE || \
(option) == CURLOPT_CRLFILE || \
(option) == CURLOPT_ISSUERCERT || \
(option) == CURLOPT_SOCKS5_GSSAPI_SERVICE || \
(option) == CURLOPT_SSH_KNOWNHOSTS || \
(option) == CURLOPT_MAIL_FROM || \
(option) == CURLOPT_RTSP_SESSION_ID || \
(option) == CURLOPT_RTSP_STREAM_URI || \
(option) == CURLOPT_RTSP_TRANSPORT || \
0)
/* evaluates to true if option takes a curl_write_callback argument */
#define _curl_is_write_cb_option(option) \
((option) == CURLOPT_HEADERFUNCTION || \
(option) == CURLOPT_WRITEFUNCTION)
/* evaluates to true if option takes a curl_conv_callback argument */
#define _curl_is_conv_cb_option(option) \
((option) == CURLOPT_CONV_TO_NETWORK_FUNCTION || \
(option) == CURLOPT_CONV_FROM_NETWORK_FUNCTION || \
(option) == CURLOPT_CONV_FROM_UTF8_FUNCTION)
/* evaluates to true if option takes a data argument to pass to a callback */
#define _curl_is_cb_data_option(option) \
((option) == CURLOPT_WRITEDATA || \
(option) == CURLOPT_READDATA || \
(option) == CURLOPT_IOCTLDATA || \
(option) == CURLOPT_SOCKOPTDATA || \
(option) == CURLOPT_OPENSOCKETDATA || \
(option) == CURLOPT_PROGRESSDATA || \
(option) == CURLOPT_WRITEHEADER || \
(option) == CURLOPT_DEBUGDATA || \
(option) == CURLOPT_SSL_CTX_DATA || \
(option) == CURLOPT_SEEKDATA || \
(option) == CURLOPT_PRIVATE || \
(option) == CURLOPT_SSH_KEYDATA || \
(option) == CURLOPT_INTERLEAVEDATA || \
(option) == CURLOPT_CHUNK_DATA || \
(option) == CURLOPT_FNMATCH_DATA || \
0)
/* evaluates to true if option takes a POST data argument (void* or char*) */
#define _curl_is_postfields_option(option) \
((option) == CURLOPT_POSTFIELDS || \
(option) == CURLOPT_COPYPOSTFIELDS || \
0)
/* evaluates to true if option takes a struct curl_slist * argument */
#define _curl_is_slist_option(option) \
((option) == CURLOPT_HTTPHEADER || \
(option) == CURLOPT_HTTP200ALIASES || \
(option) == CURLOPT_QUOTE || \
(option) == CURLOPT_POSTQUOTE || \
(option) == CURLOPT_PREQUOTE || \
(option) == CURLOPT_TELNETOPTIONS || \
(option) == CURLOPT_MAIL_RCPT || \
0)
/* groups of curl_easy_getinfo infos that take the same type of argument */
/* evaluates to true if info expects a pointer to char * argument */
#define _curl_is_string_info(info) \
(CURLINFO_STRING < (info) && (info) < CURLINFO_LONG)
/* evaluates to true if info expects a pointer to long argument */
#define _curl_is_long_info(info) \
(CURLINFO_LONG < (info) && (info) < CURLINFO_DOUBLE)
/* evaluates to true if info expects a pointer to double argument */
#define _curl_is_double_info(info) \
(CURLINFO_DOUBLE < (info) && (info) < CURLINFO_SLIST)
/* true if info expects a pointer to struct curl_slist * argument */
#define _curl_is_slist_info(info) \
(CURLINFO_SLIST < (info))
/* typecheck helpers -- check whether given expression has requested type*/
/* For pointers, you can use the _curl_is_ptr/_curl_is_arr macros,
* otherwise define a new macro. Search for __builtin_types_compatible_p
* in the GCC manual.
* NOTE: these macros MUST NOT EVALUATE their arguments! The argument is
* the actual expression passed to the curl_easy_setopt macro. This
* means that you can only apply the sizeof and __typeof__ operators, no
* == or whatsoever.
*/
/* XXX: should evaluate to true iff expr is a pointer */
#define _curl_is_any_ptr(expr) \
(sizeof(expr) == sizeof(void*))
/* evaluates to true if expr is NULL */
/* XXX: must not evaluate expr, so this check is not accurate */
#define _curl_is_NULL(expr) \
(__builtin_types_compatible_p(__typeof__(expr), __typeof__(NULL)))
/* evaluates to true if expr is type*, const type* or NULL */
#define _curl_is_ptr(expr, type) \
(_curl_is_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), type *) || \
__builtin_types_compatible_p(__typeof__(expr), const type *))
/* evaluates to true if expr is one of type[], type*, NULL or const type* */
#define _curl_is_arr(expr, type) \
(_curl_is_ptr((expr), type) || \
__builtin_types_compatible_p(__typeof__(expr), type []))
/* evaluates to true if expr is a string */
#define _curl_is_string(expr) \
(_curl_is_arr((expr), char) || \
_curl_is_arr((expr), signed char) || \
_curl_is_arr((expr), unsigned char))
/* evaluates to true if expr is a long (no matter the signedness)
* XXX: for now, int is also accepted (and therefore short and char, which
* are promoted to int when passed to a variadic function) */
#define _curl_is_long(expr) \
(__builtin_types_compatible_p(__typeof__(expr), long) || \
__builtin_types_compatible_p(__typeof__(expr), signed long) || \
__builtin_types_compatible_p(__typeof__(expr), unsigned long) || \
__builtin_types_compatible_p(__typeof__(expr), int) || \
__builtin_types_compatible_p(__typeof__(expr), signed int) || \
__builtin_types_compatible_p(__typeof__(expr), unsigned int) || \
__builtin_types_compatible_p(__typeof__(expr), short) || \
__builtin_types_compatible_p(__typeof__(expr), signed short) || \
__builtin_types_compatible_p(__typeof__(expr), unsigned short) || \
__builtin_types_compatible_p(__typeof__(expr), char) || \
__builtin_types_compatible_p(__typeof__(expr), signed char) || \
__builtin_types_compatible_p(__typeof__(expr), unsigned char))
/* evaluates to true if expr is of type curl_off_t */
#define _curl_is_off_t(expr) \
(__builtin_types_compatible_p(__typeof__(expr), curl_off_t))
/* evaluates to true if expr is abuffer suitable for CURLOPT_ERRORBUFFER */
/* XXX: also check size of an char[] array? */
#define _curl_is_error_buffer(expr) \
(_curl_is_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), char *) || \
__builtin_types_compatible_p(__typeof__(expr), char[]))
/* evaluates to true if expr is of type (const) void* or (const) FILE* */
#if 0
#define _curl_is_cb_data(expr) \
(_curl_is_ptr((expr), void) || \
_curl_is_ptr((expr), FILE))
#else /* be less strict */
#define _curl_is_cb_data(expr) \
_curl_is_any_ptr(expr)
#endif
/* evaluates to true if expr is of type FILE* */
#define _curl_is_FILE(expr) \
(__builtin_types_compatible_p(__typeof__(expr), FILE *))
/* evaluates to true if expr can be passed as POST data (void* or char*) */
#define _curl_is_postfields(expr) \
(_curl_is_ptr((expr), void) || \
_curl_is_arr((expr), char))
/* FIXME: the whole callback checking is messy...
* The idea is to tolerate char vs. void and const vs. not const
* pointers in arguments at least
*/
/* helper: __builtin_types_compatible_p distinguishes between functions and
* function pointers, hide it */
#define _curl_callback_compatible(func, type) \
(__builtin_types_compatible_p(__typeof__(func), type) || \
__builtin_types_compatible_p(__typeof__(func), type*))
/* evaluates to true if expr is of type curl_read_callback or "similar" */
#define _curl_is_read_cb(expr) \
(_curl_is_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), __typeof__(fread)) || \
__builtin_types_compatible_p(__typeof__(expr), curl_read_callback) || \
_curl_callback_compatible((expr), _curl_read_callback1) || \
_curl_callback_compatible((expr), _curl_read_callback2) || \
_curl_callback_compatible((expr), _curl_read_callback3) || \
_curl_callback_compatible((expr), _curl_read_callback4) || \
_curl_callback_compatible((expr), _curl_read_callback5) || \
_curl_callback_compatible((expr), _curl_read_callback6))
typedef size_t (_curl_read_callback1)(char *, size_t, size_t, void*);
typedef size_t (_curl_read_callback2)(char *, size_t, size_t, const void*);
typedef size_t (_curl_read_callback3)(char *, size_t, size_t, FILE*);
typedef size_t (_curl_read_callback4)(void *, size_t, size_t, void*);
typedef size_t (_curl_read_callback5)(void *, size_t, size_t, const void*);
typedef size_t (_curl_read_callback6)(void *, size_t, size_t, FILE*);
/* evaluates to true if expr is of type curl_write_callback or "similar" */
#define _curl_is_write_cb(expr) \
(_curl_is_read_cb(expr) || \
__builtin_types_compatible_p(__typeof__(expr), __typeof__(fwrite)) || \
__builtin_types_compatible_p(__typeof__(expr), curl_write_callback) || \
_curl_callback_compatible((expr), _curl_write_callback1) || \
_curl_callback_compatible((expr), _curl_write_callback2) || \
_curl_callback_compatible((expr), _curl_write_callback3) || \
_curl_callback_compatible((expr), _curl_write_callback4) || \
_curl_callback_compatible((expr), _curl_write_callback5) || \
_curl_callback_compatible((expr), _curl_write_callback6))
typedef size_t (_curl_write_callback1)(const char *, size_t, size_t, void*);
typedef size_t (_curl_write_callback2)(const char *, size_t, size_t,
const void*);
typedef size_t (_curl_write_callback3)(const char *, size_t, size_t, FILE*);
typedef size_t (_curl_write_callback4)(const void *, size_t, size_t, void*);
typedef size_t (_curl_write_callback5)(const void *, size_t, size_t,
const void*);
typedef size_t (_curl_write_callback6)(const void *, size_t, size_t, FILE*);
/* evaluates to true if expr is of type curl_ioctl_callback or "similar" */
#define _curl_is_ioctl_cb(expr) \
(_curl_is_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), curl_ioctl_callback) || \
_curl_callback_compatible((expr), _curl_ioctl_callback1) || \
_curl_callback_compatible((expr), _curl_ioctl_callback2) || \
_curl_callback_compatible((expr), _curl_ioctl_callback3) || \
_curl_callback_compatible((expr), _curl_ioctl_callback4))
typedef curlioerr (_curl_ioctl_callback1)(CURL *, int, void*);
typedef curlioerr (_curl_ioctl_callback2)(CURL *, int, const void*);
typedef curlioerr (_curl_ioctl_callback3)(CURL *, curliocmd, void*);
typedef curlioerr (_curl_ioctl_callback4)(CURL *, curliocmd, const void*);
/* evaluates to true if expr is of type curl_sockopt_callback or "similar" */
#define _curl_is_sockopt_cb(expr) \
(_curl_is_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), curl_sockopt_callback) || \
_curl_callback_compatible((expr), _curl_sockopt_callback1) || \
_curl_callback_compatible((expr), _curl_sockopt_callback2))
typedef int (_curl_sockopt_callback1)(void *, curl_socket_t, curlsocktype);
typedef int (_curl_sockopt_callback2)(const void *, curl_socket_t,
curlsocktype);
/* evaluates to true if expr is of type curl_opensocket_callback or
"similar" */
#define _curl_is_opensocket_cb(expr) \
(_curl_is_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), curl_opensocket_callback) ||\
_curl_callback_compatible((expr), _curl_opensocket_callback1) || \
_curl_callback_compatible((expr), _curl_opensocket_callback2) || \
_curl_callback_compatible((expr), _curl_opensocket_callback3) || \
_curl_callback_compatible((expr), _curl_opensocket_callback4))
typedef curl_socket_t (_curl_opensocket_callback1)
(void *, curlsocktype, struct curl_sockaddr *);
typedef curl_socket_t (_curl_opensocket_callback2)
(void *, curlsocktype, const struct curl_sockaddr *);
typedef curl_socket_t (_curl_opensocket_callback3)
(const void *, curlsocktype, struct curl_sockaddr *);
typedef curl_socket_t (_curl_opensocket_callback4)
(const void *, curlsocktype, const struct curl_sockaddr *);
/* evaluates to true if expr is of type curl_progress_callback or "similar" */
#define _curl_is_progress_cb(expr) \
(_curl_is_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), curl_progress_callback) || \
_curl_callback_compatible((expr), _curl_progress_callback1) || \
_curl_callback_compatible((expr), _curl_progress_callback2))
typedef int (_curl_progress_callback1)(void *,
double, double, double, double);
typedef int (_curl_progress_callback2)(const void *,
double, double, double, double);
/* evaluates to true if expr is of type curl_debug_callback or "similar" */
#define _curl_is_debug_cb(expr) \
(_curl_is_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), curl_debug_callback) || \
_curl_callback_compatible((expr), _curl_debug_callback1) || \
_curl_callback_compatible((expr), _curl_debug_callback2) || \
_curl_callback_compatible((expr), _curl_debug_callback3) || \
_curl_callback_compatible((expr), _curl_debug_callback4) || \
_curl_callback_compatible((expr), _curl_debug_callback5) || \
_curl_callback_compatible((expr), _curl_debug_callback6) || \
_curl_callback_compatible((expr), _curl_debug_callback7) || \
_curl_callback_compatible((expr), _curl_debug_callback8))
typedef int (_curl_debug_callback1) (CURL *,
curl_infotype, char *, size_t, void *);
typedef int (_curl_debug_callback2) (CURL *,
curl_infotype, char *, size_t, const void *);
typedef int (_curl_debug_callback3) (CURL *,
curl_infotype, const char *, size_t, void *);
typedef int (_curl_debug_callback4) (CURL *,
curl_infotype, const char *, size_t, const void *);
typedef int (_curl_debug_callback5) (CURL *,
curl_infotype, unsigned char *, size_t, void *);
typedef int (_curl_debug_callback6) (CURL *,
curl_infotype, unsigned char *, size_t, const void *);
typedef int (_curl_debug_callback7) (CURL *,
curl_infotype, const unsigned char *, size_t, void *);
typedef int (_curl_debug_callback8) (CURL *,
curl_infotype, const unsigned char *, size_t, const void *);
/* evaluates to true if expr is of type curl_ssl_ctx_callback or "similar" */
/* this is getting even messier... */
#define _curl_is_ssl_ctx_cb(expr) \
(_curl_is_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), curl_ssl_ctx_callback) || \
_curl_callback_compatible((expr), _curl_ssl_ctx_callback1) || \
_curl_callback_compatible((expr), _curl_ssl_ctx_callback2) || \
_curl_callback_compatible((expr), _curl_ssl_ctx_callback3) || \
_curl_callback_compatible((expr), _curl_ssl_ctx_callback4) || \
_curl_callback_compatible((expr), _curl_ssl_ctx_callback5) || \
_curl_callback_compatible((expr), _curl_ssl_ctx_callback6) || \
_curl_callback_compatible((expr), _curl_ssl_ctx_callback7) || \
_curl_callback_compatible((expr), _curl_ssl_ctx_callback8))
typedef CURLcode (_curl_ssl_ctx_callback1)(CURL *, void *, void *);
typedef CURLcode (_curl_ssl_ctx_callback2)(CURL *, void *, const void *);
typedef CURLcode (_curl_ssl_ctx_callback3)(CURL *, const void *, void *);
typedef CURLcode (_curl_ssl_ctx_callback4)(CURL *, const void *, const void *);
#ifdef HEADER_SSL_H
/* hack: if we included OpenSSL's ssl.h, we know about SSL_CTX
* this will of course break if we're included before OpenSSL headers...
*/
typedef CURLcode (_curl_ssl_ctx_callback5)(CURL *, SSL_CTX, void *);
typedef CURLcode (_curl_ssl_ctx_callback6)(CURL *, SSL_CTX, const void *);
typedef CURLcode (_curl_ssl_ctx_callback7)(CURL *, const SSL_CTX, void *);
typedef CURLcode (_curl_ssl_ctx_callback8)(CURL *, const SSL_CTX,
const void *);
#else
typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback5;
typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback6;
typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback7;
typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback8;
#endif
/* evaluates to true if expr is of type curl_conv_callback or "similar" */
#define _curl_is_conv_cb(expr) \
(_curl_is_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), curl_conv_callback) || \
_curl_callback_compatible((expr), _curl_conv_callback1) || \
_curl_callback_compatible((expr), _curl_conv_callback2) || \
_curl_callback_compatible((expr), _curl_conv_callback3) || \
_curl_callback_compatible((expr), _curl_conv_callback4))
typedef CURLcode (*_curl_conv_callback1)(char *, size_t length);
typedef CURLcode (*_curl_conv_callback2)(const char *, size_t length);
typedef CURLcode (*_curl_conv_callback3)(void *, size_t length);
typedef CURLcode (*_curl_conv_callback4)(const void *, size_t length);
/* evaluates to true if expr is of type curl_seek_callback or "similar" */
#define _curl_is_seek_cb(expr) \
(_curl_is_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), curl_seek_callback) || \
_curl_callback_compatible((expr), _curl_seek_callback1) || \
_curl_callback_compatible((expr), _curl_seek_callback2))
typedef CURLcode (*_curl_seek_callback1)(void *, curl_off_t, int);
typedef CURLcode (*_curl_seek_callback2)(const void *, curl_off_t, int);
#endif /* __CURL_TYPECHECK_GCC_H */
| 36,918 | 60.02314 | 79 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/libcurl/include/curl/easy.h
|
#ifndef __CURL_EASY_H
#define __CURL_EASY_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2008, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#ifdef __cplusplus
extern "C" {
#endif
CURL_EXTERN CURL *curl_easy_init(void);
CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...);
CURL_EXTERN CURLcode curl_easy_perform(CURL *curl);
CURL_EXTERN void curl_easy_cleanup(CURL *curl);
/*
* NAME curl_easy_getinfo()
*
* DESCRIPTION
*
* Request internal information from the curl session with this function. The
* third argument MUST be a pointer to a long, a pointer to a char * or a
* pointer to a double (as the documentation describes elsewhere). The data
* pointed to will be filled in accordingly and can be relied upon only if the
* function returns CURLE_OK. This function is intended to get used *AFTER* a
* performed transfer, all results from this function are undefined until the
* transfer is completed.
*/
CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...);
/*
* NAME curl_easy_duphandle()
*
* DESCRIPTION
*
* Creates a new curl session handle with the same options set for the handle
* passed in. Duplicating a handle could only be a matter of cloning data and
* options, internal state info and things like persistent connections cannot
* be transferred. It is useful in multithreaded applications when you can run
* curl_easy_duphandle() for each new thread to avoid a series of identical
* curl_easy_setopt() invokes in every thread.
*/
CURL_EXTERN CURL* curl_easy_duphandle(CURL *curl);
/*
* NAME curl_easy_reset()
*
* DESCRIPTION
*
* Re-initializes a CURL handle to the default values. This puts back the
* handle to the same state as it was in when it was just created.
*
* It does keep: live connections, the Session ID cache, the DNS cache and the
* cookies.
*/
CURL_EXTERN void curl_easy_reset(CURL *curl);
/*
* NAME curl_easy_recv()
*
* DESCRIPTION
*
* Receives data from the connected socket. Use after successful
* curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
*/
CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen,
size_t *n);
/*
* NAME curl_easy_send()
*
* DESCRIPTION
*
* Sends data over the connected socket. Use after successful
* curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
*/
CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer,
size_t buflen, size_t *n);
#ifdef __cplusplus
}
#endif
#endif
| 3,472 | 32.718447 | 78 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/libcurl/include/curl/stdcheaders.h
|
#ifndef __STDC_HEADERS_H
#define __STDC_HEADERS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2010, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include <sys/types.h>
size_t fread (void *, size_t, size_t, FILE *);
size_t fwrite (const void *, size_t, size_t, FILE *);
int strcasecmp(const char *, const char *);
int strncasecmp(const char *, const char *, size_t);
#endif /* __STDC_HEADERS_H */
| 1,330 | 38.147059 | 77 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/libcurl/include/curl/curlver.h
|
#ifndef __CURL_CURLVER_H
#define __CURL_CURLVER_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2012, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* This header file contains nothing but libcurl version info, generated by
a script at release-time. This was made its own header file in 7.11.2 */
/* This is the global package copyright */
#define LIBCURL_COPYRIGHT "1996 - 2012 Daniel Stenberg, <[email protected]>."
/* This is the version number of the libcurl package from which this header
file origins: */
#define LIBCURL_VERSION "7.28.1"
/* The numeric version number is also available "in parts" by using these
defines: */
#define LIBCURL_VERSION_MAJOR 7
#define LIBCURL_VERSION_MINOR 28
#define LIBCURL_VERSION_PATCH 1
/* This is the numeric version of the libcurl version number, meant for easier
parsing and comparions by programs. The LIBCURL_VERSION_NUM define will
always follow this syntax:
0xXXYYZZ
Where XX, YY and ZZ are the main version, release and patch numbers in
hexadecimal (using 8 bits each). All three numbers are always represented
using two digits. 1.2 would appear as "0x010200" while version 9.11.7
appears as "0x090b07".
This 6-digit (24 bits) hexadecimal number does not show pre-release number,
and it is always a greater number in a more recent release. It makes
comparisons with greater than and less than work.
*/
#define LIBCURL_VERSION_NUM 0x071c01
/*
* This is the date and time when the full source package was created. The
* timestamp is not stored in git, as the timestamp is properly set in the
* tarballs by the maketgz script.
*
* The format of the date should follow this template:
*
* "Mon Feb 12 11:35:33 UTC 2007"
*/
#define LIBCURL_TIMESTAMP "Tue Nov 20 07:12:05 UTC 2012"
#endif /* __CURL_CURLVER_H */
| 2,741 | 38.171429 | 78 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/libcurl/include/curl/mprintf.h
|
#ifndef __CURL_MPRINTF_H
#define __CURL_MPRINTF_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2006, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include <stdarg.h>
#include <stdio.h> /* needed for FILE */
#include "curl.h"
#ifdef __cplusplus
extern "C" {
#endif
CURL_EXTERN int curl_mprintf(const char *format, ...);
CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...);
CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...);
CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength,
const char *format, ...);
CURL_EXTERN int curl_mvprintf(const char *format, va_list args);
CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args);
CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args);
CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength,
const char *format, va_list args);
CURL_EXTERN char *curl_maprintf(const char *format, ...);
CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args);
#ifdef _MPRINTF_REPLACE
# undef printf
# undef fprintf
# undef sprintf
# undef vsprintf
# undef snprintf
# undef vprintf
# undef vfprintf
# undef vsnprintf
# undef aprintf
# undef vaprintf
# define printf curl_mprintf
# define fprintf curl_mfprintf
#ifdef CURLDEBUG
/* When built with CURLDEBUG we define away the sprintf() functions since we
don't want internal code to be using them */
# define sprintf sprintf_was_used
# define vsprintf vsprintf_was_used
#else
# define sprintf curl_msprintf
# define vsprintf curl_mvsprintf
#endif
# define snprintf curl_msnprintf
# define vprintf curl_mvprintf
# define vfprintf curl_mvfprintf
# define vsnprintf curl_mvsnprintf
# define aprintf curl_maprintf
# define vaprintf curl_mvaprintf
#endif
#ifdef __cplusplus
}
#endif
#endif /* __CURL_MPRINTF_H */
| 2,790 | 33.036585 | 79 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/debug.h
|
#ifndef DEBUGCONFFILE
#define DEBUGCONFFILE
#ifdef DEBUG_BUILD
#define Debug(...) do{ printf(__VA_ARGS__); } while(0)
#else
#define Debug(...) do { } while(0)
#endif
#endif //DEBUGCONFFILE
| 194 | 12.928571 | 54 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/main.cpp
|
/*
* main.cpp
*****************************************************************************
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include <QApplication>
#include "UI/DASHPlayerNoGUI.h"
#include "UI/DASHPlayer.h"
#include "log/log.h"
using namespace sampleplayer;
int main(int argc, char *argv[])
{
bool no_gui = false;
for(int i = 0; i < argc; i++)
{
if(!strcmp(argv[i],"-nohead"))
{
no_gui = true;
break;
}
}
#ifdef LOG_BUILD
// sampleplayer::log::Start((argc > 1) ? argv[1] : NULL);
sampleplayer::log::Start(NULL);
#endif //LOG_BUILD
if(no_gui)
{
pthread_mutex_t mainMutex;
pthread_cond_t mainCond;
pthread_mutex_init(&mainMutex,NULL);
pthread_cond_init(&mainCond, NULL);
L("STARTING NO GUI\n");
DASHPlayerNoGUI p(argc,argv, &mainCond, true);
pthread_mutex_lock(&mainMutex);
while(p.IsRunning())
{
pthread_cond_wait(&mainCond, &mainMutex);
}
pthread_mutex_unlock(&mainMutex);
return 0;
}
else
{
QApplication a(argc, argv);
QtSamplePlayerGui w;
DASHPlayer p(w, argc, argv);
w.show();
L("Start\n");
return a.exec();
}
}
| 1,471 | 20.028571 | 79 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/UI/FullScreenDialog.cpp
|
/*
* FullScreenDialog.cpp
*
* Created on: Oct 11, 2016
* Author: ndnops
*/
#include "QtSamplePlayerGui.h"
using namespace sampleplayer;
FullScreenDialog::FullScreenDialog(QtSamplePlayerGui * gui) :
QDialog((QMainWindow*)gui)
{
this->gui = gui;
}
FullScreenDialog::~FullScreenDialog()
{
delete this;
}
void FullScreenDialog::keyPressEvent (QKeyEvent* event)
{
if(event->key() == Qt::Key_F)
this->accept();
else
this->gui->keyPressEvent(event);
}
| 473 | 14.8 | 61 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/UI/QtSamplePlayerGui.cpp
|
/*
* qtsampleplayer.cpp
*****************************************************************************
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include <QtWidgets>
#include <vector>
#include <sstream>
#include "QtSamplePlayerGui.h"
#include "IDASHPlayerGuiObserver.h"
#include "libdash.h"
using namespace sampleplayer;
using namespace sampleplayer::renderer;
using namespace dash::mpd;
using namespace libdash::framework::mpd;
using namespace libdash::framework::adaptation;
QtSamplePlayerGui::QtSamplePlayerGui (QWidget *parent) :
QMainWindow (parent),
ui (new Ui::QtSamplePlayerClass),
mpd (NULL),
fullscreen (false),
isRunning (false),
isPlaying (false)
{
InitializeCriticalSection(&(this->monitorMutex));
this->ui->setupUi(this);
this->SetVideoSegmentBufferFillState(0);
this->SetVideoBufferFillState(0);
this->SetAudioSegmentBufferFillState(0);
this->SetAudioBufferFillState(0);
this->SetAdaptationLogicComboBox(mpd,this->ui->cb_adaptationlogic);
this->ui->button_stop->setEnabled(false);
this->ui->button_start->setEnabled(false);
// this->myStackedWidget = new QStackedWidget;
// this->myStackedWidget->addWidget(this->ui->centralWidget);
// this->setCentralWidget(this->myStackedWidget);
this->setWindowFlags(Qt::Window);
}
QtSamplePlayerGui::~QtSamplePlayerGui ()
{
DeleteCriticalSection(&(this->monitorMutex));
delete (this->ui);
}
void QtSamplePlayerGui::EnableUserActions ()
{
this->ui->cb_period->setEnabled(true);
this->ui->cb_audio_adaptationset->setEnabled(true);
this->ui->cb_video_adaptationset->setEnabled(true);
this->ui->cb_audio_representation->setEnabled(true);
this->ui->cb_video_representation->setEnabled(true);
this->Reset();
}
void QtSamplePlayerGui::DisableUserActions ()
{
this->ui->cb_period->setEnabled(false);
this->ui->cb_audio_adaptationset->setEnabled(false);
this->ui->cb_video_adaptationset->setEnabled(false);
this->ui->cb_audio_representation->setEnabled(false);
this->ui->cb_video_representation->setEnabled(false);
}
void QtSamplePlayerGui::Reset ()
{
this->ui->button_start->setEnabled(true);
this->ui->button_stop->setEnabled(false);
this->ui->cb_mpd->setDisabled(false);
this->ui->lineEdit_mpd->setDisabled(false);
this->ui->button_mpd->setDisabled(false);
}
void QtSamplePlayerGui::ClearComboBoxes ()
{
this->ui->cb_period->clear();
this->ui->cb_video_adaptationset->clear();
this->ui->cb_video_representation->clear();
this->ui->cb_audio_adaptationset->clear();
this->ui->cb_audio_representation->clear();
}
QTGLRenderer* QtSamplePlayerGui::GetVideoElement ()
{
return this->ui->videoelement;
}
void QtSamplePlayerGui::SetGuiFields (dash::mpd::IMPD* mpd)
{
this->LockUI();
this->ClearComboBoxes();
this->SetPeriodComboBox(mpd, this->ui->cb_period);
if (mpd->GetPeriods().size() > 0)
{
IPeriod *period = mpd->GetPeriods().at(0);
this->SetVideoAdaptationSetComboBox(period, this->ui->cb_video_adaptationset);
this->SetAudioAdaptationSetComboBox(period, this->ui->cb_audio_adaptationset);
if (!AdaptationSetHelper::GetVideoAdaptationSets(period).empty())
{
IAdaptationSet *adaptationSet = AdaptationSetHelper::GetVideoAdaptationSets(period).at(0);
this->SetRepresentationComoboBox(adaptationSet, this->ui->cb_video_representation);
}
if (!AdaptationSetHelper::GetAudioAdaptationSets(period).empty())
{
IAdaptationSet *adaptationSet = AdaptationSetHelper::GetAudioAdaptationSets(period).at(0);
this->SetRepresentationComoboBox(adaptationSet, this->ui->cb_audio_representation);
}
}
this->mpd = mpd;
this->UnLockUI();
this->ui->button_start->setEnabled(true);
}
bool QtSamplePlayerGui::GetNDNStatus ()
{
return this->ui->ndnCheckBox->isChecked();
}
void QtSamplePlayerGui::SetNDNStatus (bool value)
{
this->ui->ndnCheckBox->setCheckState(value? Qt::Checked : Qt::Unchecked);
}
//LogicType
int QtSamplePlayerGui::GetAdaptationLogic ()
{
return this->ui->cb_adaptationlogic->currentIndex();
}
void QtSamplePlayerGui::SetVideoSegmentBufferFillState (int percentage)
{
EnterCriticalSection(&(this->monitorMutex));
this->ui->progressBar_V->setValue(percentage);
LeaveCriticalSection(&(this->monitorMutex));
}
void QtSamplePlayerGui::SetVideoBufferFillState (int percentage)
{
EnterCriticalSection(&(this->monitorMutex));
this->ui->progressBar_VF->setValue(percentage);
LeaveCriticalSection(&(this->monitorMutex));
}
void QtSamplePlayerGui::SetAudioSegmentBufferFillState (int percentage)
{
EnterCriticalSection(&(this->monitorMutex));
this->ui->progressBar_A->setValue(percentage);
LeaveCriticalSection(&(this->monitorMutex));
}
void QtSamplePlayerGui::SetAudioBufferFillState (int percentage)
{
EnterCriticalSection(&(this->monitorMutex));
this->ui->progressBar_AC->setValue(percentage);
LeaveCriticalSection(&(this->monitorMutex));
}
void QtSamplePlayerGui::AddWidgetObserver (IDASHPlayerGuiObserver *observer)
{
this->observers.push_back(observer);
}
void QtSamplePlayerGui::SetStatusBar (const std::string& text)
{
QString str(text.c_str());
this->ui->statusBar->showMessage(str);
}
void QtSamplePlayerGui::SetRepresentationComoboBox (dash::mpd::IAdaptationSet *adaptationSet, QComboBox *cb)
{
std::vector<IRepresentation *> represenations = adaptationSet->GetRepresentation();
cb->clear();
for(size_t i = 0; i < represenations.size(); i++)
{
IRepresentation *representation = represenations.at(i);
std::stringstream ss;
ss << representation->GetId() << " " << representation->GetBandwidth() << " bps " << representation->GetWidth() << "x" << representation->GetHeight();
cb->addItem(QString(ss.str().c_str()));
}
}
void QtSamplePlayerGui::SetAdaptationSetComboBox (dash::mpd::IPeriod *period, QComboBox *cb)
{
std::vector<IAdaptationSet *> adaptationSets = period->GetAdaptationSets();
cb->clear();
for(size_t i = 0; i < adaptationSets.size(); i++)
{
IAdaptationSet *adaptationSet = adaptationSets.at(i);
std::stringstream ss;
ss << "AdaptationSet " << i+1;
cb->addItem(QString(ss.str().c_str()));
}
}
void QtSamplePlayerGui::SetAudioAdaptationSetComboBox (dash::mpd::IPeriod *period, QComboBox *cb)
{
std::vector<IAdaptationSet *> adaptationSets = AdaptationSetHelper::GetAudioAdaptationSets(period);
cb->clear();
for(size_t i = 0; i < adaptationSets.size(); i++)
{
IAdaptationSet *adaptationSet = adaptationSets.at(i);
std::stringstream ss;
ss << "AdaptationSet " << i+1;
cb->addItem(QString(ss.str().c_str()));
}
}
void QtSamplePlayerGui::SetVideoAdaptationSetComboBox (dash::mpd::IPeriod *period, QComboBox *cb)
{
std::vector<IAdaptationSet *> adaptationSets = AdaptationSetHelper::GetVideoAdaptationSets(period);
cb->clear();
for(size_t i = 0; i < adaptationSets.size(); i++)
{
IAdaptationSet *adaptationSet = adaptationSets.at(i);
std::stringstream ss;
ss << "AdaptationSet " << i+1;
cb->addItem(QString(ss.str().c_str()));
}
}
void QtSamplePlayerGui::SetPeriodComboBox (dash::mpd::IMPD *mpd, QComboBox *cb)
{
std::vector<IPeriod *> periods = mpd->GetPeriods();
cb->clear();
for(size_t i = 0; i < periods.size(); i++)
{
IPeriod *period = periods.at(i);
std::stringstream ss;
ss << "Period " << i+1;
cb->addItem(QString(ss.str().c_str()));
}
}
void QtSamplePlayerGui::SetAdaptationLogicComboBox (dash::mpd::IMPD *mpd, QComboBox *cb)
{
cb->clear();
for(int i = 0; i < Count; i++)
{
cb->addItem(QString(LogicType_string[i]));
}
}
void QtSamplePlayerGui::LockUI ()
{
this->setEnabled(false);
}
void QtSamplePlayerGui::UnLockUI ()
{
this->setEnabled(true);
}
std::string QtSamplePlayerGui::GetUrl ()
{
this->LockUI();
std::string ret = this->ui->lineEdit_mpd->text().toStdString();
this->UnLockUI();
return ret;
}
/* Notifiers */
void QtSamplePlayerGui::NotifySettingsChanged ()
{
this->LockUI();
int period = this->ui->cb_period->currentIndex();
int videoAdaptionSet = this->ui->cb_video_adaptationset->currentIndex();
int videoRepresentation = this->ui->cb_video_representation->currentIndex();
int audioAdaptionSet = this->ui->cb_audio_adaptationset->currentIndex();
int audioRepresentation = this->ui->cb_audio_representation->currentIndex();
for(size_t i = 0; i < this->observers.size(); i++)
this->observers.at(i)->OnSettingsChanged(period, videoAdaptionSet, videoRepresentation, audioAdaptionSet, audioRepresentation);
this->UnLockUI();
}
void QtSamplePlayerGui::NotifyMPDDownloadPressed (const std::string &url)
{
for(size_t i = 0; i < this->observers.size(); i++)
this->observers.at(i)->OnDownloadMPDPressed(url);
}
void QtSamplePlayerGui::NotifyStartButtonPressed ()
{
this->LockUI();
int period = this->ui->cb_period->currentIndex();
int videoAdaptionSet = this->ui->cb_video_adaptationset->currentIndex();
int videoRepresentation = this->ui->cb_video_representation->currentIndex();
int audioAdaptionSet = this->ui->cb_audio_adaptationset->currentIndex();
int audioRepresentation = this->ui->cb_audio_representation->currentIndex();
for(size_t i = 0; i < this->observers.size(); i++)
this->observers.at(i)->OnStartButtonPressed(period, videoAdaptionSet, videoRepresentation, audioAdaptionSet, audioRepresentation);
this->isPlaying = true;
this->UnLockUI();
}
void QtSamplePlayerGui::NotifyPauseButtonPressed ()
{
for(size_t i = 0; i < this->observers.size(); i++)
this->observers.at(i)->OnPauseButtonPressed();
this->isPlaying = !this->isPlaying;
}
void QtSamplePlayerGui::NotifyFastForward ()
{
for(size_t i = 0; i < this->observers.size(); i++)
this->observers.at(i)->OnFastForward();
this->isPlaying = !this->isPlaying;
}
void QtSamplePlayerGui::NotifyFastRewind ()
{
for(size_t i = 0; i < this->observers.size(); i++)
this->observers.at(i)->OnFastRewind();
this->isPlaying = !this->isPlaying;
}
void QtSamplePlayerGui::NotifyStopButtonPressed ()
{
for(size_t i = 0; i < this->observers.size(); i++)
this->observers.at(i)->OnStopButtonPressed();
}
/* UI Slots */
void QtSamplePlayerGui::on_button_mpd_clicked ()
{
this->mpd = NULL;
this->NotifyMPDDownloadPressed(this->GetUrl());
}
void QtSamplePlayerGui::on_cb_period_currentIndexChanged (int index)
{
if(index == -1 || this->mpd == NULL)
return; // No Item set
this->LockUI();
this->SetAudioAdaptationSetComboBox(mpd->GetPeriods().at(index), ui->cb_audio_adaptationset);
this->SetVideoAdaptationSetComboBox(mpd->GetPeriods().at(index), ui->cb_video_adaptationset);
this->NotifySettingsChanged();
this->UnLockUI();
}
void QtSamplePlayerGui::on_cb_mpd_currentTextChanged (const QString &arg1)
{
this->ui->button_start->setDisabled(true);
this->ui->lineEdit_mpd->setText(arg1);
}
void QtSamplePlayerGui::SetUrl (const char * text)
{
this->ui->lineEdit_mpd->setText(QString(text));
}
void QtSamplePlayerGui::SetAdaptationLogic (LogicType type)
{
this->ui->cb_adaptationlogic->setCurrentIndex((int) type);
}
void QtSamplePlayerGui::on_cb_video_adaptationset_currentIndexChanged (int index)
{
if(index == -1 || this->mpd == NULL)
return; // No Item set
this->LockUI();
IPeriod *period = this->mpd->GetPeriods().at(this->ui->cb_period->currentIndex());
this->SetRepresentationComoboBox(AdaptationSetHelper::GetVideoAdaptationSets(period).at(index), this->ui->cb_video_representation);
this->NotifySettingsChanged();
this->UnLockUI();
}
void QtSamplePlayerGui::on_cb_video_representation_currentIndexChanged (int index)
{
if(index == -1)
return; // No Item set
this->NotifySettingsChanged();
}
void QtSamplePlayerGui::on_cb_audio_adaptationset_currentIndexChanged (int index)
{
if(index == -1 || this->mpd == NULL)
return; // No Item set
this->LockUI();
IPeriod *period = this->mpd->GetPeriods().at(this->ui->cb_period->currentIndex());
this->SetRepresentationComoboBox(AdaptationSetHelper::GetAudioAdaptationSets(period).at(index), this->ui->cb_audio_representation);
this->NotifySettingsChanged();
this->UnLockUI();
}
void QtSamplePlayerGui::on_cb_audio_representation_currentIndexChanged (int index)
{
if(index == -1)
return; // No Item set
this->NotifySettingsChanged();
}
void QtSamplePlayerGui::LockStartAndDownloadButton ()
{
this->ui->button_start->setEnabled(false);
this->ui->button_stop->setEnabled(true);
this->ui->cb_mpd->setDisabled(true);
this->ui->lineEdit_mpd->setDisabled(true);
this->ui->button_mpd->setDisabled(true);
}
void QtSamplePlayerGui::on_button_start_clicked ()
{
this->ui->button_start->setEnabled(false);
this->ui->button_stop->setEnabled(true);
this->ui->cb_mpd->setDisabled(true);
this->ui->lineEdit_mpd->setDisabled(true);
this->ui->button_mpd->setDisabled(true);
this->NotifyStartButtonPressed();
}
void QtSamplePlayerGui::on_button_stop_clicked ()
{
this->ui->button_start->setEnabled(true);
this->ui->button_stop->setEnabled(false);
this->ui->cb_mpd->setDisabled(false);
this->ui->lineEdit_mpd->setDisabled(false);
this->ui->button_mpd->setDisabled(false);
this->NotifyStopButtonPressed();
}
void QtSamplePlayerGui::mouseDoubleClickEvent (QMouseEvent* event)
{
this->OnDoubleClick();
}
void QtSamplePlayerGui::OnDoubleClick ()
{
FullScreenDialog *dlg = new FullScreenDialog(this);
QHBoxLayout *dlgLayout = new QHBoxLayout(dlg);
dlgLayout->setContentsMargins(0,0,0,0);
dlgLayout->addWidget(this->ui->videoelement);
dlg->setLayout(dlgLayout);
dlg->setWindowFlags(Qt::Window);
dlg->showFullScreen();
bool r = connect(dlg, SIGNAL(rejected()), this, SLOT(showNormal()));
assert(r);
r = connect(dlg, SIGNAL(accepted()), this, SLOT(showNormal()));
assert(r);
}
void QtSamplePlayerGui::showNormal()
{
this->ui->verticalLayout_3->addWidget(this->ui->videoelement);
}
/*void QtSamplePlayerGui::OnDoubleClick ()
{
if(!this->isRunning)
{
return;
}
if(this->fullscreen)
{
this->showNormal();
this->myStackedWidget->setCurrentWidget(this->ui->centralWidget);
this->myStackedWidget->removeWidget(this->ui->videoelement);
this->ui->verticalLayout_3->addWidget(this->ui->videoelement);
this->ui->videoelement->show();
this->fullscreen = false;
}
else
{
this->ui->statusBar->hide();
this->myStackedWidget->addWidget(this->ui->videoelement);
this->myStackedWidget->setCurrentWidget(this->ui->videoelement);
this->showFullScreen();
this->fullscreen = true;
}
} */
void QtSamplePlayerGui::keyPressEvent (QKeyEvent* event)
{
switch(event->key())
{
//Play/Pause
case Qt::Key_P:
{
this->NotifyPauseButtonPressed();
break;
}
//Full Screen
case Qt::Key_F:
{
this->OnDoubleClick();
break;
}
//Fast Forward
case Qt::Key_L:
{
this->NotifyFastForward();
break;
}
//Fast Rewind
case Qt::Key_T:
{
this->NotifyFastRewind();
break;
}
default:
{
break;
}
}
}
| 16,324 | 29.571161 | 153 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/UI/DASHPlayerNoGUI.h
|
/*
* DASHPlayerNoGUI.h
*****************************************************************************
* Copyright (C) 2016
*
* Jacques Samain <[email protected]>
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef DASHPLAYERNOGUI_H_
#define DASHPLAYERNOGUI_H_
#include <iostream>
#include <sstream>
#include "libdash.h"
#include "IDASHPlayerNoGuiObserver.h"
#include "../Managers/IMultimediaManagerObserver.h"
#include "../Renderer/QTGLRenderer.h"
#include "../Renderer/QTAudioRenderer.h"
#include "../Managers/MultimediaManager.h"
#include "../libdashframework/Adaptation/AlwaysLowestLogic.h"
#include "../libdashframework/Adaptation/IAdaptationLogic.h"
#include "../libdashframework/Adaptation/ManualAdaptation.h"
#include "../libdashframework/Buffer/IBufferObserver.h"
#include "../libdashframework/MPD/AdaptationSetHelper.h"
#include "DASHPlayer.h"
namespace sampleplayer
{
class DASHPlayerNoGUI : public IDASHPlayerNoGuiObserver, public managers::IMultimediaManagerObserver
{
public:
DASHPlayerNoGUI (int argc, char** argv, pthread_cond_t *mainCond, bool nodecoding);
virtual ~DASHPlayerNoGUI ();
void parseArgs(int argc, char ** argv);
void helpMessage(char *name);
virtual void OnStartButtonPressed (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation);
virtual void OnStopButtonPressed ();
virtual void OnSettingsChanged (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation);
/* IMultimediaManagerObserver */
virtual void OnVideoBufferStateChanged (uint32_t fillstateInPercent);
virtual void OnVideoSegmentBufferStateChanged (uint32_t fillstateInPercent);
virtual void OnAudioBufferStateChanged (uint32_t fillstateInPercent);
virtual void OnAudioSegmentBufferStateChanged (uint32_t fillstateInPercent);
virtual void OnEOS ();
virtual bool OnDownloadMPDPressed (const std::string &url);
bool IsRunning ();
private:
dash::mpd::IMPD *mpd;
sampleplayer::renderer::QTGLRenderer *videoElement;
sampleplayer::renderer::QTAudioRenderer *audioElement;
sampleplayer::managers::MultimediaManager *multimediaManager;
settings_t currentSettings;
CRITICAL_SECTION monitorMutex;
char *url;
bool isNDN;
libdash::framework::adaptation::LogicType adaptLogic;
pthread_cond_t *mainCond;
bool isRunning;
int reservoirThreshold;
int maxThreshold;
double bufferTargetSeconds;
double alphaRate;
bool isBuff;
double ndnAlpha;
bool chunkGranularity;
int samplesize;
bool SettingsChanged (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation);
void SetSettings (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation);
bool noDecoding;
double qoe_w1;
double qoe_w2;
double qoe_w3;
};
}
#endif /* DASHPLAYER_H_ */
| 3,960 | 45.05814 | 159 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/UI/QtSamplePlayerGui.h
|
/*
* qtsampleplayer.h
*****************************************************************************
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef QTSAMPLEPLAYER_H
#define QTSAMPLEPLAYER_H
#include <QtMultimedia/qmediaplayer.h>
#include <QtMultimediaWidgets/qvideowidget.h>
#include <QtGui/QMovie>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QStackedWidget>
#include <QMouseEvent>
#include "ui_qtsampleplayer.h"
#include "libdash.h"
#include "../libdashframework/MPD/AdaptationSetHelper.h"
#include "../libdashframework/Adaptation/IAdaptationLogic.h"
#include "../libdashframework/Portable/MultiThreading.h"
#include <QDialog>
//#include "FullScreenDialog.h"
namespace sampleplayer
{
class IDASHPlayerGuiObserver;
class QtSamplePlayerGui : public QMainWindow
{
Q_OBJECT
public:
QtSamplePlayerGui (QWidget *parent = 0);
virtual ~QtSamplePlayerGui ();
void SetGuiFields (dash::mpd::IMPD* mpd);
virtual void AddWidgetObserver (IDASHPlayerGuiObserver* observer);
virtual void SetStatusBar (const std::string& text);
virtual std::string GetUrl ();
sampleplayer::renderer::QTGLRenderer* GetVideoElement ();
void DisableUserActions (); //On Bitrate selection
void EnableUserActions (); //On Bitrate selection
void Reset ();
void mouseDoubleClickEvent (QMouseEvent* event);
void keyPressEvent (QKeyEvent* event);
QStackedWidget* myStackedWidget;
bool isRunning;
void LockStartAndDownloadButton ();
private slots:
void on_cb_mpd_currentTextChanged (const QString &arg1);
void on_cb_period_currentIndexChanged (int index);
void on_cb_video_adaptationset_currentIndexChanged (int index);
void on_cb_video_representation_currentIndexChanged (int index);
void on_cb_audio_adaptationset_currentIndexChanged (int index);
void on_cb_audio_representation_currentIndexChanged (int index);
void on_button_mpd_clicked ();
void on_button_start_clicked ();
void on_button_stop_clicked ();
public slots:
virtual void SetVideoSegmentBufferFillState (int percentage);
virtual void SetVideoBufferFillState (int percentage);
virtual void SetAudioSegmentBufferFillState (int percentage);
virtual void SetAudioBufferFillState (int percentage);
int GetAdaptationLogic ();
bool GetNDNStatus (); //check if NDN is enabled or classical TCP
void SetNDNStatus (bool value);
void SetUrl (const char* text);
void SetAdaptationLogic (libdash::framework::adaptation::LogicType type);
void showNormal ();
private:
std::map<std::string, std::string> keyValues;
std::map<std::string, int> keyIndices;
std::map<std::string, std::vector<std::string> > video;
std::map<std::string, std::vector<std::string> > audio;
CRITICAL_SECTION monitorMutex;
Ui::QtSamplePlayerClass *ui;
std::vector<IDASHPlayerGuiObserver *> observers;
dash::mpd::IMPD *mpd;
bool fullscreen;
bool isPlaying;
void LockUI ();
void UnLockUI ();
void SetPeriodComboBox (dash::mpd::IMPD *mpd, QComboBox *cb);
void SetAdaptationLogicComboBox (dash::mpd::IMPD *mpd, QComboBox *cb);
void SetAdaptationSetComboBox (dash::mpd::IPeriod *period, QComboBox *cb);
void SetVideoAdaptationSetComboBox (dash::mpd::IPeriod *period, QComboBox *cb);
void SetAudioAdaptationSetComboBox (dash::mpd::IPeriod *period, QComboBox *cb);
void SetRepresentationComoboBox (dash::mpd::IAdaptationSet *adaptationSet, QComboBox *cb);
void ClearComboBoxes ();
void OnDoubleClick ();
void NotifySettingsChanged ();
void NotifyMPDDownloadPressed (const std::string &url);
void NotifyStartButtonPressed ();
void NotifyStopButtonPressed ();
void NotifyPauseButtonPressed ();
void NotifyFastForward ();
void NotifyFastRewind ();
};
class FullScreenDialog : public QDialog {
public:
FullScreenDialog(QtSamplePlayerGui *gui);
~FullScreenDialog();
void keyPressEvent (QKeyEvent* event);
private:
QtSamplePlayerGui *gui;
};
}
#endif // QTSAMPLEPLAYER_H
| 5,505 | 41.682171 | 111 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/UI/DASHPlayer.cpp
|
/*
* DASHPlayer.cpp
*****************************************************************************
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "DASHPlayer.h"
#include <iostream>
using namespace libdash::framework::adaptation;
using namespace libdash::framework::mpd;
using namespace libdash::framework::buffer;
using namespace sampleplayer;
using namespace sampleplayer::renderer;
using namespace sampleplayer::managers;
using namespace dash::mpd;
using namespace std;
DASHPlayer::DASHPlayer (QtSamplePlayerGui &gui,int argc, char ** argv) :
gui (&gui)
{
InitializeCriticalSection(&this->monitorMutex);
this->url = NULL;
this->isNDN = false;
this->adaptLogic = LogicType::RateBased;
// this->parseArgs(argc, argv);
if(argc == 2)
{
if(strstr(argv[1],"ndn:/"))
this->isNDN = true;
const char* startUrl = this->isNDN ? strstr(argv[1], "ndn:/") : strstr(argv[1], "http://");
this->url = startUrl;
const char* pos = strstr(this->url,"GNOME_KEYRING");
if(pos)
strncpy(pos, "\0", 1);
}
this->SetSettings(0, 0, 0, 0, 0);
this->videoElement = gui.GetVideoElement();
this->audioElement = new QTAudioRenderer(&gui);
this->multimediaManager = new MultimediaManager(this->videoElement, this->audioElement);
this->multimediaManager->SetFrameRate(25);
this->multimediaManager->AttachManagerObserver(this);
this->gui->AddWidgetObserver(this);
QObject::connect(this, SIGNAL(VideoSegmentBufferFillStateChanged(int)), &gui, SLOT(SetVideoSegmentBufferFillState(int)));
QObject::connect(this, SIGNAL(VideoBufferFillStateChanged(int)), &gui, SLOT(SetVideoBufferFillState(int)));
QObject::connect(this, SIGNAL(AudioSegmentBufferFillStateChanged(int)), &gui, SLOT(SetAudioSegmentBufferFillState(int)));
QObject::connect(this, SIGNAL(AudioBufferFillStateChanged(int)), &gui, SLOT(SetAudioBufferFillState(int)));
bool shouldStart = false;
if(this->isNDN)
{
this->gui->SetNDNStatus(this->isNDN);
}
if(this->url != NULL)
{
shouldStart = true;
this->gui->SetUrl(this->url);
}
this->gui->SetAdaptationLogic(this->adaptLogic);
if(shouldStart)
{
if(this->OnDownloadMPDPressed(string(this->url)))
{
this->gui->LockStartAndDownloadButton();
this->OnStartButtonPressed(0,0,0,0,0);
this->videoElement->grabKeyboard();
}
}
}
DASHPlayer::~DASHPlayer ()
{
this->multimediaManager->Stop();
this->audioElement->StopPlayback();
this->audioElement = NULL;
delete(this->multimediaManager);
delete(this->audioElement);
DeleteCriticalSection(&this->monitorMutex);
}
void DASHPlayer::OnStartButtonPressed (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation)
{
if(!((this->multimediaManager->SetVideoAdaptationLogic((LogicType)this->gui->GetAdaptationLogic(), 0, 0, 0) && (this->multimediaManager->SetAudioAdaptationLogic((LogicType)this->gui->GetAdaptationLogic(), 0, 0, 0)))))
{
this->gui->SetStatusBar("Error setting Video/Audio adaptation logic...");
return;
}
if(!this->multimediaManager->IsUserDependent())
{
this->gui->DisableUserActions();
}
this->gui->isRunning = true;
L("DASH PLAYER: STARTING VIDEO\n");
this->multimediaManager->Start(this->gui->GetNDNStatus(), 20, false, 100); //only segment-based adaptation when gui, therefore also samplesize not important
}
void DASHPlayer::OnStopButtonPressed ()
{
this->gui->EnableUserActions();
this->multimediaManager->Stop();
}
void DASHPlayer::OnPauseButtonPressed ()
{
this->multimediaManager->OnPausePressed();
}
void DASHPlayer::OnFastForward ()
{
this->multimediaManager->OnFastForward();
}
void DASHPlayer::OnFastRewind ()
{
this->multimediaManager->OnFastRewind();
}
void DASHPlayer::OnSettingsChanged (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation)
{
if(this->multimediaManager->GetMPD() == NULL)
return; // TODO dialog or symbol that indicates that error
if (!this->SettingsChanged(period, videoAdaptationSet, videoRepresentation, audioAdaptationSet, audioRepresentation))
return;
IPeriod *currentPeriod = this->multimediaManager->GetMPD()->GetPeriods().at(period);
std::vector<IAdaptationSet *> videoAdaptationSets = AdaptationSetHelper::GetVideoAdaptationSets(currentPeriod);
std::vector<IAdaptationSet *> audioAdaptationSets = AdaptationSetHelper::GetAudioAdaptationSets(currentPeriod);
if (videoAdaptationSet >= 0 && videoRepresentation >= 0)
{
this->multimediaManager->SetVideoQuality(currentPeriod,
videoAdaptationSets.at(videoAdaptationSet),
videoAdaptationSets.at(videoAdaptationSet)->GetRepresentation().at(videoRepresentation));
}
else
{
this->multimediaManager->SetVideoQuality(currentPeriod, NULL, NULL);
}
if (audioAdaptationSet >= 0 && audioRepresentation >= 0)
{
this->multimediaManager->SetAudioQuality(currentPeriod,
audioAdaptationSets.at(audioAdaptationSet),
audioAdaptationSets.at(audioAdaptationSet)->GetRepresentation().at(audioRepresentation));
}
else
{
this->multimediaManager->SetAudioQuality(currentPeriod, NULL, NULL);
}
}
void DASHPlayer::OnVideoBufferStateChanged (uint32_t fillstateInPercent)
{
emit VideoBufferFillStateChanged(fillstateInPercent);
}
void DASHPlayer::OnVideoSegmentBufferStateChanged (uint32_t fillstateInPercent)
{
emit VideoSegmentBufferFillStateChanged(fillstateInPercent);
}
void DASHPlayer::OnAudioBufferStateChanged (uint32_t fillstateInPercent)
{
emit AudioBufferFillStateChanged(fillstateInPercent);
}
void DASHPlayer::OnAudioSegmentBufferStateChanged (uint32_t fillstateInPercent)
{
emit AudioSegmentBufferFillStateChanged(fillstateInPercent);
}
void DASHPlayer::OnEOS ()
{
this->OnStopButtonPressed();
}
bool DASHPlayer::OnDownloadMPDPressed (const std::string &url)
{
if(this->gui->GetNDNStatus())
{
if(!this->multimediaManager->InitNDN(url))
{
this->gui->SetStatusBar("Error parsing mpd at: " + url);
return false;
}
}
else
{
if(!this->multimediaManager->Init(url))
{
this->gui->SetStatusBar("Error parsing mpd at: " + url);
return false; // TODO dialog or symbol that indicates that error
}
}
this->SetSettings(-1, -1, -1, -1, -1);
this->gui->SetGuiFields(this->multimediaManager->GetMPD());
this->gui->SetStatusBar("Successfully parsed MPD at: " + url);
return true;
}
bool DASHPlayer::SettingsChanged (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation)
{
EnterCriticalSection(&this->monitorMutex);
bool settingsChanged = false;
if (this->currentSettings.videoRepresentation != videoRepresentation ||
this->currentSettings.audioRepresentation != audioRepresentation ||
this->currentSettings.videoAdaptationSet != videoAdaptationSet ||
this->currentSettings.audioAdaptationSet != audioAdaptationSet ||
this->currentSettings.period != period)
settingsChanged = true;
if (settingsChanged)
this->SetSettings(period, videoAdaptationSet, videoRepresentation, audioAdaptationSet, audioRepresentation);
LeaveCriticalSection(&this->monitorMutex);
return settingsChanged;
}
void DASHPlayer::SetSettings (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation)
{
this->currentSettings.period = period;
this->currentSettings.videoAdaptationSet = videoAdaptationSet;
this->currentSettings.videoRepresentation = videoRepresentation;
this->currentSettings.audioAdaptationSet = audioAdaptationSet;
this->currentSettings.audioRepresentation = audioRepresentation;
}
void DASHPlayer::parseArgs(int argc, char ** argv)
{
if(argc == 1)
{
return;
}
else
{
int i = 0;
while(i < argc)
{
if(!strcmp(argv[i],"-u"))
{
this->url = argv[i+1];
i++;
goto end;
}
if(!strcmp(argv[i],"-n"))
{
this->isNDN = true;
goto end;
}
if(!strcmp(argv[i],"-a"))
{
int j =0;
for(j = 0; j < LogicType::Count; j++)
{
if(!strcmp(LogicType_string[j],argv[i+1]))
{
this->adaptLogic = (LogicType)j;
break;
}
}
if(j == LogicType::Count)
{
printf("the different adaptation logics implemented are:\n");
for(j = 0;j < LogicType::Count; j++)
{
printf("*%s\n",LogicType_string[j]);
}
printf("By default, the %s logic is selected.\n", LogicType_string[this->adaptLogic]);
}
i++;
goto end;
}
end: i++;
}
}
}
| 9,450 | 32.633452 | 221 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/UI/IDASHPlayerNoGuiObserver.h
|
/*
* IDASHPlayerNoGuiObserver.h
*****************************************************************************
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef IDASHPLAYERNOGUIOBSERVER_H_
#define IDASHPLAYERNOGUIOBSERVER_H_
#include <string>
#include "QtSamplePlayerGui.h"
namespace sampleplayer
{
class IDASHPlayerNoGuiObserver
{
public:
virtual ~IDASHPlayerNoGuiObserver() {}
virtual void OnSettingsChanged (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation) = 0;
virtual void OnStartButtonPressed (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation) = 0;
virtual void OnStopButtonPressed () = 0;
virtual bool OnDownloadMPDPressed (const std::string &url) = 0;
};
}
#endif /* IDASHPLAYERNOGUIOBSERVER_H_ */
| 1,411 | 44.548387 | 164 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/UI/DASHPlayerNoGUI.cpp
|
/*
* DASHPlayerNoGUI.cpp
*****************************************************************************
* Copyright (C) 2016
*
* Jacques Samain <[email protected]>
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "DASHPlayerNoGUI.h"
#include <iostream>
using namespace libdash::framework::adaptation;
using namespace libdash::framework::mpd;
using namespace libdash::framework::buffer;
using namespace sampleplayer;
using namespace sampleplayer::renderer;
using namespace sampleplayer::managers;
using namespace dash::mpd;
using namespace std;
DASHPlayerNoGUI::DASHPlayerNoGUI (int argc, char ** argv, pthread_cond_t *mainCond, bool nodecoding) :
mainCond (mainCond),
isRunning (true),
noDecoding (nodecoding)
{
InitializeCriticalSection(&this->monitorMutex);
// this->SetSettings(0, 0, 0, 0, 0);
this->videoElement = NULL;
this->audioElement = NULL;
this->mpd = NULL;
this->url = NULL;
this->adaptLogic = LogicType::RateBased;
this->isNDN = false;
this->ndnAlpha = 20;
this->chunkGranularity = false; //default on segment-based feedback
this->samplesize = 50; //default samplesize (e.g. when on segment-based feedback)
this->alphaRate = 0;
this->bufferTargetSeconds = 0;
this->reservoirThreshold = 0;
this->maxThreshold = 0;
this->isBuff = false;
this->qoe_w1 = -1.0;
this->qoe_w2 = -1.0;
this->qoe_w3 = -1.0;
this->multimediaManager = new MultimediaManager(this->videoElement, this->audioElement, noDecoding);
this->multimediaManager->SetFrameRate(25);
this->multimediaManager->AttachManagerObserver(this);
this->parseArgs(argc, argv);
if(this->url == NULL)
{
this->isRunning = false;
pthread_cond_broadcast(mainCond);
//delete(this);
return;
}
else
{
if(this->OnDownloadMPDPressed(string(this->url)))
{
this->OnStartButtonPressed(0,0,0,0,0);
}
else
{
this->isRunning = false;
pthread_cond_broadcast(mainCond);
}
}
}
DASHPlayerNoGUI::~DASHPlayerNoGUI ()
{
this->multimediaManager->Stop();
if(this->audioElement)
this->audioElement->StopPlayback();
this->audioElement = NULL;
delete(this->multimediaManager);
delete(this->audioElement);
DeleteCriticalSection(&this->monitorMutex);
}
void DASHPlayerNoGUI::OnStartButtonPressed (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation)
{
this->OnSettingsChanged(period,videoAdaptationSet,videoRepresentation, audioAdaptationSet, audioRepresentation);
// if(!(this->isBuff ?
// (this->multimediaManager->SetVideoAdaptationLogic((LogicType)this->adaptLogic,this->alphaRate, this->reservoirThreshold, this->maxThreshold) && (this->multimediaManager->SetAudioAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate, this->reservoirThreshold, this->maxThreshold))) : (this->multimediaManager->SetVideoAdaptationLogic((LogicType)this->adaptLogic,this->alphaRate) && (this->multimediaManager->SetAudioAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate)))))
bool setOk;
if(this->isBuff)
{
switch((LogicType)this->adaptLogic)
{
case Bola:
{
setOk = this->multimediaManager->SetVideoAdaptationLogic((LogicType)this->adaptLogic,this->alphaRate, this->bufferTargetSeconds, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
setOk = this->multimediaManager->SetAudioAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate, this->bufferTargetSeconds, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
break;
}
case Panda:
{
setOk = this->multimediaManager->SetVideoAdaptationLogic((LogicType)this->adaptLogic,this->alphaRate, this->bufferTargetSeconds, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
setOk = this->multimediaManager->SetAudioAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate, this->bufferTargetSeconds, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
break;
}
case FOOBAR:
{
setOk = this->multimediaManager->SetVideoAdaptationLogic((LogicType)this->adaptLogic,this->alphaRate, this->bufferTargetSeconds, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
setOk = this->multimediaManager->SetAudioAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate, this->bufferTargetSeconds, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
break;
}
case SparseBayesUcb:
{
setOk = this->multimediaManager->SetVideoAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate, this->bufferTargetSeconds, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
setOk = this->multimediaManager->SetAudioAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate, this->bufferTargetSeconds, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
break;
}
case SparseBayesUcbOse:
{
setOk = this->multimediaManager->SetVideoAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate, this->bufferTargetSeconds, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
setOk = this->multimediaManager->SetAudioAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate, this->bufferTargetSeconds, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
break;
}
case SparseBayesUcbSvi:
{
setOk = this->multimediaManager->SetVideoAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate, this->bufferTargetSeconds, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
setOk = this->multimediaManager->SetAudioAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate, this->bufferTargetSeconds, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
break;
}
case LinUcb:
{
setOk = this->multimediaManager->SetVideoAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate, this->bufferTargetSeconds, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
setOk = this->multimediaManager->SetAudioAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate, this->bufferTargetSeconds, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
break;
}
default:
{
setOk = this->multimediaManager->SetVideoAdaptationLogic((LogicType)this->adaptLogic,this->alphaRate, this->reservoirThreshold, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
setOk = this->multimediaManager->SetAudioAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate, this->reservoirThreshold, (double)this->maxThreshold,
this->qoe_w1, this->qoe_w2, this->qoe_w3);
break;
}
}
}
else
{
setOk = this->multimediaManager->SetVideoAdaptationLogic((LogicType)this->adaptLogic,this->alphaRate);
setOk = this->multimediaManager->SetAudioAdaptationLogic((LogicType)this->adaptLogic, this->alphaRate);
}
if(!setOk)
{
printf("Error setting Video/Audio adaptation logic...\n");
return;
}
L("DASH PLAYER: STARTING VIDEO\n");
this->multimediaManager->Start(this->isNDN, this->ndnAlpha, this->chunkGranularity, this->samplesize);
}
void DASHPlayerNoGUI::OnStopButtonPressed ()
{
this->multimediaManager->Stop();
this->isRunning = false;
pthread_cond_broadcast(mainCond);
}
bool DASHPlayerNoGUI::IsRunning ()
{
return this->isRunning;
}
void DASHPlayerNoGUI::parseArgs (int argc, char ** argv)
{
if(argc == 1)
{
helpMessage(argv[0]);
return;
}
else
{
int i = 0;
while(i < argc)
{
if(!strcmp(argv[i],"-u"))
{
this->url = argv[i+1];
i++;
i++;
continue;
}
if(!strcmp(argv[i],"-n"))
{
this->isNDN = true;
i++;
continue;
}
if(!strcmp(argv[i],"-c")) //flag: chunk granularity enabled + value: samplesize for chunk feedback
{
this->chunkGranularity = true;
char *end;
int correctInput = strtol(argv[i+1], &end, 10);
if (*end == '\0')
{
this->samplesize = atoi(argv[i+1]);
printf("Chunk-based feedback for adaptation, with value: %s\n", argv[i+1]);
i = i + 2;
} else {
printf("ERROR! Invalid value for samplesize: <<%s>>, therefore set to default value 50.\n", argv[i+1]);
i = i + 1;
}
continue;
}
if(!strcmp(argv[i],"-localmpd")) //flag for extended mpd addition
{
this->multimediaManager->SetLocalMPD(argv[i+1]); //multimediaManager already there?
printf("Use extended MPD information with new MPD at local path: %s\n", argv[i+1]);
i=i+1;
}
if(!strcmp(argv[i],"-nr"))
{
this->isNDN = true;
this->ndnAlpha = atof(argv[i+1]);
i++;
i++;
continue;
}
if(!strcmp(argv[i], "-b"))
{
this->adaptLogic = LogicType::BufferBased;
this->isBuff = true;
this->reservoirThreshold = atoi(argv[i+1]);
this->maxThreshold = atoi(argv[i+2]);
i = i + 3;
continue;
}
if(!strcmp(argv[i], "-br"))
{
this->adaptLogic = LogicType::BufferRateBased;
this->isBuff = true;
this->alphaRate = atof(argv[i+1]);
this->reservoirThreshold = atoi(argv[i+2]);
this->maxThreshold = atoi(argv[i+3]);
i = i + 3;
printf("BufferRateBased chosen, next arg is: %s\n", argv[i]);
continue;
}
if(!strcmp(argv[i], "-bola"))
{
this->adaptLogic = LogicType::Bola;
this->isBuff = true;
this->alphaRate = atof(argv[i+1]);
this->bufferTargetSeconds = 0;
this->qoe_w1 = atof(argv[i+2]);
this->qoe_w2 = atof(argv[i+3]);
this->qoe_w3 = atof(argv[i+4]);
i = i + 5;
printf("Bola chosen, next arg is: %s\n", argv[i]);
printf("Weights: %f, %f, %f\n", this->qoe_w1, this->qoe_w2, this->qoe_w3);
continue;
}
if(!strcmp(argv[i], "-sbu"))
{
this->adaptLogic = LogicType::SparseBayesUcb;
this->isBuff = true;
this->alphaRate = atof(argv[i+1]);
this->bufferTargetSeconds = 0;
this->qoe_w1 = atof(argv[i+2]);
this->qoe_w2 = atof(argv[i+3]);
this->qoe_w3 = atof(argv[i+4]);
i = i + 5;
printf("Sparse Bayes UCB chosen, next arg is: %s\n", argv[i]);
printf("Weights: %f, %f, %f\n", this->qoe_w1, this->qoe_w2, this->qoe_w3);
continue;
}
if(!strcmp(argv[i], "-sbuose"))
{
this->adaptLogic = LogicType::SparseBayesUcbOse;
this->isBuff = true;
this->alphaRate = atof(argv[i+1]);
this->bufferTargetSeconds = 0;
this->qoe_w1 = atof(argv[i+2]);
this->qoe_w2 = atof(argv[i+3]);
this->qoe_w3 = atof(argv[i+4]);
i = i + 5;
printf("Sparse Bayes UCB OSE chosen, next arg is: %s\n", argv[i]);
printf("Weights: %f, %f, %f", this->qoe_w1, this->qoe_w2, this->qoe_w3);
continue;
}
if(!strcmp(argv[i], "-sbusvi"))
{
this->adaptLogic = LogicType::SparseBayesUcbSvi;
this->isBuff = true;
this->alphaRate = atof(argv[i+1]);
this->bufferTargetSeconds = 0;
this->qoe_w1 = atof(argv[i+2]);
this->qoe_w2 = atof(argv[i+3]);
this->qoe_w3 = atof(argv[i+4]);
i = i + 5;
printf("Sparse Bayes UCB SVI chosen, next arg is: %s\n", argv[i]);
printf("Weights: %f, %f, %f\n", this->qoe_w1, this->qoe_w2, this->qoe_w3);
continue;
}
if(!strcmp(argv[i], "-linucb"))
{
this->adaptLogic = LogicType::LinUcb;
this->isBuff = true;
this->alphaRate = atof(argv[i+1]);
this->bufferTargetSeconds = 0;
this->qoe_w1 = atof(argv[i+2]);
this->qoe_w2 = atof(argv[i+3]);
this->qoe_w3 = atof(argv[i+4]);
i = i + 5;
printf("LinUCB chosen, next arg is: %s\n", argv[i]);
printf("Weights: %f, %f, %f\n", this->qoe_w1, this->qoe_w2, this->qoe_w3);
continue;
}
if(!strcmp(argv[i], "-lowest"))
{
this->adaptLogic = LogicType::AlwaysLowest;
this->isBuff = false;
printf("Always lowest is chosen");
i++;
continue;
}
if(!strcmp(argv[i], "-bt"))
{
this->adaptLogic = LogicType::BufferBasedThreeThreshold;
this->isBuff = true;
this->alphaRate = atof(argv[i+1]);
this->reservoirThreshold = atoi(argv[i+2]);
this->maxThreshold = atoi(argv[i+3]);
i = i + 3;
continue;
}
if(!strcmp(argv[i], "-r"))
{
this->adaptLogic = LogicType::RateBased;
this->alphaRate = atof(argv[i+1]);
i = i + 2;
continue;
}
if(!strcmp(argv[i], "-p"))
{
this->adaptLogic = LogicType::Panda;
this->isBuff = true;
this->alphaRate = atof(argv[i+1]);
this->bufferTargetSeconds = 0;
this->qoe_w1 = atof(argv[i+2]);
this->qoe_w2 = atof(argv[i+3]);
this->qoe_w3 = atof(argv[i+4]);
i = i + 5;
printf("PANDA chosen, next arg is: %s\n", argv[i]);
printf("Weights: %f, %f, %f\n", this->qoe_w1, this->qoe_w2, this->qoe_w3);
continue;
}
if(!strcmp(argv[i], "-fb")) //new algo inserted here
{
this->adaptLogic = LogicType::FOOBAR;
this->isBuff = true;
this->alphaRate = atof(argv[i+1]);
this->bufferTargetSeconds = atof(argv[i+2]);
i = i + 2;
printf("FOOBAR chosen, next arg is: %s\n", argv[i]);
continue;
}
if(!strcmp(argv[i],"-a"))
{
int j =0;
for(j = 0; j < LogicType::Count; j++)
{
if(!strcmp(LogicType_string[j],argv[i+1]))
{
this->adaptLogic = (LogicType)j;
break;
}
}
if(j == LogicType::Count)
{
printf("the different adaptation logics implemented are:\n");
for(j = 0;j < LogicType::Count; j++)
{
printf("*%s\n",LogicType_string[j]);
}
printf("By default, the %s logic is selected.\n", LogicType_string[this->adaptLogic]);
}
i++;
i++;
continue;
}
i++;
}
}
}
void DASHPlayerNoGUI::helpMessage (char * name)
{
printf("Usage: %s -u url -a adaptationLogic -n\n" \
"-u:\tThe MPD's url\n" \
"-a:\tThe adaptationLogic:\n" \
"\t*AlwaysLowest\n" \
"\t*RateBased(default)\n" \
"\t*BufferBased\n" \
"-n:\tFlag to use NDN instead of TCP\n" \
"-nr alpha:\tFlag to use NDN instead of TCP\n" \
"-b reservoirThreshold maxThreshold (both in %)\n" \
"-br alpha reservoirThreshold maxThreshold \n" \
"-r alpha\n", name);
}
void DASHPlayerNoGUI::OnSettingsChanged (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation)
{
if(this->multimediaManager->GetMPD() == NULL)
return; // TODO dialog or symbol that indicates that error
if (!this->SettingsChanged(period, videoAdaptationSet, videoRepresentation, audioAdaptationSet, audioRepresentation))
return;
IPeriod *currentPeriod = this->multimediaManager->GetMPD()->GetPeriods().at(period);
std::vector<IAdaptationSet *> videoAdaptationSets = AdaptationSetHelper::GetVideoAdaptationSets(currentPeriod);
std::vector<IAdaptationSet *> audioAdaptationSets = AdaptationSetHelper::GetAudioAdaptationSets(currentPeriod);
if (videoAdaptationSet >= 0 && videoRepresentation >= 0 && !videoAdaptationSets.empty())
{
this->multimediaManager->SetVideoQuality(currentPeriod,
videoAdaptationSets.at(videoAdaptationSet),
videoAdaptationSets.at(videoAdaptationSet)->GetRepresentation().at(videoRepresentation));
}
else
{
this->multimediaManager->SetVideoQuality(currentPeriod, NULL, NULL);
}
if (audioAdaptationSet >= 0 && audioRepresentation >= 0 && !audioAdaptationSets.empty())
{
this->multimediaManager->SetAudioQuality(currentPeriod,
audioAdaptationSets.at(audioAdaptationSet),
audioAdaptationSets.at(audioAdaptationSet)->GetRepresentation().at(audioRepresentation));
}
else
{
this->multimediaManager->SetAudioQuality(currentPeriod, NULL, NULL);
}
}
void DASHPlayerNoGUI::OnEOS ()
{
this->OnStopButtonPressed();
}
bool DASHPlayerNoGUI::OnDownloadMPDPressed (const std::string &url)
{
if(this->isNDN)
{
if(!this->multimediaManager->InitNDN(url))
{
printf("Problem parsing the mpd. NDN is enabled.");
return false;
}
}
else
{
if(!this->multimediaManager->Init(url))
{
printf("Problem parsing the mpd. NDN is disabled.");
return false; // TODO dialog or symbol that indicates that error
}
}
return true;
}
bool DASHPlayerNoGUI::SettingsChanged (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation)
{
return true;
/* EnterCriticalSection(&this->monitorMutex);
bool settingsChanged = false;
if (this->currentSettings.videoRepresentation != videoRepresentation ||
this->currentSettings.audioRepresentation != audioRepresentation ||
this->currentSettings.videoAdaptationSet != videoAdaptationSet ||
this->currentSettings.audioAdaptationSet != audioAdaptationSet ||
this->currentSettings.period != period)
settingsChanged = true;
if (settingsChanged)
this->SetSettings(period, videoAdaptationSet, videoRepresentation, audioAdaptationSet, audioRepresentation);
LeaveCriticalSection(&this->monitorMutex);
return settingsChanged;
*/
}
void DASHPlayerNoGUI::SetSettings (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation)
{
this->currentSettings.period = period;
this->currentSettings.videoAdaptationSet = videoAdaptationSet;
this->currentSettings.videoRepresentation = videoRepresentation;
this->currentSettings.audioAdaptationSet = audioAdaptationSet;
this->currentSettings.audioRepresentation = audioRepresentation;
}
void DASHPlayerNoGUI::OnVideoBufferStateChanged (uint32_t fillstateInPercent)
{
}
void DASHPlayerNoGUI::OnVideoSegmentBufferStateChanged (uint32_t fillstateInPercent)
{
}
void DASHPlayerNoGUI::OnAudioBufferStateChanged (uint32_t fillstateInPercent)
{
}
void DASHPlayerNoGUI::OnAudioSegmentBufferStateChanged (uint32_t fillstateInPercent)
{
}
| 19,430 | 34.983333 | 492 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/UI/IDASHPlayerGuiObserver.h
|
/*
* IDASHPlayerGuiObserver.h
*****************************************************************************
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef IDASHPLAYERGUIOBSERVER_H_
#define IDASHPLAYERGUIOBSERVER_H_
#include <string>
#include <qobject.h>
#include "QtSamplePlayerGui.h"
namespace sampleplayer
{
class IDASHPlayerGuiObserver : public QObject
{
Q_OBJECT
public:
virtual ~IDASHPlayerGuiObserver() {}
virtual void OnSettingsChanged (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation) = 0;
virtual void OnStartButtonPressed (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation) = 0;
virtual void OnStopButtonPressed () = 0;
virtual bool OnDownloadMPDPressed (const std::string &url) = 0;
virtual void OnPauseButtonPressed () = 0;
virtual void OnFastForward () = 0;
virtual void OnFastRewind () = 0;
};
}
#endif /* IDASHPLAYERGUIOBSERVER_H_ */
| 1,687 | 44.621622 | 164 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/UI/DASHPlayer.h
|
/*
* DASHPlayer.h
*****************************************************************************
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef DASHPLAYER_H_
#define DASHPLAYER_H_
#include <iostream>
#include <sstream>
#include <qobject.h>
#include "libdash.h"
#include "IDASHPlayerGuiObserver.h"
#include "../Managers/IMultimediaManagerObserver.h"
#include "../Renderer/QTGLRenderer.h"
#include "../Renderer/QTAudioRenderer.h"
#include "../Managers/MultimediaManager.h"
#include "../libdashframework/Adaptation/AlwaysLowestLogic.h"
#include "../libdashframework/Adaptation/ManualAdaptation.h"
#include "../libdashframework/Buffer/IBufferObserver.h"
#include "../libdashframework/MPD/AdaptationSetHelper.h"
#include <qimage.h>
namespace sampleplayer
{
struct settings_t
{
int period;
int videoAdaptationSet;
int audioAdaptationSet;
int videoRepresentation;
int audioRepresentation;
};
class DASHPlayer : public IDASHPlayerGuiObserver, public managers::IMultimediaManagerObserver
{
Q_OBJECT
public:
DASHPlayer (QtSamplePlayerGui& gui, int argc, char ** argv);
virtual ~DASHPlayer ();
virtual void OnSettingsChanged (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation);
virtual void OnStartButtonPressed (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation);
virtual void OnStopButtonPressed ();
virtual void OnPauseButtonPressed ();
virtual void OnFastForward ();
virtual void OnFastRewind ();
/* IMultimediaManagerObserver */
virtual void OnVideoBufferStateChanged (uint32_t fillstateInPercent);
virtual void OnVideoSegmentBufferStateChanged (uint32_t fillstateInPercent);
virtual void OnAudioBufferStateChanged (uint32_t fillstateInPercent);
virtual void OnAudioSegmentBufferStateChanged (uint32_t fillstateInPercent);
virtual void OnEOS ();
virtual bool OnDownloadMPDPressed (const std::string &url);
private:
dash::mpd::IMPD *mpd;
sampleplayer::renderer::QTGLRenderer *videoElement;
sampleplayer::renderer::QTAudioRenderer *audioElement;
QtSamplePlayerGui *gui;
sampleplayer::managers::MultimediaManager *multimediaManager;
settings_t currentSettings;
CRITICAL_SECTION monitorMutex;
const char *url;
bool isNDN;
libdash::framework::adaptation::LogicType adaptLogic;
bool SettingsChanged (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation);
void SetSettings (int period, int videoAdaptationSet, int videoRepresentation, int audioAdaptationSet, int audioRepresentation);
void parseArgs (int argc, char** argv);
signals:
void VideoSegmentBufferFillStateChanged (int fillStateInPercent);
void VideoBufferFillStateChanged (int fillStateInPercent);
void AudioSegmentBufferFillStateChanged (int fillStateInPercent);
void AudioBufferFillStateChanged (int fillStateInPercent);
};
}
#endif /* DASHPLAYER_H_ */
| 3,894 | 41.336957 | 159 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/UI/FullScreenDialog.h
|
/*
* FullScreenDialog.h
*
* Created on: Oct 11, 2016
* Author: ndnops
*/
#ifndef QTSAMPLEPLAYER_UI_FULLSCREENDIALOG_H_
#define QTSAMPLEPLAYER_UI_FULLSCREENDIALOG_H_
//USELESS FILE
#include <QDialog>
#include <QtMultimedia/qmediaplayer.h>
#include <QtGui/QMovie>
#include <QtWidgets/QMainWindow>
#include "QtSamplePlayerGui.h"
namespace sampleplayer
{
// class QtSamplePlayerGui;
// void QtSamplePlayerGui::keyPressEvent(QKeyEvent*);
class FullScreenDialog : public QDialog {
public:
FullScreenDialog(QtSamplePlayerGui *gui);
~FullScreenDialog();
void keyPressEvent (QKeyEvent* event);
private:
QtSamplePlayerGui *gui;
};
}
#endif /* QTSAMPLEPLAYER_UI_FULLSCREENDIALOG_H_ */
| 709 | 19.285714 | 53 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Portable/MultiThreading.cpp
|
#include "MultiThreading.h"
THREAD_HANDLE CreateThreadPortable (void *(*start_routine) (void *), void *arg)
{
#if defined _WIN32 || defined _WIN64
return CreateThread (0, 0, (LPTHREAD_START_ROUTINE)start_routine, (LPVOID)arg, 0, 0);
#else
THREAD_HANDLE th = (THREAD_HANDLE)malloc(sizeof(pthread_t));
if (!th)
{
std::cerr << "Error allocating thread." << std::endl;
return NULL;
}
if(int err = pthread_create(th, NULL, start_routine, arg))
{
std::cerr << strerror(err) << std::endl;
return NULL;
}
return th;
#endif
}
void DestroyThreadPortable (THREAD_HANDLE th)
{
#if !defined _WIN32 && !defined _WIN64
if(th)
free(th);
#else
CloseHandle(th);
#endif
}
/****************************************************************************
* Condition variables for Windows XP and older windows sytems
*****************************************************************************/
#if defined WINXPOROLDER
void InitCondition (condition_variable_t *cv)
{
InitializeCriticalSection(&cv->waitersCountLock);
cv->waitersCount = 0;
cv->waitGenerationCount = 0;
cv->releaseCount = 0;
cv->waitingEvent = CreateEvent (NULL, // no security
TRUE, // manual-reset
FALSE, // non-signaled initially
NULL); // unnamed
}
void WaitCondition (condition_variable_t *cv, CRITICAL_SECTION *externalMutex)
{
EnterCriticalSection(&cv->waitersCountLock);
cv->waitersCount++;
int currentGenerationCount = cv->waitGenerationCount;
LeaveCriticalSection(&cv->waitersCountLock);
LeaveCriticalSection(externalMutex);
bool isWaitDone = false;
while(!isWaitDone)
{
WaitForSingleObject (cv->waitingEvent, INFINITE);
EnterCriticalSection (&cv->waitersCountLock);
isWaitDone = (cv->releaseCount > 0 && cv->waitGenerationCount != currentGenerationCount);
LeaveCriticalSection (&cv->waitersCountLock);
}
EnterCriticalSection(externalMutex);
EnterCriticalSection(&cv->waitersCountLock);
cv->waitersCount--;
cv->releaseCount--;
bool isLastWaiter = (cv->releaseCount == 0);
LeaveCriticalSection(&cv->waitersCountLock);
if(isLastWaiter)
ResetEvent(cv->waitingEvent);
}
void SignalCondition (condition_variable_t *cv)
{
EnterCriticalSection(&cv->waitersCountLock);
if(cv->waitersCount > cv->releaseCount)
{
SetEvent(cv->waitingEvent);
cv->releaseCount++;
cv->waitGenerationCount++;
}
LeaveCriticalSection(&cv->waitersCountLock);
}
void BroadcastCondition (condition_variable_t *cv)
{
EnterCriticalSection(&cv->waitersCountLock);
if(cv->waitersCount > 0)
{
SetEvent(cv->waitingEvent);
cv->releaseCount = cv->waitersCount;
cv->waitGenerationCount++;
}
LeaveCriticalSection(&cv->waitersCountLock);
}
#endif
| 3,344 | 29.409091 | 101 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Portable/MultiThreading.h
|
/*
* MultiThreading.h
*****************************************************************************
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_PORTABLE_MULTITHREADING_H_
#define LIBDASH_FRAMEWORK_PORTABLE_MULTITHREADING_H_
#if defined _WIN32 || defined _WIN64
#define _WINSOCKAPI_
#include <Windows.h>
#define DeleteConditionVariable(cond_p) {}
// void sleep_for(const chrono::duration<Rep, Period>& rel_time);
#define PortableSleep(seconds) Sleep(seconds * 1000)
#define JoinThread(handle) WaitForSingleObject(handle, INFINITE)
typedef HANDLE THREAD_HANDLE;
#if defined WINXPOROLDER
/****************************************************************************
* Variables
*****************************************************************************/
struct condition_variable_t
{
int waitersCount; // Count of the number of waiters.
CRITICAL_SECTION waitersCountLock; // Serialize access to <waitersCount>.
int releaseCount; // Number of threads to release via a <BroadcastCondition> or a <SignalCondition>.
int waitGenerationCount; // Keeps track of the current "generation" so that we don't allow one thread to steal all the "releases" from the broadcast.
HANDLE waitingEvent; // A manual-reset event that's used to block and release waiting threads.
};
/****************************************************************************
* Prototypes
*****************************************************************************/
void InitCondition (condition_variable_t *cv);
void WaitCondition (condition_variable_t *cv, CRITICAL_SECTION *externalMutex);
void SignalCondition (condition_variable_t *cv);
void BroadcastCondition (condition_variable_t *cv);
/****************************************************************************
* Defines
*****************************************************************************/
#define CONDITION_VARIABLE condition_variable_t
#define InitializeConditionVariable(cond_p) InitCondition(cond_p)
#define SleepConditionVariableCS(cond_p, mutex_p, infinite) WaitCondition(cond_p, mutex_p) // INFINITE should be handled mor properly
#define WakeConditionVariable(cond_p) SignalCondition(cond_p)
#define WakeAllConditionVariable(cond_p) BroadcastCondition(cond_p)
#endif
#else
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <stdlib.h>
#include <iostream>
#include <unistd.h>
#define CRITICAL_SECTION pthread_mutex_t
#define CONDITION_VARIABLE pthread_cond_t
#define PortableSleep(seconds) usleep(seconds * 1000000)
#define JoinThread(handle) pthread_join(*(handle), NULL)
#define InitializeCriticalSection(mutex_p) pthread_mutex_init(mutex_p, NULL)
#define DeleteCriticalSection(mutex_p) pthread_mutex_destroy(mutex_p)
#define EnterCriticalSection(mutex_p) pthread_mutex_lock(mutex_p)
#define LeaveCriticalSection(mutex_p) pthread_mutex_unlock(mutex_p)
#define InitializeConditionVariable(cond_p) pthread_cond_init(cond_p, NULL)
#define DeleteConditionVariable(cond_p) pthread_cond_destroy(cond_p)
#define SleepConditionVariableCS(cond_p, mutex_p, infinite) pthread_cond_wait(cond_p, mutex_p) // INFINITE should be handled mor properly
#define WakeConditionVariable(cond_p) pthread_cond_signal(cond_p)
#define WakeAllConditionVariable(cond_p) pthread_cond_broadcast(cond_p)
typedef pthread_t* THREAD_HANDLE;
#endif
THREAD_HANDLE CreateThreadPortable (void *(*start_routine) (void *), void *arg);
void DestroyThreadPortable (THREAD_HANDLE th);
#endif // LIBDASH_FRAMEWORK_PORTABLE_MULTITHREADING_H_
| 4,562 | 51.448276 | 180 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/helpers/TimingObject.cpp
|
/*
* TimingObject.cpp
*****************************************************************************
* Copyright (C) 2013, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "TimingObject.h"
using namespace libdash::framework::helpers;
TimingObject::TimingObject (std::string desc) :
description (desc)
{
this->timeStamp = Timing::GetCurrentUTCTimeInMsec();
}
TimingObject::~TimingObject ()
{
}
clock_t TimingObject::TimeStamp ()
{
return this->timeStamp;
}
std::string TimingObject::Description ()
{
return this->description;
}
| 841 | 24.515152 | 79 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/helpers/Timing.cpp
|
/*
* Timing.cpp
*****************************************************************************
* Copyright (C) 2013, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "Timing.h"
using namespace libdash::framework::helpers;
#define NUMBER_WIDTH 4
#define TEXT_WIDTH 22
std::vector<void *> Timing::timingsInBetween;
clock_t Timing::GetCurrentUTCTimeInMsec ()
{
return clock();
}
float Timing::GetDifference (clock_t before, clock_t after)
{
return (float) (after - before) / CLOCKS_PER_SEC;
}
void Timing::AddTiming (void *timing)
{
Timing::timingsInBetween.push_back(timing);
}
std::string Timing::TimingsInBetweenList ()
{
std::stringstream ss;
for (size_t i = 1; i < Timing::timingsInBetween.size(); i++)
{
ss << std::setfill('0') << std::setw(NUMBER_WIDTH) << i << " "
<< std::setfill(' ') << std::setw(TEXT_WIDTH) << ((TimingObject *)Timing::timingsInBetween.at(i-1))->Description() << " --- "
<< std::setfill(' ') << std::setw(TEXT_WIDTH) << ((TimingObject *)Timing::timingsInBetween.at(i))->Description() << ": "
<< Timing::GetDifference(((TimingObject *)Timing::timingsInBetween.at(i-1))->TimeStamp(), ((TimingObject *)Timing::timingsInBetween.at(i))->TimeStamp())
<< std::endl;
}
return ss.str();
}
std::string Timing::TimingsList ()
{
std::stringstream ss;
for (size_t i = 0; i < Timing::timingsInBetween.size(); i++)
{
ss << std::setfill('0') << std::setw(NUMBER_WIDTH) << i + 1 << " "
<< std::setfill(' ') << std::setw(TEXT_WIDTH) << ((TimingObject *) Timing::timingsInBetween.at(i))->Description() << ": "
<< ((TimingObject *) Timing::timingsInBetween.at(i))->TimeStamp() << std::endl;
}
return ss.str();
}
void Timing::WriteToFile (std::string filename)
{
std::ofstream myfile;
myfile.open (filename);
myfile << "Intervals:" << std::endl << Timing::TimingsInBetweenList() << std::endl;
myfile << "Timestamp list: " << std::endl << Timing::TimingsList() << std::endl;
myfile.close();
}
void Timing::DisposeTimingObjects ()
{
size_t numObj = Timing::timingsInBetween.size();
for (size_t i = 0; i < numObj; i++)
{
TimingObject *timing = (TimingObject *) Timing::timingsInBetween.at(i);
delete timing;
}
}
| 2,702 | 33.21519 | 164 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/helpers/TimingObject.h
|
/*
* TimingObject.h
*****************************************************************************
* Copyright (C) 2013, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_HELPERS_TIMINGOBJECT_H_
#define LIBDASH_FRAMEWORK_HELPERS_TIMINGOBJECT_H_
#include "config.h"
#include <time.h>
#include "Timing.h"
namespace libdash
{
namespace framework
{
namespace helpers
{
class TimingObject
{
public:
TimingObject (std::string desc);
virtual ~TimingObject ();
clock_t TimeStamp ();
std::string Description ();
private:
clock_t timeStamp;
std::string description;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_HELPERS_TIMINGOBJECT_H_ */
| 1,162 | 24.844444 | 79 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/helpers/Timing.h
|
/*
* Timing.h
*****************************************************************************
* Copyright (C) 2013, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_HELPERS_TIMING_H_
#define LIBDASH_FRAMEWORK_HELPERS_TIMING_H_
#include <time.h>
#include "config.h"
#include "TimingObject.h"
#include <iomanip>
#include <fstream>
namespace libdash
{
namespace framework
{
namespace helpers
{
class Timing
{
public:
static void AddTiming (void *timing);
static clock_t GetCurrentUTCTimeInMsec ();
static void WriteToFile (std::string filename);
static void DisposeTimingObjects ();
private:
static float GetDifference (clock_t before, clock_t after);
static std::string TimingsInBetweenList ();
static std::string TimingsList ();
static std::vector<void *> timingsInBetween;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_HELPERS_TIMING_H_ */
| 1,511 | 29.857143 | 100 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/RateBasedAdaptation.h
|
/*
* RateBasedAdaptation.h
*****************************************************************************
* Copyright (C) 2016,
* Jacques Samain <[email protected]>
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_RATEBASEDADAPTATION_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_RATEBASEDADAPTATION_H_
#include "AbstractAdaptationLogic.h"
#include "../MPD/AdaptationSetStream.h"
#include "../Input/IDASHReceiverObserver.h"
namespace libdash
{
namespace framework
{
namespace adaptation
{
class RateBasedAdaptation : public AbstractAdaptationLogic
{
public:
RateBasedAdaptation (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, bool isVid, double arg1);
virtual ~RateBasedAdaptation ();
virtual LogicType GetType ();
virtual bool IsUserDependent ();
virtual bool IsRateBased ();
virtual bool IsBufferBased ();
virtual void BitrateUpdate (uint64_t bps);
virtual void SegmentPositionUpdate(uint32_t qualitybps);
virtual void DLTimeUpdate (double time);
virtual void BufferUpdate (uint32_t bufferfill);
void SetBitrate (uint64_t bps);
uint64_t GetBitrate ();
virtual void SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager);
void NotifyBitrateChange ();
void OnEOS (bool value);
virtual void OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec);
void ewma (uint64_t bps);
void CheckedByDASHReceiver();
private:
uint64_t currentBitrate;
std::vector<uint64_t> availableBitrates;
sampleplayer::managers::IMultimediaManagerBase *multimediaManager;
dash::mpd::IRepresentation *representation;
double alpha;
uint64_t averageBw;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_RATEBASEDADAPTATION_H_ */
| 2,699 | 45.551724 | 174 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/SparseBayesUcbSvi.cpp
|
/*
* SparseBayesUcbSvi.cpp
* By Trevor Ballard and Bastian Alt, <[email protected]>, <[email protected]>
*
* Adapted from code by Michele Tortelli and Jacques Samain, whose copyright is
* reproduced below.
*
*****************************************************************************
* Copyright (C) 2016
* Michele Tortelli and Jacques Samain, <[email protected]>, <[email protected]>
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "SparseBayesUcbSvi.h"
#include <stdio.h>
#include <math.h>
#include <chrono>
#include <string>
#include <stdint.h>
#include <iostream>
#include <sstream>
#include <chrono>
#include <inttypes.h>
#include <stdlib.h>
#include <stdarg.h>
#include <algorithm>
#include <inttypes.h>
#include <time.h>
#include <limits.h>
#include <errno.h>
#include <Python.h>
#include <chrono>
#include <thread>
const double MINIMUM_BUFFER_LEVEL_SPACING = 5.0; // The minimum space required between buffer levels (in seconds).
const uint32_t THROUGHPUT_SAMPLES = 3; // Number of samples considered for throughput estimate.
const double SAFETY_FACTOR = 0.9; // Safety factor used with bandwidth estimate.
static PyObject *pName, *pModule, *pDict, *pFuncChoose, *pFuncUpdate;
static int gil_init = 0;
using namespace dash::mpd;
using namespace libdash::framework::adaptation;
using namespace libdash::framework::input;
using namespace libdash::framework::mpd;
using std::bind;
using std::placeholders::_1;
using std::placeholders::_2;
using duration_in_seconds = std::chrono::duration<double, std::ratio<1, 1> >;
SparseBayesUcbSviAdaptation::SparseBayesUcbSviAdaptation (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6) : AbstractAdaptationLogic (mpd, period, adaptationSet, isVid)
{
// Set SparseBayesUcbSvi init STATE
this->initState = true;
this->sparseBayesUcbSviState = STARTUP;
this->lastDownloadTimeInstant = 0.0;
this->currentDownloadTimeInstant = 0.0;
//this->lastSegmentDownloadTime = 0.0;
this->currentQuality = 0;
this->cumQoE = 0.0;
this->bufferMaxSizeSeconds = 20.0; // It is 'bufferMax' in dash.js implementation
// Find a way to retrieve the value without hard coding it
// Set QoE weights
this->qoe_w1 = arg4;
this->qoe_w2 = arg5;
this->qoe_w3 = arg6;
// Set alpha for the EWMA (bw estimate)
this->alphaRate = 0.8;
this->bufferTargetSeconds = 12.0; // 12s (dash.js implementation) corresponds to 40% with a buffer of 30s
/// Retrieve available bitrates
std::vector<IRepresentation* > representations = this->adaptationSet->GetRepresentation();
this->availableBitrates.clear();
//L("SPARSEBAYESUCBSVI Available Bitrates...\n");
for(size_t i = 0; i < representations.size(); i++)
{
this->availableBitrates.push_back((uint64_t)(representations.at(i)->GetBandwidth()));
//L("%d - %I64u bps\n", i+1, this->availableBitrates[i]);
}
// Check if they are in increasing order (i.e., bitrate[0] <= bitrate[1], etc.)
this->bitrateCount = this->availableBitrates.size();
// We check if we have only one birate value or if the bitrate list is irregular (i.e., it is not strictly increasing)
if (this->bitrateCount < 2 || this->availableBitrates[0] >= this->availableBitrates[1] || this->availableBitrates[this->bitrateCount - 2] >= this->availableBitrates[this->bitrateCount - 1]) {
this->sparseBayesUcbSviState = ONE_BITRATE;
// return 0; // Check if exit with a message is necessary
}
// Check if the following is correct
this->totalDuration = TimeResolver::GetDurationInSec(this->mpd->GetMediaPresentationDuration());
//this->segmentDuration = (double) (representations.at(0)->GetSegmentTemplate()->GetDuration() / representations.at(0)->GetSegmentTemplate()->GetTimescale() );
this->segmentDuration = 2.0;
//L("Total Duration - SPARSEBAYESUCBSVI:\t%f\nSegment Duration - SPARSEBAYESUCBSVI:\t%f\n",this->totalDuration, this->segmentDuration);
// if not correct --> segmentDuration = 2.0;
// Compute the SPARSEBAYESUCBSVI Buffer Target
this->sparseBayesUcbSviBufferTargetSeconds = this->bufferTargetSeconds;
if (this->sparseBayesUcbSviBufferTargetSeconds < this->segmentDuration + MINIMUM_BUFFER_LEVEL_SPACING)
{
this->sparseBayesUcbSviBufferTargetSeconds = this->segmentDuration + MINIMUM_BUFFER_LEVEL_SPACING;
}
//L("SPARSEBAYESUCBSVI Buffer Target Seconds:\t%f\n",this->sparseBayesUcbSviBufferTargetSeconds);
// Compute UTILTY vector, Vp, and gp
//L("SPARSEBAYESUCBSVI Utility Values...\n");
double utility_tmp;
for (uint32_t i = 0; i < this->bitrateCount; ++i) {
utility_tmp = log(((double)this->availableBitrates[i] * (1./(double)this->availableBitrates[0])));
if(utility_tmp < 0)
utility_tmp = 0;
this->utilityVector.push_back( log(((double)this->availableBitrates[i] * (1./(double)this->availableBitrates[0]))));
//L("%d - %f\n", i+1, this->utilityVector[i]);
}
this->Vp = (this->sparseBayesUcbSviBufferTargetSeconds - this->segmentDuration) / this->utilityVector[this->bitrateCount - 1];
this->gp = 1.0 + this->utilityVector[this->bitrateCount - 1] / (this->sparseBayesUcbSviBufferTargetSeconds / this->segmentDuration - 1.0);
//L("SPARSEBAYESUCBSVI Parameters:\tVp: %f\tgp: %f\n",this->Vp, this->gp);
/* If bufferTargetSeconds (not sparseBayesUcbSviBufferTargetSecond) is large enough, we might guarantee that SparseBayesUcbSvi will never rebuffer
* unless the network bandwidth drops below the lowest encoded bitrate level. For this to work, SparseBayesUcbSvi needs to use the real buffer
* level without the additional virtualBuffer. Also, for this to work efficiently, we need to make sure that if the buffer level
* drops to one fragment during a download, the current download does not have more bits remaining than the size of one fragment
* at the lowest quality*/
this->maxRtt = 0.2; // Is this reasonable?
if(this->sparseBayesUcbSviBufferTargetSeconds == this->bufferTargetSeconds) {
this->safetyGuarantee = true;
}
if (this->safetyGuarantee) {
//L("SPARSEBAYESUCBSVI SafetyGuarantee...\n");
// we might need to adjust Vp and gp
double VpNew = this->Vp;
double gpNew = this->gp;
for (uint32_t i = 1; i < this->bitrateCount; ++i) {
double threshold = VpNew * (gpNew - this->availableBitrates[0] * this->utilityVector[i] / (this->availableBitrates[i] - this->availableBitrates[0]));
double minThreshold = this->segmentDuration * (2.0 - this->availableBitrates[0] / this->availableBitrates[i]) + maxRtt;
if (minThreshold >= this->bufferTargetSeconds) {
safetyGuarantee = false;
break;
}
if (threshold < minThreshold) {
VpNew = VpNew * (this->bufferTargetSeconds - minThreshold) / (this->bufferTargetSeconds - threshold);
gpNew = minThreshold / VpNew + this->utilityVector[i] * this->availableBitrates[0] / (this->availableBitrates[i] - this->availableBitrates[0]);
}
}
if (safetyGuarantee && (this->bufferTargetSeconds - this->segmentDuration) * VpNew / this->Vp < MINIMUM_BUFFER_LEVEL_SPACING) {
safetyGuarantee = false;
}
if (safetyGuarantee) {
this->Vp = VpNew;
this->gp = gpNew;
}
}
//L("SPARSEBAYESUCBSVI New Parameters:\tVp: %f\tgp: %f\n",this->Vp, this->gp);
// Capping of the virtual buffer (when using it)
this->sparseBayesUcbSviBufferMaxSeconds = this->Vp * (this->utilityVector[this->bitrateCount - 1] + this->gp);
//L("SPARSEBAYESUCBSVI Max Buffer Seconds:\t%f\n",this->sparseBayesUcbSviBufferMaxSeconds);
this->virtualBuffer = 0.0; // Check if we should use either the virtualBuffer or the safetyGuarantee
this->instantBw = 0;
this->averageBw = 0;
this->batchBw = 0; // Computed every THROUGHPUT_SAMPLES samples (average)
this->batchBwCount = 0;
this->multimediaManager = NULL;
this->lastBufferFill = 0; // (?)
this->bufferEOS = false;
this->shouldAbort = false;
this->isCheckedForReceiver = false;
this->representation = representations.at(0);
this->currentBitrate = (uint64_t) this->representation->GetBandwidth();
this->rebufferStart = 0;
this->rebufferEnd = 0;
Py_Initialize();
PyRun_SimpleString("import sys; sys.path.append('/'); import run_bandits");
pName = PyUnicode_FromString("run_bandits");
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFuncChoose = PyDict_GetItemString(pDict, "choose");
pFuncUpdate = PyDict_GetItemString(pDict, "update");
//L("SPARSEBAYESUCBSVI Init Params - \tAlpha: %f \t BufferTarget: %f\n",this->alphaRate, this->bufferTargetSeconds);
//L("SPARSEBAYESUCBSVI Init Current BitRate - %I64u\n",this->currentBitrate);
Debug("Buffer Adaptation SPARSEBAYESUCBSVI: STARTED\n");
}
SparseBayesUcbSviAdaptation::~SparseBayesUcbSviAdaptation ()
{
Py_DECREF(pModule);
Py_DECREF(pName);
Py_Finalize();
}
LogicType SparseBayesUcbSviAdaptation::GetType ()
{
return adaptation::BufferBased;
}
bool SparseBayesUcbSviAdaptation::IsUserDependent ()
{
return false;
}
bool SparseBayesUcbSviAdaptation::IsRateBased ()
{
return true;
}
bool SparseBayesUcbSviAdaptation::IsBufferBased ()
{
return true;
}
void SparseBayesUcbSviAdaptation::SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager)
{
this->multimediaManager = _mmManager;
}
void SparseBayesUcbSviAdaptation::NotifyBitrateChange ()
{
if(this->multimediaManager)
if(this->multimediaManager->IsStarted() && !this->multimediaManager->IsStopping())
if(this->isVideo)
this->multimediaManager->SetVideoQuality(this->period, this->adaptationSet, this->representation);
else
this->multimediaManager->SetAudioQuality(this->period, this->adaptationSet, this->representation);
//Should Abort is done here to avoid race condition with DASHReceiver::DoBuffering()
if(this->shouldAbort)
{
//L("Aborting! To avoid race condition.");
//printf("Sending Abort request\n");
this->multimediaManager->ShouldAbort(this->isVideo);
//printf("Received Abort request\n");
}
this->shouldAbort = false;
}
uint64_t SparseBayesUcbSviAdaptation::GetBitrate ()
{
return this->currentBitrate;
}
int SparseBayesUcbSviAdaptation::getQualityFromThroughput(uint64_t bps) {
int q = 0;
for (int i = 0; i < this->availableBitrates.size(); ++i) {
if (this->availableBitrates[i] > bps) {
break;
}
q = i;
}
return q;
}
int SparseBayesUcbSviAdaptation::getQualityFromBufferLevel(double bufferLevelSec) {
int quality = this->bitrateCount - 1;
double score = 0.0;
for (int i = 0; i < this->bitrateCount; ++i) {
double s = (this->utilityVector[i] + this->gp - bufferLevelSec / this->Vp) / this->availableBitrates[i];
if (s > score) {
score = s;
quality = i;
}
}
return quality;
}
void SparseBayesUcbSviAdaptation::SetBitrate (uint32_t bufferFill)
{
int result = 0;
PyObject *pArgs, *pValue;
std::vector<IRepresentation*> representations = this->adaptationSet->GetRepresentation();
int numArms = (int)representations.size();
pValue = PyList_New(0);
for (int i=0; i<numArms; i++) {
PyObject* pTemp = PyList_New(0);
// for bufferFill
PyList_Append(pTemp, PyFloat_FromDouble((double)bufferFill/(double)100));
// for RTT
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> rttVec = this->rttMap[i];
for (int j=0; j<rttVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)rttVec[j]));
}
// for num hops
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> numHopsVec = this->numHopsMap[i];
for (int j=0; j<numHopsVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)numHopsVec[j]));
}
PyList_Append(pValue, pTemp);
Py_XDECREF(pTemp);
}
pArgs = PyTuple_New(2);
PyTuple_SetItem(pArgs, 0, PyUnicode_FromString("sbusvi"));
PyTuple_SetItem(pArgs, 1, pValue);
if (!gil_init) {
gil_init = 1;
PyEval_InitThreads();
PyEval_SaveThread();
}
// 2: Execute
PyGILState_STATE state = PyGILState_Ensure();
unsigned long long int execStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
pValue = PyObject_CallObject(pFuncChoose, pArgs);
unsigned long long int execEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
result = (int)PyLong_AsLong(pValue);
Py_XDECREF(pArgs);
Py_XDECREF(pValue);
PyGILState_Release(state);
int duration = (int)(execEnd - execStart);
std::cout << "stat-begin" << std::endl;
std::cout << "stat-chexecms " << duration << std::endl;
std::cout << "stat-chqual " << result << std::endl;
if (result < 0 || result > numArms-1) {
std::cout << "ERROR: Result was out of bounds. Using quality of 2." << std::endl;
result = 2;
}
this->currentQuality = result;
this->representation = this->adaptationSet->GetRepresentation().at(this->currentQuality);
this->currentBitrate = (uint64_t) this->availableBitrates[this->currentQuality];
//L("STEADY - Current Bitrate:\t%I64u\n", this->currentBitrate);
//L("ADAPTATION_LOGIC:\tFor %s:\tlast_buffer: %f\tbuffer_level: %f, instantaneousBw: %lu, AverageBW: %lu, choice: %d\n",isVideo ? "video" : "audio",(double)lastBufferFill/100 , (double)bufferFill/100, this->instantBw, this->averageBw , this->currentQuality);
this->lastBufferFill = bufferFill;
}
void SparseBayesUcbSviAdaptation::BitrateUpdate(uint64_t bps)
{
}
void SparseBayesUcbSviAdaptation::SegmentPositionUpdate (uint32_t qualitybps)
{
//L("Called SegmentPositionUpdate\n");
}
void SparseBayesUcbSviAdaptation::DLTimeUpdate (double time)
{
auto m_now = std::chrono::system_clock::now();
auto m_now_sec = std::chrono::time_point_cast<std::chrono::seconds>(m_now);
auto now_value = m_now_sec.time_since_epoch();
double dl_instant = now_value.count();
//this->lastSegmentDownloadTime = time;
//this->currentDownloadTimeInstant = std::chrono::duration_cast<duration_in_seconds>(system_clock::now()).count();
this->currentDownloadTimeInstant = dl_instant;
}
void SparseBayesUcbSviAdaptation::OnEOS (bool value)
{
this->bufferEOS = value;
}
void SparseBayesUcbSviAdaptation::OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec)
{
std::vector<IRepresentation*> representations = this->adaptationSet->GetRepresentation();
int numArms = (int)representations.size();
uint32_t bufferFill = (uint32_t)(bufferFillPct * (double)100);
std::cout << "stat-qual " << quality << std::endl;
//L("stat-buffpct %f\n", bufferFillPct);
////////////////
// Update MAB //
////////////////
// First calculate the real QoE for the segment:
// 1. Base quality (kbps)
// 2. Decline in quality (kbps)
// 3. Time spent rebuffering (ms)
// 1. Base quality
int baseQuality = (int)(this->availableBitrates[quality] / (uint64_t)1000);
std::cout << "stat-qoebase " << baseQuality << std::endl;
// 2. Decline in quality
this->qualityHistory[segNum] = quality;
int qualityDecline = 0;
if (this->qualityHistory[segNum] < this->qualityHistory[segNum-1]) {
int prevQuality = (int)(this->availableBitrates[this->qualityHistory[segNum-1]]/(uint64_t)1000);
int currQuality = (int)(this->availableBitrates[quality]/(uint64_t)1000);
qualityDecline = prevQuality - currQuality;
}
std::cout << "stat-qoedecl " << qualityDecline << std::endl;
// 3. Time spent rebuffering
// We just got a new segment so rebuffering has stopped
// If it occurred, we need to know for how long
int rebufferTime = 0;
if (this->rebufferStart != 0) {
if (this->rebufferEnd == 0) {
this->rebufferEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
}
rebufferTime = (int)(this->rebufferEnd - this->rebufferStart);
this->rebufferStart = 0;
}
std::cout << "stat-qoerebuffms " << rebufferTime << std::endl;
// Put it all together for the reward
// The weight of 3 comes from the SIGCOMM paper; they use 3000 because their
// rebufferTime is in seconds, but ours is milliseconds
double reward = (this->qoe_w1*(double)baseQuality) - (this->qoe_w2*(double)qualityDecline) - (this->qoe_w3*(double)rebufferTime*(double)rebufferTime);
this->cumQoE += reward;
std::cout << "stat-qoeseg " << reward << std::endl;
std::cout << "stat-qoecum " << this->cumQoE << std::endl;
// If we're still in the first K iterations, we have to try all arms. Try the one
// corresponding to this segment
// TODO would be better to put in SetBitrate, but that'd take a bit of refactoring
/*
if (segNum < numArms) {
//L("stat-initarms %d\n", segNum);
this->currentQuality = segNum;
this->representation = this->adaptationSet->GetRepresentation().at(this->currentQuality);
this->currentBitrate = (uint64_t) this->availableBitrates[this->currentQuality];
this->lastBufferFill = bufferFill;
//L("STEADY - Current Bitrate:\t%I64u\n", this->currentBitrate);
this->qualityHistory[segNum] = quality;
this->rttMap[quality] = rttVec;
this->ecnMap[quality] = ecnVec;
this->numHopsMap[quality] = numHopsVec;
this->NotifyBitrateChange();
}
else {
*/
// 1: Build args
int result = 0;
PyObject *pArgs, *pValue;
pValue = PyList_New(0);
for (int i=0; i<numArms; i++) {
PyObject* pTemp = PyList_New(0);
PyList_Append(pTemp, PyFloat_FromDouble(bufferFillPct));
// for RTT
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> tempRttVec = this->rttMap[i];
for (int j=0; j<tempRttVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)tempRttVec[j]));
}
/*
// for ECN
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> tempEcnVec = this->ecnMap[i];
for (int j=0; j<tempEcnVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)tempEcnVec[j]));
}
*/
// for num hops
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> tempNumHopsVec = this->numHopsMap[i];
for (int j=0; j<tempNumHopsVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)tempNumHopsVec[j]));
}
PyList_Append(pValue, pTemp);
Py_XDECREF(pTemp);
}
pArgs = PyTuple_New(5);
PyTuple_SetItem(pArgs, 0, PyUnicode_FromString("sbusvi"));
// context
PyTuple_SetItem(pArgs, 1, pValue);
// last quality (action)
PyTuple_SetItem(pArgs, 2, PyLong_FromLong((long)quality));
// reward
PyTuple_SetItem(pArgs, 3, PyFloat_FromDouble(reward));
// timestep
PyTuple_SetItem(pArgs, 4, PyLong_FromLong((long)segNum));
if (!gil_init) {
std::cout << "WARNING: setting gil_init in BitrateUpdate" << std::endl;
gil_init = 1;
PyEval_InitThreads();
PyEval_SaveThread();
}
// 2: Execute
PyGILState_STATE state = PyGILState_Ensure();
unsigned long long int execStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
pValue = PyObject_CallObject(pFuncUpdate, pArgs);
unsigned long long int execEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
result = (int)PyLong_AsLong(pValue);
Py_XDECREF(pArgs);
Py_XDECREF(pValue);
PyGILState_Release(state);
int duration = (int)(execEnd - execStart);
std::cout << "stat-updexecms " << duration << std::endl;
if (result != 1) {
std::cout << "WARNING: Update MAB failed" << std::endl;
}
/////////////////////////////
// Update internal context //
/////////////////////////////
this->rttMap[quality] = rttVec;
//this->ecnMap[quality] = ecnVec;
this->numHopsMap[quality] = numHopsVec;
// Run MAB using the new context
this->SetBitrate(bufferFill);
this->NotifyBitrateChange();
//} <--- the commented out else statement
}
void SparseBayesUcbSviAdaptation::CheckedByDASHReceiver ()
{
//L("CheckedByDASHReceiver called\n");
this->isCheckedForReceiver = false;
}
void SparseBayesUcbSviAdaptation::BufferUpdate (uint32_t bufferFill)
{
if (bufferFill == (uint32_t)0 && this->rebufferStart == 0) {
this->rebufferStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
this->rebufferEnd = 0;
//L("Buffer is at 0; rebuffering has begun and playback has stalled\n");
}
else if (this->rebufferEnd == 0 && this->rebufferStart != 0) {
this->rebufferEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
//L("Stopped rebuffering; resuming playback\n");
}
}
| 22,245 | 39.010791 | 268 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/FOOBAR.h
|
/*
* FOOBAR.h
*
* Created on: Oct 17, 2016
* Author: ndnops
*/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_FOOBAR_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_FOOBAR_H_
#include "AbstractAdaptationLogic.h"
#include "../MPD/AdaptationSetStream.h"
#include "../Input/IDASHReceiverObserver.h"
namespace libdash
{
namespace framework
{
namespace adaptation
{
class FOOBARAdaptation : public AbstractAdaptationLogic
{
public:
FOOBARAdaptation(dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6);
virtual ~FOOBARAdaptation();
virtual LogicType GetType ();
virtual bool IsUserDependent ();
virtual bool IsRateBased ();
virtual bool IsBufferBased ();
virtual void BitrateUpdate (uint64_t bps);
virtual void SegmentPositionUpdate(uint32_t qualitybps);
virtual void DLTimeUpdate (double time);
virtual void BufferUpdate (uint32_t bufferFill);
void SetBitrate (uint64_t bufferFill);
uint64_t GetBitrate ();
virtual void SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager);
void NotifyBitrateChange ();
void OnEOS (bool value);
virtual void OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec);
void CheckedByDASHReceiver();
void Quantizer ();
private:
uint64_t currentBitrate;
std::vector<uint64_t> availableBitrates;
sampleplayer::managers::IMultimediaManagerBase *multimediaManager;
dash::mpd::IRepresentation *representation;
uint64_t averageBw; // Classic EWMA
uint64_t instantBw;
uint64_t smoothBw; // FOOBAR paper smoothed y[n]
uint64_t targetBw; // FOOBAR paper x[n] bw estimation
double param_Alpha;
double alpha_ewma;
double param_Epsilon;
double param_K;
double param_W;
double param_Beta;
double param_Bmin;
double interTime; // Actual inter time
double targetInterTime; // Target inter time
double downloadTime;
uint32_t bufferLevel;
uint32_t lastBufferLevel;
double bufferMaxSizeSeconds; // Usually set to 60s
double bufferLevelSeconds; // Current buffer level [s]
double segmentDuration;
double deltaUp;
double deltaDown;
size_t current;
};
} /* namespace adaptation */
} /* namespace framework */
} /* namespace libdash */
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_FOOBAR_H_ */
| 3,402 | 39.511905 | 204 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/AlwaysLowestLogic.cpp
|
/*
* AlwaysLowestLogic.cpp
*****************************************************************************
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "AlwaysLowestLogic.h"
#include<stdio.h>
using namespace libdash::framework::adaptation;
using namespace libdash::framework::input;
using namespace dash::mpd;
AlwaysLowestLogic::AlwaysLowestLogic (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, bool isVid) :
AbstractAdaptationLogic (mpd, period, adaptationSet, isVid)
{
this->representation = this->adaptationSet->GetRepresentation().at(0);
}
AlwaysLowestLogic::~AlwaysLowestLogic ()
{
}
LogicType AlwaysLowestLogic::GetType ()
{
return adaptation::AlwaysLowest;
}
bool AlwaysLowestLogic::IsUserDependent()
{
return false;
}
bool AlwaysLowestLogic::IsRateBased()
{
return false;
}
bool AlwaysLowestLogic::IsBufferBased()
{
return false;
}
void AlwaysLowestLogic::BitrateUpdate(uint64_t bps)
{
}
void AlwaysLowestLogic::SegmentPositionUpdate (uint32_t qualitybps)
{
}
void AlwaysLowestLogic::DLTimeUpdate (double time)
{
}
void AlwaysLowestLogic::BufferUpdate(uint32_t bufferfill)
{
}
void AlwaysLowestLogic::SetMultimediaManager(sampleplayer::managers::IMultimediaManagerBase *mmM)
{
}
void AlwaysLowestLogic::OnEOS(bool value)
{
}
void AlwaysLowestLogic::OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec)
{
}
void AlwaysLowestLogic::CheckedByDASHReceiver()
{
}
| 1,841 | 23.56 | 156 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/LinUcb.cpp
|
/*
* LinUcb.cpp
* By Trevor Ballard and Bastian Alt, <[email protected]>, <[email protected]>
*
* Adapted from code by Michele Tortelli and Jacques Samain, whose copyright is
* reproduced below.
*
*****************************************************************************
* Copyright (C) 2016
* Michele Tortelli and Jacques Samain, <[email protected]>, <[email protected]>
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "LinUcb.h"
#include <stdio.h>
#include <math.h>
#include <chrono>
#include <string>
#include <stdint.h>
#include <iostream>
#include <sstream>
#include <chrono>
#include <inttypes.h>
#include <stdlib.h>
#include <stdarg.h>
#include <algorithm>
#include <inttypes.h>
#include <time.h>
#include <limits.h>
#include <errno.h>
#include <Python.h>
#include <chrono>
#include <thread>
const double MINIMUM_BUFFER_LEVEL_SPACING = 5.0; // The minimum space required between buffer levels (in seconds).
const uint32_t THROUGHPUT_SAMPLES = 3; // Number of samples considered for throughput estimate.
const double SAFETY_FACTOR = 0.9; // Safety factor used with bandwidth estimate.
static PyObject *pName, *pModule, *pDict, *pFuncChoose, *pFuncUpdate;
static int gil_init = 0;
using namespace dash::mpd;
using namespace libdash::framework::adaptation;
using namespace libdash::framework::input;
using namespace libdash::framework::mpd;
using std::bind;
using std::placeholders::_1;
using std::placeholders::_2;
using duration_in_seconds = std::chrono::duration<double, std::ratio<1, 1> >;
LinUcbAdaptation::LinUcbAdaptation (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6) : AbstractAdaptationLogic (mpd, period, adaptationSet, isVid)
{
// Set LinUcb init STATE
this->initState = true;
this->linUcbState = STARTUP;
this->lastDownloadTimeInstant = 0.0;
this->currentDownloadTimeInstant = 0.0;
//this->lastSegmentDownloadTime = 0.0;
this->currentQuality = 0;
this->cumQoE = 0.0;
this->bufferMaxSizeSeconds = 20.0; // It is 'bufferMax' in dash.js implementation
// Find a way to retrieve the value without hard coding it
// Set QoE weights
this->qoe_w1 = arg4;
this->qoe_w2 = arg5;
this->qoe_w3 = arg6;
// Set alpha for the EWMA (bw estimate)
this->alphaRate = 0.8;
this->bufferTargetSeconds = 12.0; // 12s (dash.js implementation) corresponds to 40% with a buffer of 30s
/// Retrieve available bitrates
std::vector<IRepresentation* > representations = this->adaptationSet->GetRepresentation();
this->availableBitrates.clear();
//L("LINUCB Available Bitrates...\n");
for(size_t i = 0; i < representations.size(); i++)
{
this->availableBitrates.push_back((uint64_t)(representations.at(i)->GetBandwidth()));
//L("%d - %I64u bps\n", i+1, this->availableBitrates[i]);
}
// Check if they are in increasing order (i.e., bitrate[0] <= bitrate[1], etc.)
this->bitrateCount = this->availableBitrates.size();
// We check if we have only one birate value or if the bitrate list is irregular (i.e., it is not strictly increasing)
if (this->bitrateCount < 2 || this->availableBitrates[0] >= this->availableBitrates[1] || this->availableBitrates[this->bitrateCount - 2] >= this->availableBitrates[this->bitrateCount - 1]) {
this->linUcbState = ONE_BITRATE;
// return 0; // Check if exit with a message is necessary
}
// Check if the following is correct
this->totalDuration = TimeResolver::GetDurationInSec(this->mpd->GetMediaPresentationDuration());
//this->segmentDuration = (double) (representations.at(0)->GetSegmentTemplate()->GetDuration() / representations.at(0)->GetSegmentTemplate()->GetTimescale() );
this->segmentDuration = 2.0;
//L("Total Duration - LINUCB:\t%f\nSegment Duration - LINUCB:\t%f\n",this->totalDuration, this->segmentDuration);
// if not correct --> segmentDuration = 2.0;
// Compute the LINUCB Buffer Target
this->linUcbBufferTargetSeconds = this->bufferTargetSeconds;
if (this->linUcbBufferTargetSeconds < this->segmentDuration + MINIMUM_BUFFER_LEVEL_SPACING)
{
this->linUcbBufferTargetSeconds = this->segmentDuration + MINIMUM_BUFFER_LEVEL_SPACING;
}
//L("LINUCB Buffer Target Seconds:\t%f\n",this->linUcbBufferTargetSeconds);
// Compute UTILTY vector, Vp, and gp
//L("LINUCB Utility Values...\n");
double utility_tmp;
for (uint32_t i = 0; i < this->bitrateCount; ++i) {
utility_tmp = log(((double)this->availableBitrates[i] * (1./(double)this->availableBitrates[0])));
if(utility_tmp < 0)
utility_tmp = 0;
this->utilityVector.push_back( log(((double)this->availableBitrates[i] * (1./(double)this->availableBitrates[0]))));
//L("%d - %f\n", i+1, this->utilityVector[i]);
}
this->Vp = (this->linUcbBufferTargetSeconds - this->segmentDuration) / this->utilityVector[this->bitrateCount - 1];
this->gp = 1.0 + this->utilityVector[this->bitrateCount - 1] / (this->linUcbBufferTargetSeconds / this->segmentDuration - 1.0);
//L("LINUCB Parameters:\tVp: %f\tgp: %f\n",this->Vp, this->gp);
/* If bufferTargetSeconds (not linUcbBufferTargetSecond) is large enough, we might guarantee that LinUcb will never rebuffer
* unless the network bandwidth drops below the lowest encoded bitrate level. For this to work, LinUcb needs to use the real buffer
* level without the additional virtualBuffer. Also, for this to work efficiently, we need to make sure that if the buffer level
* drops to one fragment during a download, the current download does not have more bits remaining than the size of one fragment
* at the lowest quality*/
this->maxRtt = 0.2; // Is this reasonable?
if(this->linUcbBufferTargetSeconds == this->bufferTargetSeconds) {
this->safetyGuarantee = true;
}
if (this->safetyGuarantee) {
//L("LINUCB SafetyGuarantee...\n");
// we might need to adjust Vp and gp
double VpNew = this->Vp;
double gpNew = this->gp;
for (uint32_t i = 1; i < this->bitrateCount; ++i) {
double threshold = VpNew * (gpNew - this->availableBitrates[0] * this->utilityVector[i] / (this->availableBitrates[i] - this->availableBitrates[0]));
double minThreshold = this->segmentDuration * (2.0 - this->availableBitrates[0] / this->availableBitrates[i]) + maxRtt;
if (minThreshold >= this->bufferTargetSeconds) {
safetyGuarantee = false;
break;
}
if (threshold < minThreshold) {
VpNew = VpNew * (this->bufferTargetSeconds - minThreshold) / (this->bufferTargetSeconds - threshold);
gpNew = minThreshold / VpNew + this->utilityVector[i] * this->availableBitrates[0] / (this->availableBitrates[i] - this->availableBitrates[0]);
}
}
if (safetyGuarantee && (this->bufferTargetSeconds - this->segmentDuration) * VpNew / this->Vp < MINIMUM_BUFFER_LEVEL_SPACING) {
safetyGuarantee = false;
}
if (safetyGuarantee) {
this->Vp = VpNew;
this->gp = gpNew;
}
}
//L("LINUCB New Parameters:\tVp: %f\tgp: %f\n",this->Vp, this->gp);
// Capping of the virtual buffer (when using it)
this->linUcbBufferMaxSeconds = this->Vp * (this->utilityVector[this->bitrateCount - 1] + this->gp);
//L("LINUCB Max Buffer Seconds:\t%f\n",this->linUcbBufferMaxSeconds);
this->virtualBuffer = 0.0; // Check if we should use either the virtualBuffer or the safetyGuarantee
this->instantBw = 0;
this->averageBw = 0;
this->batchBw = 0; // Computed every THROUGHPUT_SAMPLES samples (average)
this->batchBwCount = 0;
this->multimediaManager = NULL;
this->lastBufferFill = 0; // (?)
this->bufferEOS = false;
this->shouldAbort = false;
this->isCheckedForReceiver = false;
this->representation = representations.at(0);
this->currentBitrate = (uint64_t) this->representation->GetBandwidth();
this->rebufferStart = 0;
this->rebufferEnd = 0;
Py_Initialize();
PyRun_SimpleString("import sys; sys.path.append('/'); import run_bandits");
pName = PyUnicode_FromString("run_bandits");
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFuncChoose = PyDict_GetItemString(pDict, "choose");
pFuncUpdate = PyDict_GetItemString(pDict, "update");
//L("LINUCB Init Params - \tAlpha: %f \t BufferTarget: %f\n",this->alphaRate, this->bufferTargetSeconds);
//L("LINUCB Init Current BitRate - %I64u\n",this->currentBitrate);
Debug("Buffer Adaptation LINUCB: STARTED\n");
}
LinUcbAdaptation::~LinUcbAdaptation ()
{
Py_DECREF(pModule);
Py_DECREF(pName);
Py_Finalize();
}
LogicType LinUcbAdaptation::GetType ()
{
return adaptation::BufferBased;
}
bool LinUcbAdaptation::IsUserDependent ()
{
return false;
}
bool LinUcbAdaptation::IsRateBased ()
{
return true;
}
bool LinUcbAdaptation::IsBufferBased ()
{
return true;
}
void LinUcbAdaptation::SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager)
{
this->multimediaManager = _mmManager;
}
void LinUcbAdaptation::NotifyBitrateChange ()
{
if(this->multimediaManager)
if(this->multimediaManager->IsStarted() && !this->multimediaManager->IsStopping())
if(this->isVideo)
this->multimediaManager->SetVideoQuality(this->period, this->adaptationSet, this->representation);
else
this->multimediaManager->SetAudioQuality(this->period, this->adaptationSet, this->representation);
//Should Abort is done here to avoid race condition with DASHReceiver::DoBuffering()
if(this->shouldAbort)
{
//L("Aborting! To avoid race condition.");
//printf("Sending Abort request\n");
this->multimediaManager->ShouldAbort(this->isVideo);
//printf("Received Abort request\n");
}
this->shouldAbort = false;
}
uint64_t LinUcbAdaptation::GetBitrate ()
{
return this->currentBitrate;
}
int LinUcbAdaptation::getQualityFromThroughput(uint64_t bps) {
int q = 0;
for (int i = 0; i < this->availableBitrates.size(); ++i) {
if (this->availableBitrates[i] > bps) {
break;
}
q = i;
}
return q;
}
int LinUcbAdaptation::getQualityFromBufferLevel(double bufferLevelSec) {
int quality = this->bitrateCount - 1;
double score = 0.0;
for (int i = 0; i < this->bitrateCount; ++i) {
double s = (this->utilityVector[i] + this->gp - bufferLevelSec / this->Vp) / this->availableBitrates[i];
if (s > score) {
score = s;
quality = i;
}
}
return quality;
}
void LinUcbAdaptation::SetBitrate (uint32_t bufferFill)
{
int result = 0;
PyObject *pArgs, *pValue;
std::vector<IRepresentation*> representations = this->adaptationSet->GetRepresentation();
int numArms = (int)representations.size();
pValue = PyList_New(0);
for (int i=0; i<numArms; i++) {
PyObject* pTemp = PyList_New(0);
// for bufferFill
PyList_Append(pTemp, PyFloat_FromDouble((double)bufferFill/(double)100));
// for RTT
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> rttVec = this->rttMap[i];
for (int j=0; j<rttVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)rttVec[j]));
}
// for num hops
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> numHopsVec = this->numHopsMap[i];
for (int j=0; j<numHopsVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)numHopsVec[j]));
}
PyList_Append(pValue, pTemp);
Py_XDECREF(pTemp);
}
pArgs = PyTuple_New(2);
PyTuple_SetItem(pArgs, 0, PyUnicode_FromString("linucb"));
PyTuple_SetItem(pArgs, 1, pValue);
if (!gil_init) {
gil_init = 1;
PyEval_InitThreads();
PyEval_SaveThread();
}
// 2: Execute
PyGILState_STATE state = PyGILState_Ensure();
unsigned long long int execStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
pValue = PyObject_CallObject(pFuncChoose, pArgs);
unsigned long long int execEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
result = (int)PyLong_AsLong(pValue);
Py_XDECREF(pArgs);
Py_XDECREF(pValue);
PyGILState_Release(state);
int duration = (int)(execEnd - execStart);
std::cout << "stat-begin" << std::endl;
std::cout << "stat-bandit-normal" << std::endl;
std::cout << "stat-chexecms " << duration << std::endl;
std::cout << "stat-chqual " << result << std::endl;
if (result < 0 || result > numArms-1) {
std::cout << "ERROR: Result was out of bounds. Using quality of 2." << std::endl;
result = 2;
}
this->currentQuality = result;
this->representation = this->adaptationSet->GetRepresentation().at(this->currentQuality);
this->currentBitrate = (uint64_t) this->availableBitrates[this->currentQuality];
//L("STEADY - Current Bitrate:\t%I64u\n", this->currentBitrate);
//L("ADAPTATION_LOGIC:\tFor %s:\tlast_buffer: %f\tbuffer_level: %f, instantaneousBw: %lu, AverageBW: %lu, choice: %d\n",isVideo ? "video" : "audio",(double)lastBufferFill/100 , (double)bufferFill/100, this->instantBw, this->averageBw , this->currentQuality);
this->lastBufferFill = bufferFill;
}
void LinUcbAdaptation::BitrateUpdate(uint64_t bps)
{
}
void LinUcbAdaptation::SegmentPositionUpdate (uint32_t qualitybps)
{
//L("Called SegmentPositionUpdate\n");
}
void LinUcbAdaptation::DLTimeUpdate (double time)
{
auto m_now = std::chrono::system_clock::now();
auto m_now_sec = std::chrono::time_point_cast<std::chrono::seconds>(m_now);
auto now_value = m_now_sec.time_since_epoch();
double dl_instant = now_value.count();
//this->lastSegmentDownloadTime = time;
//this->currentDownloadTimeInstant = std::chrono::duration_cast<duration_in_seconds>(system_clock::now()).count();
this->currentDownloadTimeInstant = dl_instant;
}
void LinUcbAdaptation::OnEOS (bool value)
{
this->bufferEOS = value;
}
void LinUcbAdaptation::OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec)
{
std::vector<IRepresentation*> representations = this->adaptationSet->GetRepresentation();
int numArms = (int)representations.size();
uint32_t bufferFill = (uint32_t)(bufferFillPct * (double)100);
std::cout << "stat-qual " << quality << std::endl;
//L("stat-buffpct %f\n", bufferFillPct);
////////////////
// Update MAB //
////////////////
// First calculate the real QoE for the segment:
// 1. Base quality (kbps)
// 2. Decline in quality (kbps)
// 3. Time spent rebuffering (ms)
// 1. Base quality
int baseQuality = (int)(this->availableBitrates[quality] / (uint64_t)1000);
std::cout << "stat-qoebase " << baseQuality << std::endl;
// 2. Decline in quality
this->qualityHistory[segNum] = quality;
int qualityDecline = 0;
if (this->qualityHistory[segNum] < this->qualityHistory[segNum-1]) {
int prevQuality = (int)(this->availableBitrates[this->qualityHistory[segNum-1]]/(uint64_t)1000);
int currQuality = (int)(this->availableBitrates[quality]/(uint64_t)1000);
qualityDecline = prevQuality - currQuality;
}
std::cout << "stat-qoedecl " << qualityDecline << std::endl;
// 3. Time spent rebuffering
// We just got a new segment so rebuffering has stopped
// If it occurred, we need to know for how long
int rebufferTime = 0;
if (this->rebufferStart != 0) {
if (this->rebufferEnd == 0) {
this->rebufferEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
}
rebufferTime = (int)(this->rebufferEnd - this->rebufferStart);
this->rebufferStart = 0;
}
std::cout << "stat-qoerebuffms " << rebufferTime << std::endl;
// Put it all together for the reward
// The weight of 3 comes from the SIGCOMM paper; they use 3000 because their
// rebufferTime is in seconds, but ours is milliseconds
double reward = (this->qoe_w1*(double)baseQuality) - (this->qoe_w2*(double)qualityDecline) - (this->qoe_w3*(double)rebufferTime*(double)rebufferTime);
this->cumQoE += reward;
std::cout << "stat-qoeseg " << reward << std::endl;
std::cout << "stat-qoecum " << this->cumQoE << std::endl;
// If we're still in the first K iterations, we have to try all arms. Try the one
// corresponding to this segment
// TODO would be better to put in SetBitrate, but that'd take a bit of refactoring
/*
if (segNum < numArms) {
//L("stat-initarms %d\n", segNum);
std::cout << "stat-bandit-init" << std::endl;
this->currentQuality = segNum;
this->representation = this->adaptationSet->GetRepresentation().at(this->currentQuality);
this->currentBitrate = (uint64_t) this->availableBitrates[this->currentQuality];
this->lastBufferFill = bufferFill;
//L("STEADY - Current Bitrate:\t%I64u\n", this->currentBitrate);
this->qualityHistory[segNum] = quality;
this->rttMap[quality] = rttVec;
this->ecnMap[quality] = ecnVec;
this->numHopsMap[quality] = numHopsVec;
this->NotifyBitrateChange();
}
else {
*/
// 1: Build args
int result = 0;
PyObject *pArgs, *pValue;
pValue = PyList_New(0);
for (int i=0; i<numArms; i++) {
PyObject* pTemp = PyList_New(0);
PyList_Append(pTemp, PyFloat_FromDouble(bufferFillPct));
// for RTT
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> tempRttVec = this->rttMap[i];
for (int j=0; j<tempRttVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)tempRttVec[j]));
}
/*
// for ECN
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> tempEcnVec = this->ecnMap[i];
for (int j=0; j<tempEcnVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)tempEcnVec[j]));
}
*/
// for num hops
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> tempNumHopsVec = this->numHopsMap[i];
for (int j=0; j<tempNumHopsVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)tempNumHopsVec[j]));
}
PyList_Append(pValue, pTemp);
Py_XDECREF(pTemp);
}
pArgs = PyTuple_New(5);
PyTuple_SetItem(pArgs, 0, PyUnicode_FromString("linucb"));
// context
PyTuple_SetItem(pArgs, 1, pValue);
// last quality (action)
PyTuple_SetItem(pArgs, 2, PyLong_FromLong((long)quality));
// reward
PyTuple_SetItem(pArgs, 3, PyFloat_FromDouble(reward));
// timestep
PyTuple_SetItem(pArgs, 4, PyLong_FromLong((long)segNum));
if (!gil_init) {
std::cout << "WARNING: setting gil_init in BitrateUpdate" << std::endl;
gil_init = 1;
PyEval_InitThreads();
PyEval_SaveThread();
}
// 2: Execute
PyGILState_STATE state = PyGILState_Ensure();
unsigned long long int execStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
pValue = PyObject_CallObject(pFuncUpdate, pArgs);
unsigned long long int execEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
result = (int)PyLong_AsLong(pValue);
Py_XDECREF(pArgs);
Py_XDECREF(pValue);
PyGILState_Release(state);
int duration = (int)(execEnd - execStart);
std::cout << "stat-updexecms " << duration << std::endl;
if (result != 1) {
std::cout << "WARNING: Update MAB failed" << std::endl;
}
/////////////////////////////
// Update internal context //
/////////////////////////////
this->rttMap[quality] = rttVec;
//this->ecnMap[quality] = ecnVec;
this->numHopsMap[quality] = numHopsVec;
// Run MAB using the new context
this->SetBitrate(bufferFill);
this->NotifyBitrateChange();
//} <--- the commented out else statement
}
void LinUcbAdaptation::CheckedByDASHReceiver ()
{
//L("CheckedByDASHReceiver called\n");
this->isCheckedForReceiver = false;
}
void LinUcbAdaptation::BufferUpdate (uint32_t bufferFill)
{
if (bufferFill == (uint32_t)0 && this->rebufferStart == 0) {
this->rebufferStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
this->rebufferEnd = 0;
//L("Buffer is at 0; rebuffering has begun and playback has stalled\n");
}
else if (this->rebufferEnd == 0 && this->rebufferStart != 0) {
this->rebufferEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
//L("Stopped rebuffering; resuming playback\n");
}
}
| 21,790 | 38.051971 | 262 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/ManualAdaptation.h
|
/*
* ManualAdaptation.h
*****************************************************************************
* Copyright (C) 2013, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_MANUALADAPTATION_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_MANUALADAPTATION_H_
#include "AbstractAdaptationLogic.h"
#include "../MPD/AdaptationSetStream.h"
namespace libdash
{
namespace framework
{
namespace adaptation
{
class ManualAdaptation : public AbstractAdaptationLogic
{
public:
ManualAdaptation (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, bool isVid);
virtual ~ManualAdaptation ();
virtual LogicType GetType ();
virtual bool IsUserDependent ();
virtual bool IsRateBased ();
virtual bool IsBufferBased ();
virtual void BitrateUpdate (uint64_t bps);
virtual void SegmentPositionUpdate(uint32_t qualitybps);
virtual void DLTimeUpdate (double time);
virtual void BufferUpdate (uint32_t bufferfill);
virtual void SetMultimediaManager(sampleplayer::managers::IMultimediaManagerBase *mmM);
virtual void OnEOS (bool value);
virtual void OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec);
virtual void CheckedByDASHReceiver();
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_MANUALADAPTATION_H_ */
| 2,088 | 42.520833 | 174 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/Bola.cpp
|
/*
* Bola.cpp
*****************************************************************************
* Copyright (C) 2016
* Michele Tortelli and Jacques Samain, <[email protected]>, <[email protected]>
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "Bola.h"
#include <stdio.h>
#include <math.h>
#include <chrono>
#include <string>
#include <stdint.h>
#include <iostream>
#include <sstream>
#include <chrono>
#include <inttypes.h>
#include <stdlib.h>
#include <stdarg.h>
#include <algorithm>
#include <inttypes.h>
#include <time.h>
#include <limits.h>
#include <errno.h>
const double MINIMUM_BUFFER_LEVEL_SPACING = 5.0; // The minimum space required between buffer levels (in seconds).
const uint32_t THROUGHPUT_SAMPLES = 3; // Number of samples considered for throughput estimate.
const double SAFETY_FACTOR = 0.9; // Safety factor used with bandwidth estimate.
using namespace dash::mpd;
using namespace libdash::framework::adaptation;
using namespace libdash::framework::input;
using namespace libdash::framework::mpd;
using std::bind;
using std::placeholders::_1;
using std::placeholders::_2;
using duration_in_seconds = std::chrono::duration<double, std::ratio<1, 1> >;
BolaAdaptation::BolaAdaptation (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6) :
AbstractAdaptationLogic (mpd, period, adaptationSet, isVid)
{
// Set Bola init STATE
this->initState = true;
this->bolaState = STARTUP;
this->lastDownloadTimeInstant = 0.0;
this->currentDownloadTimeInstant = 0.0;
//this->lastSegmentDownloadTime = 0.0;
this->currentQuality = 0;
this->bufferMaxSizeSeconds = 20.0; // It is 'bufferMax' in dash.js implementation
// Find a way to retrieve the value without hard coding it
// Set QoE weights
this->qoe_w1 = arg4;
this->qoe_w2 = arg5;
this->qoe_w3 = arg6;
this->rebufferStart = 0;
this->rebufferEnd = 0;
// Set alpha for the EWMA (bw estimate)
if(arg1) {
if(arg1 >= 0 && arg1 <= 1) {
this->alphaRate = arg1;
}
else
this->alphaRate = 0.8;
}
else {
Debug("EWMA Alpha parameter NOT SPECIFIED!\n");
}
/// Set 'bufferTarget' (it separates STARTUP from STEADY STATE)
if(arg2) {
if(arg2 > 0 && arg2 < (int)bufferMaxSizeSeconds) {
this->bufferTargetSeconds = (double)arg2;
}
else
this->bufferTargetSeconds = 12.0; // 12s (dash.js implementation) corresponds to 40% with a buffer of 30s
this->bufferTargetPerc = (uint32_t) ( round(this->bufferTargetSeconds / this->bufferMaxSizeSeconds)*100 );
}
else {
Debug("bufferTarget NOT SPECIFIED!\n");
}
/// Retrieve available bitrates
std::vector<IRepresentation* > representations = this->adaptationSet->GetRepresentation();
this->availableBitrates.clear();
L("BOLA Available Bitrates...\n");
for(size_t i = 0; i < representations.size(); i++)
{
this->availableBitrates.push_back((uint64_t)(representations.at(i)->GetBandwidth()));
L("%d - %I64u bps\n", i+1, this->availableBitrates[i]);
}
// Check if they are in increasing order (i.e., bitrate[0] <= bitrate[1], etc.)
this->bitrateCount = this->availableBitrates.size();
// We check if we have only one birate value or if the bitrate list is irregular (i.e., it is not strictly increasing)
if (this->bitrateCount < 2 || this->availableBitrates[0] >= this->availableBitrates[1] || this->availableBitrates[this->bitrateCount - 2] >= this->availableBitrates[this->bitrateCount - 1]) {
this->bolaState = ONE_BITRATE;
// return 0; // Check if exit with a message is necessary
}
// Check if the following is correct
this->totalDuration = TimeResolver::GetDurationInSec(this->mpd->GetMediaPresentationDuration());
//this->segmentDuration = (double) (representations.at(0)->GetSegmentTemplate()->GetDuration() / representations.at(0)->GetSegmentTemplate()->GetTimescale() );
this->segmentDuration = 2.0;
L("Total Duration - BOLA:\t%f\nSegment Duration - BOLA:\t%f\n",this->totalDuration, this->segmentDuration);
// if not correct --> segmentDuration = 2.0;
// Compute the BOLA Buffer Target
this->bolaBufferTargetSeconds = this->bufferTargetSeconds;
if (this->bolaBufferTargetSeconds < this->segmentDuration + MINIMUM_BUFFER_LEVEL_SPACING)
{
this->bolaBufferTargetSeconds = this->segmentDuration + MINIMUM_BUFFER_LEVEL_SPACING;
}
L("BOLA Buffer Target Seconds:\t%f\n",this->bolaBufferTargetSeconds);
// Compute UTILTY vector, Vp, and gp
L("BOLA Utility Values...\n");
double utility_tmp;
for (uint32_t i = 0; i < this->bitrateCount; ++i) {
utility_tmp = log(((double)this->availableBitrates[i] * (1./(double)this->availableBitrates[0])));
if(utility_tmp < 0)
utility_tmp = 0;
this->utilityVector.push_back( log(((double)this->availableBitrates[i] * (1./(double)this->availableBitrates[0]))));
L("%d - %f\n", i+1, this->utilityVector[i]);
}
this->Vp = (this->bolaBufferTargetSeconds - this->segmentDuration) / this->utilityVector[this->bitrateCount - 1];
this->gp = 1.0 + this->utilityVector[this->bitrateCount - 1] / (this->bolaBufferTargetSeconds / this->segmentDuration - 1.0);
L("BOLA Parameters:\tVp: %f\tgp: %f\n",this->Vp, this->gp);
/* If bufferTargetSeconds (not bolaBufferTargetSecond) is large enough, we might guarantee that Bola will never rebuffer
* unless the network bandwidth drops below the lowest encoded bitrate level. For this to work, Bola needs to use the real buffer
* level without the additional virtualBuffer. Also, for this to work efficiently, we need to make sure that if the buffer level
* drops to one fragment during a download, the current download does not have more bits remaining than the size of one fragment
* at the lowest quality*/
this->maxRtt = 0.2; // Is this reasonable?
if(this->bolaBufferTargetSeconds == this->bufferTargetSeconds) {
this->safetyGuarantee = true;
}
if (this->safetyGuarantee) {
L("BOLA SafetyGuarantee...\n");
// we might need to adjust Vp and gp
double VpNew = this->Vp;
double gpNew = this->gp;
for (uint32_t i = 1; i < this->bitrateCount; ++i) {
double threshold = VpNew * (gpNew - this->availableBitrates[0] * this->utilityVector[i] / (this->availableBitrates[i] - this->availableBitrates[0]));
double minThreshold = this->segmentDuration * (2.0 - this->availableBitrates[0] / this->availableBitrates[i]) + maxRtt;
if (minThreshold >= this->bufferTargetSeconds) {
safetyGuarantee = false;
break;
}
if (threshold < minThreshold) {
VpNew = VpNew * (this->bufferTargetSeconds - minThreshold) / (this->bufferTargetSeconds - threshold);
gpNew = minThreshold / VpNew + this->utilityVector[i] * this->availableBitrates[0] / (this->availableBitrates[i] - this->availableBitrates[0]);
}
}
if (safetyGuarantee && (this->bufferTargetSeconds - this->segmentDuration) * VpNew / this->Vp < MINIMUM_BUFFER_LEVEL_SPACING) {
safetyGuarantee = false;
}
if (safetyGuarantee) {
this->Vp = VpNew;
this->gp = gpNew;
}
}
L("BOLA New Parameters:\tVp: %f\tgp: %f\n",this->Vp, this->gp);
// Capping of the virtual buffer (when using it)
this->bolaBufferMaxSeconds = this->Vp * (this->utilityVector[this->bitrateCount - 1] + this->gp);
L("BOLA Max Buffer Seconds:\t%f\n",this->bolaBufferMaxSeconds);
this->virtualBuffer = 0.0; // Check if we should use either the virtualBuffer or the safetyGuarantee
this->instantBw = 0;
this->averageBw = 0;
this->batchBw = 0; // Computed every THROUGHPUT_SAMPLES samples (average)
this->batchBwCount = 0;
this->multimediaManager = NULL;
this->lastBufferFill = 0; // (?)
this->bufferEOS = false;
this->shouldAbort = false;
this->isCheckedForReceiver = false;
this->representation = representations.at(0);
this->currentBitrate = (uint64_t) this->representation->GetBandwidth();
L("BOLA Init Params - \tAlpha: %f \t BufferTarget: %f\n",this->alphaRate, this->bufferTargetSeconds);
L("BOLA Init Current BitRate - %I64u\n",this->currentBitrate);
Debug("Buffer Adaptation BOLA: STARTED\n");
}
BolaAdaptation::~BolaAdaptation ()
{
}
LogicType BolaAdaptation::GetType ()
{
return adaptation::BufferBased;
}
bool BolaAdaptation::IsUserDependent ()
{
return false;
}
bool BolaAdaptation::IsRateBased ()
{
return true;
}
bool BolaAdaptation::IsBufferBased ()
{
return true;
}
void BolaAdaptation::SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager)
{
this->multimediaManager = _mmManager;
}
void BolaAdaptation::NotifyBitrateChange ()
{
if(this->multimediaManager)
if(this->multimediaManager->IsStarted() && !this->multimediaManager->IsStopping())
if(this->isVideo)
this->multimediaManager->SetVideoQuality(this->period, this->adaptationSet, this->representation);
else
this->multimediaManager->SetAudioQuality(this->period, this->adaptationSet, this->representation);
//Should Abort is done here to avoid race condition with DASHReceiver::DoBuffering()
if(this->shouldAbort)
{
//printf("Sending Abort request\n");
this->multimediaManager->ShouldAbort(this->isVideo);
//printf("Received Abort request\n");
}
this->shouldAbort = false;
}
uint64_t BolaAdaptation::GetBitrate ()
{
return this->currentBitrate;
}
int BolaAdaptation::getQualityFromThroughput(uint64_t bps) {
int q = 0;
for (int i = 0; i < this->availableBitrates.size(); ++i) {
if (this->availableBitrates[i] > bps) {
break;
}
q = i;
}
return q;
}
int BolaAdaptation::getQualityFromBufferLevel(double bufferLevelSec) {
int quality = this->bitrateCount - 1;
double score = 0.0;
for (int i = 0; i < this->bitrateCount; ++i) {
double s = (this->utilityVector[i] + this->gp - bufferLevelSec / this->Vp) / this->availableBitrates[i];
if (s > score) {
score = s;
quality = i;
}
}
return quality;
}
void BolaAdaptation::SetBitrate (uint32_t bufferFill)
{
// *** NB *** Insert Log messages
if(this->initState)
{
this->initState = false;
if(this->bolaState != ONE_BITRATE)
{
if(this->batchBw != 0) // Check the current estimated throughput (batch mean)
this->currentQuality = getQualityFromThroughput(this->batchBw*SAFETY_FACTOR);
//else --> quality unchanged
}
//this->representation = this->availableBitrates[this->currentQuality];
//this->currentBitrate = (uint64_t) this->representation->GetBandwidth();
this->representation = this->adaptationSet->GetRepresentation().at(this->currentQuality);
this->currentBitrate = (uint64_t) this->availableBitrates[this->currentQuality];
L("INIT - Current Bitrate:\t%I64u\n", this->currentBitrate);
L("ADAPTATION_LOGIC:\tFor %s:\tlast_buffer: %f\tbuffer_level: %f, instantaneousBw: %lu, AverageBW: %lu, choice: %d\n",isVideo ? "video" : "audio",(double)lastBufferFill/100 , (double)bufferFill/100, this->instantBw, this->averageBw , this->currentQuality);
this->lastBufferFill = bufferFill;
return;
}
if(this->bolaState == ONE_BITRATE) {
this->currentQuality = 0;
//this->representation = this->availableBitrates[this->currentQuality];
//this->currentBitrate = (uint64_t) this->representation->GetBandwidth();
this->representation = this->adaptationSet->GetRepresentation().at(this->currentQuality);
this->currentBitrate = (uint64_t) this->availableBitrates[this->currentQuality];
L("ONE BITRATE - Current Bitrate:\t%I64u\n", this->currentBitrate);
L("ADAPTATION_LOGIC:\tFor %s:\tlast_buffer: %f\tbuffer_level: %f, instantaneousBw: %lu, AverageBW: %lu, choice: %d\n",isVideo ? "video" : "audio",(double)lastBufferFill/100 , (double)bufferFill/100, this->instantBw, this->averageBw , this->currentQuality);
this->lastBufferFill = bufferFill;
return;
}
// Obtain bufferFill in seconds;
double bufferLevelSeconds = (double)( (bufferFill * this->bufferMaxSizeSeconds) *1./100);
int bolaQuality = getQualityFromBufferLevel(bufferLevelSeconds);
L("REGULAR - Buffer Level Seconds:\t%f; Bola Quality:\t%d\n", bufferLevelSeconds, bolaQuality);
if (bufferLevelSeconds <= 0.1) {
// rebuffering occurred, reset virtual buffer
this->virtualBuffer = 0.0;
}
// We check if the safetyGuarantee should be used. if not, we use the virtual buffer
// STILL NOT COMPLETE; Find a way to retrieved time since the last download
if (!this->safetyGuarantee) // we can use virtualBuffer
{
// find out if there was delay because of lack of availability or because bolaBufferTarget > bufferTarget
// TODO
//double timeSinceLastDownload = getDelayFromLastFragmentInSeconds(); // Define function
double timeSinceLastDownload = this->currentDownloadTimeInstant - this->lastDownloadTimeInstant;
L("VirtualBuffer - Time Since Last Download:\t%f\n", timeSinceLastDownload);
if (timeSinceLastDownload > 0.0) {
this->virtualBuffer += timeSinceLastDownload;
}
if ( (bufferLevelSeconds + this->virtualBuffer) > this->bolaBufferMaxSeconds) {
this->virtualBuffer = this->bolaBufferMaxSeconds - bufferLevelSeconds;
}
if (this->virtualBuffer < 0.0) {
this->virtualBuffer = 0.0;
}
L("VirtualBuffer - Virtual Buffer Value:\t%f\n", this->virtualBuffer);
// Update currentDownloadTimeInstant
this->lastDownloadTimeInstant = this->currentDownloadTimeInstant;
// Update bolaQuality using virtualBuffer: bufferLevel might be artificially low because of lack of availability
int bolaQualityVirtual = getQualityFromBufferLevel(bufferLevelSeconds + this->virtualBuffer);
L("VirtualBuffer - Bola Quality Virtual:\t%d\n", bolaQualityVirtual);
if (bolaQualityVirtual > bolaQuality) {
// May use quality higher than that indicated by real buffer level.
// In this case, make sure there is enough throughput to download a fragment before real buffer runs out.
int maxQuality = bolaQuality;
while (maxQuality < bolaQualityVirtual && (this->availableBitrates[maxQuality + 1] * this->segmentDuration) / (this->currentBitrate * SAFETY_FACTOR) < bufferLevelSeconds)
{
++maxQuality;
}
// TODO: maybe we can use a more conservative level here, but this should be OK
L("VirtualBuffer - Bola Quality Virtual HIGHER than Bola Quality - Max Quality:\t%d\n", maxQuality);
if (maxQuality > bolaQuality)
{
// We can (and will) download at a quality higher than that indicated by real buffer level.
if (bolaQualityVirtual <= maxQuality) {
// we can download fragment indicated by real+virtual buffer without rebuffering
bolaQuality = bolaQualityVirtual;
} else {
// downloading fragment indicated by real+virtual rebuffers, use lower quality
bolaQuality = maxQuality;
// deflate virtual buffer to match quality
double targetBufferLevel = this->Vp * (this->gp + this->utilityVector[bolaQuality]);
if (bufferLevelSeconds + this->virtualBuffer > targetBufferLevel) {
this->virtualBuffer = targetBufferLevel - bufferLevelSeconds;
if (this->virtualBuffer < 0.0) { // should be false
this->virtualBuffer = 0.0;
}
}
}
}
}
}
if (this->bolaState == STARTUP || this->bolaState == STARTUP_NO_INC) {
// in startup phase, use some throughput estimation
int quality = getQualityFromThroughput(this->batchBw*SAFETY_FACTOR);
if (this->batchBw <= 0.0) {
// something went wrong - go to steady state
this->bolaState = STEADY;
}
if (this->bolaState == STARTUP && quality < this->currentQuality) {
// Since the quality is decreasing during startup, it will not be allowed to increase again.
this->bolaState = STARTUP_NO_INC;
}
if (this->bolaState == STARTUP_NO_INC && quality > this->currentQuality) {
// In this state the quality is not allowed to increase until steady state.
quality = this->currentQuality;
}
if (quality <= bolaQuality) {
// Since the buffer is full enough for steady state operation to match startup operation, switch over to steady state.
this->bolaState = STEADY;
}
if (this->bolaState != STEADY) {
// still in startup mode
this->currentQuality = quality;
//this->representation = this->availableBitrates[this->currentQuality];
//this->currentBitrate = (uint64_t) this->representation->GetBandwidth();
this->representation = this->adaptationSet->GetRepresentation().at(this->currentQuality);
this->currentBitrate = (uint64_t) this->availableBitrates[this->currentQuality];
L("STILL IN STARTUP - Current Bitrate:\t%I64u\n", this->currentBitrate);
L("ADAPTATION_LOGIC:\tFor %s:\tlast_buffer: %f\tbuffer_level: %f, instantaneousBw: %lu, AverageBW: %lu, choice: %d\n",isVideo ? "video" : "audio",(double)lastBufferFill/100 , (double)bufferFill/100, this->instantBw, this->averageBw , this->currentQuality);
this->lastBufferFill = bufferFill;
return;
}
}
// Steady State
// In order to avoid oscillation, the "BOLA-O" variant is implemented.
// When network bandwidth lies between two encoded bitrate levels, stick to the lowest one.
double delaySeconds = 0.0;
if (bolaQuality > this->currentQuality) {
L("STEADY -- BOLA QUALITY:\t%d - HIGHER than - CURRENT QUALITY:\t%I64u\n", bolaQuality, this->currentBitrate);
// do not multiply throughput by bandwidthSafetyFactor here;
// we are not using throughput estimation but capping bitrate to avoid oscillations
int quality = getQualityFromThroughput(this->batchBw);
if (bolaQuality > quality) {
// only intervene if we are trying to *increase* quality to an *unsustainable* level
if (quality < this->currentQuality) {
// The aim is only to avoid oscillations - do not drop below current quality
quality = this->currentQuality;
} else {
// We are dropping to an encoded bitrate which is a little less than the network bandwidth
// since bitrate levels are discrete. Quality 'quality' might lead to buffer inflation,
// so we deflate the buffer to the level that 'quality' gives positive utility.
double targetBufferLevel = this->Vp * (this->utilityVector[quality] + this->gp);
delaySeconds = bufferLevelSeconds - targetBufferLevel;
}
bolaQuality = quality;
}
}
if (delaySeconds > 0.0) {
// first reduce virtual buffer
if (delaySeconds > this->virtualBuffer) {
delaySeconds -= this->virtualBuffer;
this->virtualBuffer = 0.0;
} else {
this->virtualBuffer -= delaySeconds;
delaySeconds = 0.0;
}
}
if (delaySeconds > 0.0) {
// TODO Check the scope of this function. Is it a delayed request?
// streamProcessor.getScheduleController().setTimeToLoadDelay(1000.0 * delaySeconds);
// NEED TO CHECK THIS
L("STEADY -- DELAY DOWNLOAD OF:\t%f\n", delaySeconds);
this->multimediaManager->SetTargetDownloadingTime(this->isVideo, delaySeconds);
}
this->currentQuality = bolaQuality;
//this->representation = this->availableBitrates[this->currentQuality];
this->representation = this->adaptationSet->GetRepresentation().at(this->currentQuality);
this->currentBitrate = (uint64_t) this->availableBitrates[this->currentQuality];
L("STEADY - Current Bitrate:\t%I64u\n", this->currentBitrate);
L("ADAPTATION_LOGIC:\tFor %s:\tlast_buffer: %f\tbuffer_level: %f, instantaneousBw: %lu, AverageBW: %lu, choice: %d\n",isVideo ? "video" : "audio",(double)lastBufferFill/100 , (double)bufferFill/100, this->instantBw, this->averageBw , this->currentQuality);
this->lastBufferFill = bufferFill;
}
void BolaAdaptation::BitrateUpdate (uint64_t bps)
{
this->instantBw = bps;
// Avg bandwidth estimate with EWMA
if(this->averageBw == 0)
{
this->averageBw = bps;
}
else
{
this->averageBw = this->alphaRate*this->averageBw + (1 - this->alphaRate)*bps;
}
// Avg bandwidth estimate with batch mean of THROUGHPUT_SAMPLES sample
this->batchBwCount++;
this->batchBwSamples.push_back(bps);
if(this->batchBwCount++ == THROUGHPUT_SAMPLES)
{
for(int i=0; i<THROUGHPUT_SAMPLES; i++)
this->batchBw += this->batchBwSamples[i];
this->batchBw /= THROUGHPUT_SAMPLES;
L("BATCH BW:\t%I64u\n", this->batchBw);
this->batchBwCount=0;
this->batchBwSamples.clear();
}
}
void BolaAdaptation::SegmentPositionUpdate (uint32_t qualitybps)
{
}
void BolaAdaptation::DLTimeUpdate (double time)
{
auto m_now = std::chrono::system_clock::now();
auto m_now_sec = std::chrono::time_point_cast<std::chrono::seconds>(m_now);
auto now_value = m_now_sec.time_since_epoch();
double dl_instant = now_value.count();
//this->lastSegmentDownloadTime = time;
//this->currentDownloadTimeInstant = std::chrono::duration_cast<duration_in_seconds>(system_clock::now()).count();
this->currentDownloadTimeInstant = dl_instant;
}
void BolaAdaptation::OnEOS (bool value)
{
this->bufferEOS = value;
}
void BolaAdaptation::OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec)
{
std::vector<IRepresentation*> representations = this->adaptationSet->GetRepresentation();
int numArms = (int)representations.size();
uint32_t bufferFill = (uint32_t)(bufferFillPct * (double)100);
std::cout << "stat-begin" << std::endl;
std::cout << "stat-nonbandit" << std::endl;
std::cout << "stat-qual " << quality << std::endl;
///////////////////
// Calculate QoE //
///////////////////
// 1. Base quality (kbps)
// 2. Decline in quality (kbps)
// 3. Time spent rebuffering (ms)
// 1. Base quality
int baseQuality = (int)(this->availableBitrates[quality] / (uint64_t)1000);
std::cout << "stat-qoebase " << baseQuality << std::endl;
// 2. Decline in quality
this->qualityHistory[segNum] = quality;
int qualityDecline = 0;
if (this->qualityHistory[segNum] < this->qualityHistory[segNum-1]) {
int prevQuality = (int)(this->availableBitrates[this->qualityHistory[segNum-1]]/(uint64_t)1000);
int currQuality = (int)(this->availableBitrates[quality]/(uint64_t)1000);
qualityDecline = prevQuality - currQuality;
}
std::cout << "stat-qoedecl " << qualityDecline << std::endl;
// 3. Time spent rebuffering
// We just got a new segment so rebuffering has stopped
// If it occurred, we need to know for how long
int rebufferTime = 0;
if (this->rebufferStart != 0) {
if (this->rebufferEnd == 0) {
this->rebufferEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
}
rebufferTime = (int)(this->rebufferEnd - this->rebufferStart);
this->rebufferStart = 0;
}
std::cout << "stat-qoerebuffms " << rebufferTime << std::endl;
// Put it all together for the reward
// The weight of 3 comes from the SIGCOMM paper; they use 3000 because their
// rebufferTime is in seconds, but ours is milliseconds
double reward = (this->qoe_w1*(double)baseQuality) - (this->qoe_w2*(double)qualityDecline) - (this->qoe_w3*(double)rebufferTime*(double)rebufferTime);
this->cumQoE += reward;
std::cout << "stat-qoeseg " << reward << std::endl;
std::cout << "stat-qoecum " << this->cumQoE << std::endl;
}
void BolaAdaptation::CheckedByDASHReceiver ()
{
this->isCheckedForReceiver = false;
}
void BolaAdaptation::BufferUpdate (uint32_t bufferFill)
{
if (bufferFill == (uint32_t)0 && this->rebufferStart == 0) {
this->rebufferStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
this->rebufferEnd = 0;
}
else if (this->rebufferEnd == 0 && this->rebufferStart != 0) {
this->rebufferEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
}
this->SetBitrate(bufferFill);
this->NotifyBitrateChange();
}
| 24,253 | 39.023102 | 262 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/SparseBayesUcbOse.cpp
|
/*
* SparseBayesUcbOse.cpp
* By Trevor Ballard and Bastian Alt, <[email protected]>, <[email protected]>
*
* Adapted from code by Michele Tortelli and Jacques Samain, whose copyright is
* reproduced below.
*
*****************************************************************************
* Copyright (C) 2016
* Michele Tortelli and Jacques Samain, <[email protected]>, <[email protected]>
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "SparseBayesUcbOse.h"
#include <stdio.h>
#include <math.h>
#include <chrono>
#include <string>
#include <stdint.h>
#include <iostream>
#include <sstream>
#include <chrono>
#include <inttypes.h>
#include <stdlib.h>
#include <stdarg.h>
#include <algorithm>
#include <inttypes.h>
#include <time.h>
#include <limits.h>
#include <errno.h>
#include <Python.h>
#include <chrono>
#include <thread>
const double MINIMUM_BUFFER_LEVEL_SPACING = 5.0; // The minimum space required between buffer levels (in seconds).
const uint32_t THROUGHPUT_SAMPLES = 3; // Number of samples considered for throughput estimate.
const double SAFETY_FACTOR = 0.9; // Safety factor used with bandwidth estimate.
static PyObject *pName, *pModule, *pDict, *pFuncChoose, *pFuncUpdate;
static int gil_init = 0;
using namespace dash::mpd;
using namespace libdash::framework::adaptation;
using namespace libdash::framework::input;
using namespace libdash::framework::mpd;
using std::bind;
using std::placeholders::_1;
using std::placeholders::_2;
using duration_in_seconds = std::chrono::duration<double, std::ratio<1, 1> >;
SparseBayesUcbOseAdaptation::SparseBayesUcbOseAdaptation (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6) : AbstractAdaptationLogic (mpd, period, adaptationSet, isVid)
{
// Set SparseBayesUcbOse init STATE
this->initState = true;
this->sparseBayesUcbOseState = STARTUP;
this->lastDownloadTimeInstant = 0.0;
this->currentDownloadTimeInstant = 0.0;
//this->lastSegmentDownloadTime = 0.0;
this->currentQuality = 0;
this->cumQoE = 0.0;
this->bufferMaxSizeSeconds = 20.0; // It is 'bufferMax' in dash.js implementation
// Find a way to retrieve the value without hard coding it
// Set QoE weights
this->qoe_w1 = arg4;
this->qoe_w2 = arg5;
this->qoe_w3 = arg6;
// Set alpha for the EWMA (bw estimate)
this->alphaRate = 0.8;
this->bufferTargetSeconds = 12.0; // 12s (dash.js implementation) corresponds to 40% with a buffer of 30s
/// Retrieve available bitrates
std::vector<IRepresentation* > representations = this->adaptationSet->GetRepresentation();
this->availableBitrates.clear();
//L("SPARSEBAYESUCBOSE Available Bitrates...\n");
for(size_t i = 0; i < representations.size(); i++)
{
this->availableBitrates.push_back((uint64_t)(representations.at(i)->GetBandwidth()));
//L("%d - %I64u bps\n", i+1, this->availableBitrates[i]);
}
// Check if they are in increasing order (i.e., bitrate[0] <= bitrate[1], etc.)
this->bitrateCount = this->availableBitrates.size();
// We check if we have only one birate value or if the bitrate list is irregular (i.e., it is not strictly increasing)
if (this->bitrateCount < 2 || this->availableBitrates[0] >= this->availableBitrates[1] || this->availableBitrates[this->bitrateCount - 2] >= this->availableBitrates[this->bitrateCount - 1]) {
this->sparseBayesUcbOseState = ONE_BITRATE;
// return 0; // Check if exit with a message is necessary
}
// Check if the following is correct
this->totalDuration = TimeResolver::GetDurationInSec(this->mpd->GetMediaPresentationDuration());
//this->segmentDuration = (double) (representations.at(0)->GetSegmentTemplate()->GetDuration() / representations.at(0)->GetSegmentTemplate()->GetTimescale() );
this->segmentDuration = 2.0;
//L("Total Duration - SPARSEBAYESUCBOSE:\t%f\nSegment Duration - SPARSEBAYESUCBOSE:\t%f\n",this->totalDuration, this->segmentDuration);
// if not correct --> segmentDuration = 2.0;
// Compute the SPARSEBAYESUCBOSE Buffer Target
this->sparseBayesUcbOseBufferTargetSeconds = this->bufferTargetSeconds;
if (this->sparseBayesUcbOseBufferTargetSeconds < this->segmentDuration + MINIMUM_BUFFER_LEVEL_SPACING)
{
this->sparseBayesUcbOseBufferTargetSeconds = this->segmentDuration + MINIMUM_BUFFER_LEVEL_SPACING;
}
//L("SPARSEBAYESUCBOSE Buffer Target Seconds:\t%f\n",this->sparseBayesUcbOseBufferTargetSeconds);
// Compute UTILTY vector, Vp, and gp
//L("SPARSEBAYESUCBOSE Utility Values...\n");
double utility_tmp;
for (uint32_t i = 0; i < this->bitrateCount; ++i) {
utility_tmp = log(((double)this->availableBitrates[i] * (1./(double)this->availableBitrates[0])));
if(utility_tmp < 0)
utility_tmp = 0;
this->utilityVector.push_back( log(((double)this->availableBitrates[i] * (1./(double)this->availableBitrates[0]))));
//L("%d - %f\n", i+1, this->utilityVector[i]);
}
this->Vp = (this->sparseBayesUcbOseBufferTargetSeconds - this->segmentDuration) / this->utilityVector[this->bitrateCount - 1];
this->gp = 1.0 + this->utilityVector[this->bitrateCount - 1] / (this->sparseBayesUcbOseBufferTargetSeconds / this->segmentDuration - 1.0);
//L("SPARSEBAYESUCBOSE Parameters:\tVp: %f\tgp: %f\n",this->Vp, this->gp);
/* If bufferTargetSeconds (not sparseBayesUcbOseBufferTargetSecond) is large enough, we might guarantee that SparseBayesUcbOse will never rebuffer
* unless the network bandwidth drops below the lowest encoded bitrate level. For this to work, SparseBayesUcbOse needs to use the real buffer
* level without the additional virtualBuffer. Also, for this to work efficiently, we need to make sure that if the buffer level
* drops to one fragment during a download, the current download does not have more bits remaining than the size of one fragment
* at the lowest quality*/
this->maxRtt = 0.2; // Is this reasonable?
if(this->sparseBayesUcbOseBufferTargetSeconds == this->bufferTargetSeconds) {
this->safetyGuarantee = true;
}
if (this->safetyGuarantee) {
//L("SPARSEBAYESUCBOSE SafetyGuarantee...\n");
// we might need to adjust Vp and gp
double VpNew = this->Vp;
double gpNew = this->gp;
for (uint32_t i = 1; i < this->bitrateCount; ++i) {
double threshold = VpNew * (gpNew - this->availableBitrates[0] * this->utilityVector[i] / (this->availableBitrates[i] - this->availableBitrates[0]));
double minThreshold = this->segmentDuration * (2.0 - this->availableBitrates[0] / this->availableBitrates[i]) + maxRtt;
if (minThreshold >= this->bufferTargetSeconds) {
safetyGuarantee = false;
break;
}
if (threshold < minThreshold) {
VpNew = VpNew * (this->bufferTargetSeconds - minThreshold) / (this->bufferTargetSeconds - threshold);
gpNew = minThreshold / VpNew + this->utilityVector[i] * this->availableBitrates[0] / (this->availableBitrates[i] - this->availableBitrates[0]);
}
}
if (safetyGuarantee && (this->bufferTargetSeconds - this->segmentDuration) * VpNew / this->Vp < MINIMUM_BUFFER_LEVEL_SPACING) {
safetyGuarantee = false;
}
if (safetyGuarantee) {
this->Vp = VpNew;
this->gp = gpNew;
}
}
//L("SPARSEBAYESUCBOSE New Parameters:\tVp: %f\tgp: %f\n",this->Vp, this->gp);
// Capping of the virtual buffer (when using it)
this->sparseBayesUcbOseBufferMaxSeconds = this->Vp * (this->utilityVector[this->bitrateCount - 1] + this->gp);
//L("SPARSEBAYESUCBOSE Max Buffer Seconds:\t%f\n",this->sparseBayesUcbOseBufferMaxSeconds);
this->virtualBuffer = 0.0; // Check if we should use either the virtualBuffer or the safetyGuarantee
this->instantBw = 0;
this->averageBw = 0;
this->batchBw = 0; // Computed every THROUGHPUT_SAMPLES samples (average)
this->batchBwCount = 0;
this->multimediaManager = NULL;
this->lastBufferFill = 0; // (?)
this->bufferEOS = false;
this->shouldAbort = false;
this->isCheckedForReceiver = false;
this->representation = representations.at(0);
this->currentBitrate = (uint64_t) this->representation->GetBandwidth();
this->rebufferStart = 0;
this->rebufferEnd = 0;
Py_Initialize();
PyRun_SimpleString("import sys; sys.path.append('/'); import run_bandits");
pName = PyUnicode_FromString("run_bandits");
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFuncChoose = PyDict_GetItemString(pDict, "choose");
pFuncUpdate = PyDict_GetItemString(pDict, "update");
//L("SPARSEBAYESUCBOSE Init Params - \tAlpha: %f \t BufferTarget: %f\n",this->alphaRate, this->bufferTargetSeconds);
//L("SPARSEBAYESUCBOSE Init Current BitRate - %I64u\n",this->currentBitrate);
Debug("Buffer Adaptation SPARSEBAYESUCBOSE: STARTED\n");
}
SparseBayesUcbOseAdaptation::~SparseBayesUcbOseAdaptation ()
{
Py_DECREF(pModule);
Py_DECREF(pName);
Py_Finalize();
}
LogicType SparseBayesUcbOseAdaptation::GetType ()
{
return adaptation::BufferBased;
}
bool SparseBayesUcbOseAdaptation::IsUserDependent ()
{
return false;
}
bool SparseBayesUcbOseAdaptation::IsRateBased ()
{
return true;
}
bool SparseBayesUcbOseAdaptation::IsBufferBased ()
{
return true;
}
void SparseBayesUcbOseAdaptation::SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager)
{
this->multimediaManager = _mmManager;
}
void SparseBayesUcbOseAdaptation::NotifyBitrateChange ()
{
if(this->multimediaManager)
if(this->multimediaManager->IsStarted() && !this->multimediaManager->IsStopping())
if(this->isVideo)
this->multimediaManager->SetVideoQuality(this->period, this->adaptationSet, this->representation);
else
this->multimediaManager->SetAudioQuality(this->period, this->adaptationSet, this->representation);
//Should Abort is done here to avoid race condition with DASHReceiver::DoBuffering()
if(this->shouldAbort)
{
//L("Aborting! To avoid race condition.");
//printf("Sending Abort request\n");
this->multimediaManager->ShouldAbort(this->isVideo);
//printf("Received Abort request\n");
}
this->shouldAbort = false;
}
uint64_t SparseBayesUcbOseAdaptation::GetBitrate ()
{
return this->currentBitrate;
}
int SparseBayesUcbOseAdaptation::getQualityFromThroughput(uint64_t bps) {
int q = 0;
for (int i = 0; i < this->availableBitrates.size(); ++i) {
if (this->availableBitrates[i] > bps) {
break;
}
q = i;
}
return q;
}
int SparseBayesUcbOseAdaptation::getQualityFromBufferLevel(double bufferLevelSec) {
int quality = this->bitrateCount - 1;
double score = 0.0;
for (int i = 0; i < this->bitrateCount; ++i) {
double s = (this->utilityVector[i] + this->gp - bufferLevelSec / this->Vp) / this->availableBitrates[i];
if (s > score) {
score = s;
quality = i;
}
}
return quality;
}
void SparseBayesUcbOseAdaptation::SetBitrate (uint32_t bufferFill)
{
int result = 0;
PyObject *pArgs, *pValue;
std::vector<IRepresentation*> representations = this->adaptationSet->GetRepresentation();
int numArms = (int)representations.size();
pValue = PyList_New(0);
for (int i=0; i<numArms; i++) {
PyObject* pTemp = PyList_New(0);
// for bufferFill
PyList_Append(pTemp, PyFloat_FromDouble((double)bufferFill/(double)100));
// for RTT
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> rttVec = this->rttMap[i];
for (int j=0; j<rttVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)rttVec[j]));
}
// for num hops
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> numHopsVec = this->numHopsMap[i];
for (int j=0; j<numHopsVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)numHopsVec[j]));
}
PyList_Append(pValue, pTemp);
Py_XDECREF(pTemp);
}
pArgs = PyTuple_New(2);
PyTuple_SetItem(pArgs, 0, PyUnicode_FromString("sbuose"));
PyTuple_SetItem(pArgs, 1, pValue);
if (!gil_init) {
gil_init = 1;
PyEval_InitThreads();
PyEval_SaveThread();
}
// 2: Execute
PyGILState_STATE state = PyGILState_Ensure();
unsigned long long int execStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
pValue = PyObject_CallObject(pFuncChoose, pArgs);
unsigned long long int execEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
result = (int)PyLong_AsLong(pValue);
Py_XDECREF(pArgs);
Py_XDECREF(pValue);
PyGILState_Release(state);
int duration = (int)(execEnd - execStart);
std::cout << "stat-begin" << std::endl;
std::cout << "stat-chexecms " << duration << std::endl;
std::cout << "stat-chqual " << result << std::endl;
if (result < 0 || result > numArms-1) {
std::cout << "ERROR: Result was out of bounds. Using quality of 2." << std::endl;
result = 2;
}
this->currentQuality = result;
this->representation = this->adaptationSet->GetRepresentation().at(this->currentQuality);
this->currentBitrate = (uint64_t) this->availableBitrates[this->currentQuality];
//L("STEADY - Current Bitrate:\t%I64u\n", this->currentBitrate);
//L("ADAPTATION_LOGIC:\tFor %s:\tlast_buffer: %f\tbuffer_level: %f, instantaneousBw: %lu, AverageBW: %lu, choice: %d\n",isVideo ? "video" : "audio",(double)lastBufferFill/100 , (double)bufferFill/100, this->instantBw, this->averageBw , this->currentQuality);
this->lastBufferFill = bufferFill;
}
void SparseBayesUcbOseAdaptation::BitrateUpdate(uint64_t bps)
{
}
void SparseBayesUcbOseAdaptation::SegmentPositionUpdate (uint32_t qualitybps)
{
//L("Called SegmentPositionUpdate\n");
}
void SparseBayesUcbOseAdaptation::DLTimeUpdate (double time)
{
auto m_now = std::chrono::system_clock::now();
auto m_now_sec = std::chrono::time_point_cast<std::chrono::seconds>(m_now);
auto now_value = m_now_sec.time_since_epoch();
double dl_instant = now_value.count();
//this->lastSegmentDownloadTime = time;
//this->currentDownloadTimeInstant = std::chrono::duration_cast<duration_in_seconds>(system_clock::now()).count();
this->currentDownloadTimeInstant = dl_instant;
}
void SparseBayesUcbOseAdaptation::OnEOS (bool value)
{
this->bufferEOS = value;
}
void SparseBayesUcbOseAdaptation::OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec)
{
std::vector<IRepresentation*> representations = this->adaptationSet->GetRepresentation();
int numArms = (int)representations.size();
uint32_t bufferFill = (uint32_t)(bufferFillPct * (double)100);
std::cout << "stat-qual " << quality << std::endl;
//L("stat-buffpct %f\n", bufferFillPct);
////////////////
// Update MAB //
////////////////
// First calculate the real QoE for the segment:
// 1. Base quality (kbps)
// 2. Decline in quality (kbps)
// 3. Time spent rebuffering (ms)
// 1. Base quality
int baseQuality = (int)(this->availableBitrates[quality] / (uint64_t)1000);
std::cout << "stat-qoebase " << baseQuality << std::endl;
// 2. Decline in quality
this->qualityHistory[segNum] = quality;
int qualityDecline = 0;
if (this->qualityHistory[segNum] < this->qualityHistory[segNum-1]) {
int prevQuality = (int)(this->availableBitrates[this->qualityHistory[segNum-1]]/(uint64_t)1000);
int currQuality = (int)(this->availableBitrates[quality]/(uint64_t)1000);
qualityDecline = prevQuality - currQuality;
}
std::cout << "stat-qoedecl " << qualityDecline << std::endl;
// 3. Time spent rebuffering
// We just got a new segment so rebuffering has stopped
// If it occurred, we need to know for how long
int rebufferTime = 0;
if (this->rebufferStart != 0) {
if (this->rebufferEnd == 0) {
this->rebufferEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
}
rebufferTime = (int)(this->rebufferEnd - this->rebufferStart);
this->rebufferStart = 0;
}
std::cout << "stat-qoerebuffms " << rebufferTime << std::endl;
// Put it all together for the reward
// The weight of 3 comes from the SIGCOMM paper; they use 3000 because their
// rebufferTime is in seconds, but ours is milliseconds
double reward = (this->qoe_w1*(double)baseQuality) - (this->qoe_w2*(double)qualityDecline) - (this->qoe_w3*(double)rebufferTime*(double)rebufferTime);
this->cumQoE += reward;
std::cout << "stat-qoeseg " << reward << std::endl;
std::cout << "stat-qoecum " << this->cumQoE << std::endl;
// If we're still in the first K iterations, we have to try all arms. Try the one
// corresponding to this segment
// TODO would be better to put in SetBitrate, but that'd take a bit of refactoring
/*
if (segNum < numArms) {
//L("stat-initarms %d\n", segNum);
this->currentQuality = segNum;
this->representation = this->adaptationSet->GetRepresentation().at(this->currentQuality);
this->currentBitrate = (uint64_t) this->availableBitrates[this->currentQuality];
this->lastBufferFill = bufferFill;
//L("STEADY - Current Bitrate:\t%I64u\n", this->currentBitrate);
this->qualityHistory[segNum] = quality;
this->rttMap[quality] = rttVec;
this->ecnMap[quality] = ecnVec;
this->numHopsMap[quality] = numHopsVec;
this->NotifyBitrateChange();
}
else {
*/
// 1: Build args
int result = 0;
PyObject *pArgs, *pValue;
pValue = PyList_New(0);
for (int i=0; i<numArms; i++) {
PyObject* pTemp = PyList_New(0);
PyList_Append(pTemp, PyFloat_FromDouble(bufferFillPct));
// for RTT
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> tempRttVec = this->rttMap[i];
for (int j=0; j<tempRttVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)tempRttVec[j]));
}
/*
// for ECN
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> tempEcnVec = this->ecnMap[i];
for (int j=0; j<tempEcnVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)tempEcnVec[j]));
}
*/
// for num hops
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> tempNumHopsVec = this->numHopsMap[i];
for (int j=0; j<tempNumHopsVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)tempNumHopsVec[j]));
}
PyList_Append(pValue, pTemp);
Py_XDECREF(pTemp);
}
pArgs = PyTuple_New(5);
PyTuple_SetItem(pArgs, 0, PyUnicode_FromString("sbuose"));
// context
PyTuple_SetItem(pArgs, 1, pValue);
// last quality (action)
PyTuple_SetItem(pArgs, 2, PyLong_FromLong((long)quality));
// reward
PyTuple_SetItem(pArgs, 3, PyFloat_FromDouble(reward));
// timestep
PyTuple_SetItem(pArgs, 4, PyLong_FromLong((long)segNum));
if (!gil_init) {
std::cout << "WARNING: setting gil_init in BitrateUpdate" << std::endl;
gil_init = 1;
PyEval_InitThreads();
PyEval_SaveThread();
}
// 2: Execute
PyGILState_STATE state = PyGILState_Ensure();
unsigned long long int execStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
pValue = PyObject_CallObject(pFuncUpdate, pArgs);
unsigned long long int execEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
result = (int)PyLong_AsLong(pValue);
Py_XDECREF(pArgs);
Py_XDECREF(pValue);
PyGILState_Release(state);
int duration = (int)(execEnd - execStart);
std::cout << "stat-updexecms " << duration << std::endl;
if (result != 1) {
std::cout << "WARNING: Update MAB failed" << std::endl;
}
/////////////////////////////
// Update internal context //
/////////////////////////////
this->rttMap[quality] = rttVec;
//this->ecnMap[quality] = ecnVec;
this->numHopsMap[quality] = numHopsVec;
// Run MAB using the new context
this->SetBitrate(bufferFill);
this->NotifyBitrateChange();
//} <--- the commented out else statement
}
void SparseBayesUcbOseAdaptation::CheckedByDASHReceiver ()
{
//L("CheckedByDASHReceiver called\n");
this->isCheckedForReceiver = false;
}
void SparseBayesUcbOseAdaptation::BufferUpdate (uint32_t bufferFill)
{
if (bufferFill == (uint32_t)0 && this->rebufferStart == 0) {
this->rebufferStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
this->rebufferEnd = 0;
//L("Buffer is at 0; rebuffering has begun and playback has stalled\n");
}
else if (this->rebufferEnd == 0 && this->rebufferStart != 0) {
this->rebufferEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
//L("Stopped rebuffering; resuming playback\n");
}
}
| 22,245 | 39.010791 | 268 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/BufferBasedThreeThresholdAdaptation.cpp
|
/*
* BufferBasedAdaptationWithRateBased.cpp
*****************************************************************************
* Copyright (C) 2016
* Jacques Samain <[email protected]>
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "BufferBasedThreeThresholdAdaptation.h"
#include<stdio.h>
using namespace dash::mpd;
using namespace libdash::framework::adaptation;
using namespace libdash::framework::input;
using namespace libdash::framework::mpd;
BufferBasedThreeThresholdAdaptation::BufferBasedThreeThresholdAdaptation (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6) :
AbstractAdaptationLogic (mpd, period, adaptationSet, isVid)
{
this->slackParam = 0.8;
std::vector<IRepresentation* > representations = this->adaptationSet->GetRepresentation();
if(arg1 >= 0 && arg1 <= 100)
{
this->firstThreshold = arg1;
}
else
this->firstThreshold = 25;
if(arg2)
{
if(arg2 <= 100)
this->secondThreshold = arg2;
else
this->secondThreshold = 50;
}
if(arg3)
{
if(arg3 <= 100 && arg3)
this->thirdThreshold = arg3;
else
this->thirdThreshold = 75;
}
this->representation = this->adaptationSet->GetRepresentation().at(0);
this->multimediaManager = NULL;
this->lastBufferFill = 0;
this->bufferEOS = false;
this->shouldAbort = false;
this->isCheckedForReceiver = false;
L("BufferRateBasedParams:\t%f\t%f\t%f\n",(double)this->firstThreshold/100, (double)secondThreshold/100, (double)thirdThreshold/100);
Debug("Buffer Adaptation: STARTED\n");
}
BufferBasedThreeThresholdAdaptation::~BufferBasedThreeThresholdAdaptation ()
{
}
LogicType BufferBasedThreeThresholdAdaptation::GetType ()
{
return adaptation::BufferBasedThreeThreshold;
}
bool BufferBasedThreeThresholdAdaptation::IsUserDependent ()
{
return false;
}
bool BufferBasedThreeThresholdAdaptation::IsRateBased ()
{
return true;
}
bool BufferBasedThreeThresholdAdaptation::IsBufferBased ()
{
return true;
}
void BufferBasedThreeThresholdAdaptation::SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager)
{
this->multimediaManager = _mmManager;
}
void BufferBasedThreeThresholdAdaptation::NotifyBitrateChange ()
{
if(this->multimediaManager)
if(this->multimediaManager->IsStarted() && !this->multimediaManager->IsStopping())
if(this->isVideo)
this->multimediaManager->SetVideoQuality(this->period, this->adaptationSet, this->representation);
else
this->multimediaManager->SetAudioQuality(this->period, this->adaptationSet, this->representation);
//Should Abort is done here to avoid race condition with DASHReceiver::DoBuffering()
if(this->shouldAbort)
{
//printf("Sending Abort request\n");
this->multimediaManager->ShouldAbort(this->isVideo);
//printf("Received Abort request\n");
}
this->shouldAbort = false;
}
uint64_t BufferBasedThreeThresholdAdaptation::GetBitrate ()
{
return this->currentBitrate;
}
void BufferBasedThreeThresholdAdaptation::SetBitrate (uint32_t bufferFill)
{
uint32_t phi1, phi2;
std::vector<IRepresentation *> representations;
representations = this->adaptationSet->GetRepresentation();
size_t i = 0;
if(this->isCheckedForReceiver)
{
return;
}
this->isCheckedForReceiver = true;
// phi1 = 0;
// while(i < representations.size())
// {
// if(phi1 == 0 && representations.at(i)->GetBandwidth() > slackParam * this->instantBw)
// {
// phi1 = representations.at((i == 0) ? i : i -1)->GetBandwidth();
// }
// i++;
// }
// if(!phi1)
// phi1 = representations.at(representations.size() - 1)->GetBandwidth();
if(bufferFill < this->firstThreshold)
{
this->myQuality = 0;
}
else
{
if(bufferFill < this->secondThreshold)
{
if(this->currentBitrate >= this->instantBw)
{
if(this->myQuality > 0)
{
this->myQuality--;
}
}
}
else
{
if(bufferFill < this->thirdThreshold)
{
}
else
{// bufferLevel > thirdThreshold
if(this->currentBitrate <= this->instantBw)
{
if(this->myQuality < representations.size() - 1)
this->myQuality++;
}
}
}
}
this->representation = representations.at(this->myQuality);
this->currentBitrate = (uint64_t) this->representation->GetBandwidth();
L("ADAPTATION_LOGIC:\tFor %s:\tlast_buffer: %f\tbuffer_level: %f, instantaneousBw: %lu, choice: %d\n",isVideo ? "video" : "audio",(double)lastBufferFill/100 , (double)bufferFill/100, this->instantBw, this->myQuality);
}
void BufferBasedThreeThresholdAdaptation::BitrateUpdate (uint64_t bps)
{
this->instantBw = bps;
}
void BufferBasedThreeThresholdAdaptation::SegmentPositionUpdate (uint32_t qualitybps)
{
}
void BufferBasedThreeThresholdAdaptation::DLTimeUpdate (double time)
{
}
void BufferBasedThreeThresholdAdaptation::OnEOS (bool value)
{
this->bufferEOS = value;
}
void BufferBasedThreeThresholdAdaptation::OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec)
{
}
void BufferBasedThreeThresholdAdaptation::CheckedByDASHReceiver ()
{
this->isCheckedForReceiver = false;
}
void BufferBasedThreeThresholdAdaptation::BufferUpdate (uint32_t bufferFill)
{
this->SetBitrate(bufferFill);
this->NotifyBitrateChange();
}
| 5,523 | 26.89899 | 233 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/SparseBayesUcbOse.h
|
/*
* SparseBayesUcbOse.h
* By Trevor Ballard and Bastian Alt, <[email protected]>, <[email protected]>
*
* Adapted from code by Michele Tortelli and Jacques Samain, whose copyright is
* reproduced below.
*
*****************************************************************************
* Copyright (C) 2016,
* Michele Tortelli and Jacques Samain, <[email protected]>, <[email protected]>
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_SPARSEBAYESUCBOSE_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_SPARSEBAYESUCBOSE_H_
#include "AbstractAdaptationLogic.h"
#include "../MPD/AdaptationSetStream.h"
#include "../Input/IDASHReceiverObserver.h"
namespace libdash
{
namespace framework
{
namespace adaptation
{
class SparseBayesUcbOseAdaptation : public AbstractAdaptationLogic
{
public:
SparseBayesUcbOseAdaptation (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6);
virtual ~SparseBayesUcbOseAdaptation();
virtual LogicType GetType ();
virtual bool IsUserDependent ();
virtual bool IsRateBased ();
virtual bool IsBufferBased ();
virtual void BitrateUpdate(uint64_t bps);
virtual void SegmentPositionUpdate(uint32_t qualitybps);
virtual void DLTimeUpdate (double time);
virtual void BufferUpdate (uint32_t bufferFill);
void SetBitrate (uint32_t bufferFill);
uint64_t GetBitrate ();
virtual void SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager);
void NotifyBitrateChange ();
void OnEOS (bool value);
virtual void OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec);
void CheckedByDASHReceiver();
int getQualityFromThroughput(uint64_t bps);
int getQualityFromBufferLevel(double bufferLevelSec);
private:
enum SparseBayesUcbOseState
{
ONE_BITRATE, // If one bitrate (or init failed), always NO_CHANGE
STARTUP, // Download fragments at most recently measured throughput
STARTUP_NO_INC, // If quality increased then decreased during startup, then quality cannot be increased.
STEADY // The buffer is primed (should be above bufferTarget)
};
bool initState;
double bufferMaxSizeSeconds; // Usually set to 30s
double bufferTargetSeconds; // It is passed as an init parameter.
// It states the difference between STARTUP and STEADY
// 12s following dash.js implementation
double sparseBayesUcbOseBufferTargetSeconds; // SPARSEBAYESUCBOSE introduces a virtual buffer level in order to make quality decisions
// as it was filled (instead of the actual bufferTargetSeconds)
double sparseBayesUcbOseBufferMaxSeconds; // When using the virtual buffer, it must be capped.
uint32_t bufferTargetPerc; // Computed considering a bufferSize = 30s
double totalDuration; // Total video duration in seconds (taken from MPD)
double segmentDuration; // Segment duration in seconds
std::vector<uint64_t> availableBitrates;
std::vector<double> utilityVector;
uint32_t bitrateCount; // Number of available bitrates
SparseBayesUcbOseState sparseBayesUcbOseState; // Keeps track of SparseBayesUcbOse state
// SparseBayesUcbOse Vp and gp (multiplied by the segment duration 'p')
// They are dimensioned such that log utility would always prefer
// - the lowest bitrate when bufferLevel = segmentDuration
// - the highest bitrate when bufferLevel = bufferTarget
double Vp;
double gp;
bool safetyGuarantee;
double maxRtt;
double virtualBuffer;
uint64_t currentBitrate;
int currentQuality;
uint64_t batchBw;
int batchBwCount;
std::vector<uint64_t> batchBwSamples;
uint64_t instantBw;
uint64_t averageBw;
double lastDownloadTimeInstant;
double currentDownloadTimeInstant;
double lastSegmentDownloadTime;
uint32_t lastBufferFill;
bool bufferEOS;
bool shouldAbort;
double alphaRate;
bool isCheckedForReceiver;
sampleplayer::managers::IMultimediaManagerBase *multimediaManager;
dash::mpd::IRepresentation *representation;
std::map<int, std::vector<int>> rttMap;
std::map<int, std::vector<int>> ecnMap;
std::map<int, std::vector<int>> numHopsMap;
std::map<int, int> qualityHistory;
unsigned long long int rebufferStart;
unsigned long long int rebufferEnd;
double cumQoE;
double qoe_w1;
double qoe_w2;
double qoe_w3;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_SPARSEBAYESUCBOSE_H_ */
| 6,534 | 57.348214 | 235 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/SparseBayesUcbSvi.h
|
/*
* SparseBayesUcbSvi.h
* By Trevor Ballard and Bastian Alt, <[email protected]>, <[email protected]>
*
* Adapted from code by Michele Tortelli and Jacques Samain, whose copyright is
* reproduced below.
*
*****************************************************************************
* Copyright (C) 2016,
* Michele Tortelli and Jacques Samain, <[email protected]>, <[email protected]>
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_SPARSEBAYESUCBSVI_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_SPARSEBAYESUCBSVI_H_
#include "AbstractAdaptationLogic.h"
#include "../MPD/AdaptationSetStream.h"
#include "../Input/IDASHReceiverObserver.h"
namespace libdash
{
namespace framework
{
namespace adaptation
{
class SparseBayesUcbSviAdaptation : public AbstractAdaptationLogic
{
public:
SparseBayesUcbSviAdaptation (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6);
virtual ~SparseBayesUcbSviAdaptation();
virtual LogicType GetType ();
virtual bool IsUserDependent ();
virtual bool IsRateBased ();
virtual bool IsBufferBased ();
virtual void BitrateUpdate(uint64_t bps);
virtual void SegmentPositionUpdate(uint32_t qualitybps);
virtual void DLTimeUpdate (double time);
virtual void BufferUpdate (uint32_t bufferFill);
void SetBitrate (uint32_t bufferFill);
uint64_t GetBitrate ();
virtual void SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager);
void NotifyBitrateChange ();
void OnEOS (bool value);
virtual void OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec);
void CheckedByDASHReceiver();
int getQualityFromThroughput(uint64_t bps);
int getQualityFromBufferLevel(double bufferLevelSec);
private:
enum SparseBayesUcbSviState
{
ONE_BITRATE, // If one bitrate (or init failed), always NO_CHANGE
STARTUP, // Download fragments at most recently measured throughput
STARTUP_NO_INC, // If quality increased then decreased during startup, then quality cannot be increased.
STEADY // The buffer is primed (should be above bufferTarget)
};
bool initState;
double bufferMaxSizeSeconds; // Usually set to 30s
double bufferTargetSeconds; // It is passed as an init parameter.
// It states the difference between STARTUP and STEADY
// 12s following dash.js implementation
double sparseBayesUcbSviBufferTargetSeconds; // SPARSEBAYESUCBSVI introduces a virtual buffer level in order to make quality decisions
// as it was filled (instead of the actual bufferTargetSeconds)
double sparseBayesUcbSviBufferMaxSeconds; // When using the virtual buffer, it must be capped.
uint32_t bufferTargetPerc; // Computed considering a bufferSize = 30s
double totalDuration; // Total video duration in seconds (taken from MPD)
double segmentDuration; // Segment duration in seconds
std::vector<uint64_t> availableBitrates;
std::vector<double> utilityVector;
uint32_t bitrateCount; // Number of available bitrates
SparseBayesUcbSviState sparseBayesUcbSviState; // Keeps track of SparseBayesUcbSvi state
// SparseBayesUcbSvi Vp and gp (multiplied by the segment duration 'p')
// They are dimensioned such that log utility would always prefer
// - the lowest bitrate when bufferLevel = segmentDuration
// - the highest bitrate when bufferLevel = bufferTarget
double Vp;
double gp;
bool safetyGuarantee;
double maxRtt;
double virtualBuffer;
uint64_t currentBitrate;
int currentQuality;
uint64_t batchBw;
int batchBwCount;
std::vector<uint64_t> batchBwSamples;
uint64_t instantBw;
uint64_t averageBw;
double lastDownloadTimeInstant;
double currentDownloadTimeInstant;
double lastSegmentDownloadTime;
uint32_t lastBufferFill;
bool bufferEOS;
bool shouldAbort;
double alphaRate;
bool isCheckedForReceiver;
sampleplayer::managers::IMultimediaManagerBase *multimediaManager;
dash::mpd::IRepresentation *representation;
std::map<int, std::vector<int>> rttMap;
std::map<int, std::vector<int>> ecnMap;
std::map<int, std::vector<int>> numHopsMap;
std::map<int, int> qualityHistory;
unsigned long long int rebufferStart;
unsigned long long int rebufferEnd;
double cumQoE;
double qoe_w1;
double qoe_w2;
double qoe_w3;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_SPARSEBAYESUCBSVI_H_ */
| 6,534 | 57.348214 | 235 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/BufferBasedThreeThresholdAdaptation.h
|
/*
* RateBasedAdaptation.h
*****************************************************************************
* Copyright (C) 2016,
* Jacques Samain <[email protected]>
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_BUFFERBASEDADAPTATIONTHREE_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_BUFFERBASEDADAPTATIONTHREE_H_
#include "AbstractAdaptationLogic.h"
#include "../MPD/AdaptationSetStream.h"
#include "../Input/IDASHReceiverObserver.h"
namespace libdash
{
namespace framework
{
namespace adaptation
{
class BufferBasedThreeThresholdAdaptation : public AbstractAdaptationLogic
{
public:
BufferBasedThreeThresholdAdaptation (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6);
virtual ~BufferBasedThreeThresholdAdaptation ();
virtual LogicType GetType ();
virtual bool IsUserDependent ();
virtual bool IsRateBased ();
virtual bool IsBufferBased ();
virtual void BitrateUpdate (uint64_t bps);
virtual void SegmentPositionUpdate(uint32_t qualitybps);
virtual void DLTimeUpdate (double time);
virtual void BufferUpdate (uint32_t bufferFill);
void SetBitrate (uint32_t bufferFill);
uint64_t GetBitrate ();
virtual void SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager);
void NotifyBitrateChange ();
void OnEOS (bool value);
virtual void OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec);
void CheckedByDASHReceiver();
private:
uint64_t currentBitrate;
std::vector<uint64_t> availableBitrates;
sampleplayer::managers::IMultimediaManagerBase *multimediaManager;
dash::mpd::IRepresentation *representation;
uint32_t secondThreshold;
uint32_t thirdThreshold;
uint32_t lastBufferFill;
bool bufferEOS;
bool shouldAbort;
uint32_t firstThreshold;
uint64_t instantBw;
int myQuality;
double slackParam;
bool isCheckedForReceiver;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_BUFFERBASEDADAPTATIONTHREE_H_ */
| 3,168 | 46.298507 | 243 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/AdaptationLogicFactory.h
|
/*
* AdaptationLogicFactory.h
*****************************************************************************
* Copyright (C) 2013, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_ADAPTATIONLOGICFACTORY_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_ADAPTATIONLOGICFACTORY_H_
#include "IAdaptationLogic.h"
#include "AlwaysLowestLogic.h"
#include "ManualAdaptation.h"
#include "RateBasedAdaptation.h"
#include "BufferBasedAdaptation.h"
#include "BufferBasedAdaptationWithRateBased.h"
#include "BufferBasedThreeThresholdAdaptation.h"
#include "Panda.h"
#include "FOOBAR.h"
#include "Bola.h"
#include "SparseBayesUcb.h"
#include "SparseBayesUcbOse.h"
#include "SparseBayesUcbSvi.h"
#include "LinUcb.h"
namespace libdash
{
namespace framework
{
namespace adaptation
{
class AdaptationLogicFactory
{
public:
static IAdaptationLogic* Create(libdash::framework::adaptation::LogicType logic,
dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, bool isVid,
double arg1 = 0., double arg2=0, double arg3=0, double arg4=0, double arg5=0, double arg6=0);
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_ADAPTATIONLOGICFACTORY_H_ */
| 1,669 | 33.791667 | 156 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/IAdaptationLogic.h
|
/*
* IAdaptationLogic.h
*****************************************************************************
* Copyright (C) 2013, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_IADAPTATIONLOGIC_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_IADAPTATIONLOGIC_H_
#include "../Input/MediaObject.h"
#include "../Input/DASHReceiver.h"
#include "IRepresentation.h"
#include "../../Managers/IMultimediaManagerBase.h"
#include "log/log.h"
namespace libdash
{
namespace framework
{
namespace input
{
class DASHReceiver;
}
namespace adaptation
{
//#define START __LINE__
//ADAPTATIONLOGIC Count is an hack to have the number of adaptation logic that we can use
#define FOREACH_ADAPTATIONLOGIC(ADAPTATIONLOGIC) \
ADAPTATIONLOGIC(Manual) \
ADAPTATIONLOGIC(AlwaysLowest) \
ADAPTATIONLOGIC(RateBased) \
ADAPTATIONLOGIC(BufferBased) \
ADAPTATIONLOGIC(BufferRateBased) \
ADAPTATIONLOGIC(BufferBasedThreeThreshold) \
ADAPTATIONLOGIC(Panda) \
ADAPTATIONLOGIC(FOOBAR) \
ADAPTATIONLOGIC(Bola) \
ADAPTATIONLOGIC(SparseBayesUcb) \
ADAPTATIONLOGIC(SparseBayesUcbOse) \
ADAPTATIONLOGIC(SparseBayesUcbSvi) \
ADAPTATIONLOGIC(LinUcb) \
ADAPTATIONLOGIC(Count) \
// #define NUMBER_OF_LOGICS __LINE__-START-1
#define GENERATE_ENUM(ENUM) ENUM,
#define GENERATE_STRING(STRING) #STRING,
enum LogicType {
FOREACH_ADAPTATIONLOGIC(GENERATE_ENUM)
};
static const char *LogicType_string[] = {
FOREACH_ADAPTATIONLOGIC(GENERATE_STRING)
};
// enum LogicType
// {
// Manual,
// AlwaysLowest
// };
class IAdaptationLogic
{
public:
virtual ~IAdaptationLogic () {}
virtual uint32_t GetPosition () = 0;
virtual void SetPosition (uint32_t segmentNumber) = 0;
virtual dash::mpd::IRepresentation* GetRepresentation () = 0;
virtual void SetRepresentation (dash::mpd::IPeriod *period,
dash::mpd::IAdaptationSet *adaptationSet,
dash::mpd::IRepresentation *representation) = 0;
virtual LogicType GetType () = 0;
virtual bool IsUserDependent () = 0;
virtual void BitrateUpdate (uint64_t bps) = 0;
virtual void SegmentPositionUpdate (uint32_t qualitybps) = 0;
virtual void DLTimeUpdate (double time) = 0;
virtual void BufferUpdate (uint32_t bufferfillstate) = 0;
virtual bool IsRateBased () = 0;
virtual bool IsBufferBased () = 0;
virtual void SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *mmManager) = 0;
virtual void OnEOS (bool value) = 0;
virtual void OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec) = 0;
virtual void CheckedByDASHReceiver() = 0;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_IADAPTATIONLOGIC_H_ */
| 4,145 | 42.1875 | 182 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/BufferBasedAdaptationWithRateBased.cpp
|
/*
* BufferBasedAdaptationWithRateBased.cpp
*****************************************************************************
* Copyright (C) 2016
* Jacques Samain <[email protected]>
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "BufferBasedAdaptationWithRateBased.h"
#include<stdio.h>
using namespace dash::mpd;
using namespace libdash::framework::adaptation;
using namespace libdash::framework::input;
using namespace libdash::framework::mpd;
BufferBasedAdaptationWithRateBased::BufferBasedAdaptationWithRateBased (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6) :
AbstractAdaptationLogic (mpd, period, adaptationSet, isVid)
{
this->slackParam = 0.8;
std::vector<IRepresentation* > representations = this->adaptationSet->GetRepresentation();
if(arg1 >= 0 && arg1 <= 1)
{
this->alphaRate = arg1;
}
else
this->alphaRate = 0.8;
if(arg2)
{
if(arg2 <= 100)
this->reservoirThreshold = arg2;
else
this->reservoirThreshold = 25;
}
if(arg3)
{
if(arg3 <= 100 && arg3)
this->maxThreshold = arg3;
else
this->maxThreshold = 100;
}
this->m_count = 0;
//this->switchUpThreshold = 15;
this->switchUpThreshold = 5;
this->instantBw = 0;
this->averageBw = 0;
this->representation = this->adaptationSet->GetRepresentation().at(0);
this->multimediaManager = NULL;
this->lastBufferFill = 0;
this->bufferEOS = false;
this->shouldAbort = false;
this->isCheckedForReceiver = false;
L("BufferRateBasedParams:\talpha:%f\t%f\t%f\n",this->alphaRate, (double)reservoirThreshold/100, (double)maxThreshold/100);
Debug("Buffer Adaptation: STARTED\n");
}
BufferBasedAdaptationWithRateBased::~BufferBasedAdaptationWithRateBased ()
{
}
LogicType BufferBasedAdaptationWithRateBased::GetType ()
{
return adaptation::BufferBased;
}
bool BufferBasedAdaptationWithRateBased::IsUserDependent ()
{
return false;
}
bool BufferBasedAdaptationWithRateBased::IsRateBased ()
{
return true;
}
bool BufferBasedAdaptationWithRateBased::IsBufferBased ()
{
return true;
}
void BufferBasedAdaptationWithRateBased::SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager)
{
this->multimediaManager = _mmManager;
}
void BufferBasedAdaptationWithRateBased::NotifyBitrateChange ()
{
if(this->multimediaManager)
if(this->multimediaManager->IsStarted() && !this->multimediaManager->IsStopping())
if(this->isVideo)
this->multimediaManager->SetVideoQuality(this->period, this->adaptationSet, this->representation);
else
this->multimediaManager->SetAudioQuality(this->period, this->adaptationSet, this->representation);
//Should Abort is done here to avoid race condition with DASHReceiver::DoBuffering()
if(this->shouldAbort)
{
//printf("Sending Abort request\n");
this->multimediaManager->ShouldAbort(this->isVideo);
//printf("Received Abort request\n");
}
this->shouldAbort = false;
}
uint64_t BufferBasedAdaptationWithRateBased::GetBitrate ()
{
return this->currentBitrate;
}
void BufferBasedAdaptationWithRateBased::SetBitrate (uint32_t bufferFill)
{
uint32_t phi1, phi2;
std::vector<IRepresentation *> representations;
representations = this->adaptationSet->GetRepresentation();
size_t i = 0;
// if(this->isCheckedForReceiver)
// {
// return;
// }
// this->isCheckedForReceiver = true;
phi1 = 0;
phi2 = 0;
while(i < representations.size())
{
if(phi1 == 0 && representations.at(i)->GetBandwidth() > slackParam * this->instantBw)
{
phi1 = representations.at((i == 0) ? i : i -1)->GetBandwidth();
}
if(phi2 == 0 && representations.at(i)->GetBandwidth() > slackParam * this->averageBw)
{
phi2 = representations.at((i == 0) ? i : i -1)->GetBandwidth();
}
i++;
}
if(!phi1)
phi1 = representations.at(representations.size() - 1)->GetBandwidth();
if(!phi2)
phi2 = representations.at(representations.size() - 1)->GetBandwidth();
if(bufferFill < this->reservoirThreshold)
{
this->m_count = 0;
this->myQuality = 0;
}
else
{
if(bufferFill < this->maxThreshold)
{
this->m_count = 0;
if(this->currentBitrate > phi1)
{
if(this->myQuality > 0)
{
this->myQuality--;
}
}
else
{
if(this->currentBitrate < phi1)
{
if(this->myQuality < representations.size() - 1)
{
this->myQuality++;
}
}
}
}
else
{ // bufferFill > this->maxThreshold
if(this->currentBitrate < phi2)
{
m_count++;
if(m_count >= switchUpThreshold && this->myQuality < representations.size() - 1)
{
this->m_count = 0;
this->myQuality++;
}
}
}
}
this->representation = representations.at(this->myQuality);
this->currentBitrate = (uint64_t) this->representation->GetBandwidth();
L("ADAPTATION_LOGIC:\tFor %s:\tlast_buffer: %f\tbuffer_level: %f, instantaneousBw: %lu, AverageBW: %lu, choice: %d\n",isVideo ? "video" : "audio",(double)lastBufferFill/100 , (double)bufferFill/100, this->instantBw, this->averageBw , this->myQuality);
}
void BufferBasedAdaptationWithRateBased::BitrateUpdate (uint64_t bps)
{
this->instantBw = bps;
if(this->averageBw == 0)
{
this->averageBw = bps;
}
else
{
this->averageBw = this->alphaRate*this->averageBw + (1 - this->alphaRate)*bps;
}
}
void BufferBasedAdaptationWithRateBased::SegmentPositionUpdate (uint32_t qualitybps)
{
}
void BufferBasedAdaptationWithRateBased::DLTimeUpdate (double time)
{
}
void BufferBasedAdaptationWithRateBased::OnEOS (bool value)
{
this->bufferEOS = value;
}
void BufferBasedAdaptationWithRateBased::OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec)
{
}
void BufferBasedAdaptationWithRateBased::CheckedByDASHReceiver ()
{
this->isCheckedForReceiver = false;
}
void BufferBasedAdaptationWithRateBased::BufferUpdate (uint32_t bufferFill)
{
this->SetBitrate(bufferFill);
this->NotifyBitrateChange();
}
| 6,220 | 26.285088 | 252 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/BufferBasedAdaptation.cpp
|
/*
* BufferBasedAdaptation.cpp
*****************************************************************************
* Copyright (C) 2016
* Jacques Samain <[email protected]>
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "BufferBasedAdaptation.h"
#include<stdio.h>
using namespace dash::mpd;
using namespace libdash::framework::adaptation;
using namespace libdash::framework::input;
using namespace libdash::framework::mpd;
BufferBasedAdaptation::BufferBasedAdaptation (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6) :
AbstractAdaptationLogic (mpd, period, adaptationSet, isVid)
{
std::vector<IRepresentation* > representations = this->adaptationSet->GetRepresentation();
if(arg1)
{
if(arg1 != 0 && arg1 >= 100)
this->reservoirThreshold = arg1;
else
this->reservoirThreshold = 25;
}
else
this->reservoirThreshold = 25;
if(arg2)
{
if(arg2 <=100 && arg2 >= arg1)
this->maxThreshold = arg2;
else
this->maxThreshold = 75;
}
else
this->maxThreshold = 75;
this->representation = this->adaptationSet->GetRepresentation().at(0);
this->multimediaManager = NULL;
this->lastBufferFill = 0;
this->bufferEOS = false;
this->shouldAbort = false;
L("BufferBasedParams:\t%f\t%f\n", (double)reservoirThreshold/100, (double)maxThreshold/100);
Debug("Buffer Adaptation: STARTED\n");
}
BufferBasedAdaptation::~BufferBasedAdaptation ()
{
}
LogicType BufferBasedAdaptation::GetType ()
{
return adaptation::BufferBased;
}
bool BufferBasedAdaptation::IsUserDependent ()
{
return false;
}
bool BufferBasedAdaptation::IsRateBased ()
{
return false;
}
bool BufferBasedAdaptation::IsBufferBased ()
{
return true;
}
void BufferBasedAdaptation::SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager)
{
this->multimediaManager = _mmManager;
}
void BufferBasedAdaptation::NotifyBitrateChange ()
{
if(this->multimediaManager)
if(this->multimediaManager->IsStarted() && !this->multimediaManager->IsStopping())
if(this->isVideo)
this->multimediaManager->SetVideoQuality(this->period, this->adaptationSet, this->representation);
else
this->multimediaManager->SetAudioQuality(this->period, this->adaptationSet, this->representation);
//Should Abort is done here to avoid race condition with DASHReceiver::DoBuffering()
if(this->shouldAbort)
{
//printf("Sending Abort request\n");
this->multimediaManager->ShouldAbort(this->isVideo);
//printf("Received Abort request\n");
}
this->shouldAbort = false;
}
uint64_t BufferBasedAdaptation::GetBitrate ()
{
return this->currentBitrate;
}
void BufferBasedAdaptation::SetBitrate (uint32_t bufferFill)
{
std::vector<IRepresentation *> representations;
representations = this->adaptationSet->GetRepresentation();
size_t i = 0;
if(representations.size() == 1)
{
i = 0;
}
else
{
while(bufferFill > this->reservoirThreshold + i * (this->maxThreshold - this->reservoirThreshold)/(representations.size()-1))
{
i++;
}
}
if((size_t)i >= (size_t)(representations.size()))
i = representations.size() - 1;
this->representation = representations.at(i);
if( 0 && !this->bufferEOS && this->lastBufferFill > this->reservoirThreshold && bufferFill <= this->reservoirThreshold)
{
this->shouldAbort = true;
}
L("ADAPTATION_LOGIC:\tFor %s:\tlast_buffer: %f\tbuffer_level: %f, choice: %lu, should_trigger_abort: %s\n",isVideo ? "video" : "audio",(double)lastBufferFill/100 , (double)bufferFill/100, i, this->shouldAbort ? "YES" : "NO");
this->lastBufferFill = bufferFill;
}
void BufferBasedAdaptation::BitrateUpdate (uint64_t bps)
{
}
void BufferBasedAdaptation::SegmentPositionUpdate (uint32_t qualitybps)
{
}
void BufferBasedAdaptation::DLTimeUpdate (double time)
{
}
void BufferBasedAdaptation::OnEOS (bool value)
{
this->bufferEOS = value;
}
void BufferBasedAdaptation::OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec)
{
}
void BufferBasedAdaptation::CheckedByDASHReceiver()
{
}
void BufferBasedAdaptation::BufferUpdate (uint32_t bufferFill)
{
this->SetBitrate(bufferFill);
this->NotifyBitrateChange();
}
| 4,505 | 27.339623 | 226 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/LinUcb.h
|
/*
* LinUcb.h
* By Trevor Ballard and Bastian Alt, <[email protected]>, <[email protected]>
*
* Adapted from code by Michele Tortelli and Jacques Samain, whose copyright is
* reproduced below.
*
*****************************************************************************
* Copyright (C) 2016,
* Michele Tortelli and Jacques Samain, <[email protected]>, <[email protected]>
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_LINUCB_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_LINUCB_H_
#include "AbstractAdaptationLogic.h"
#include "../MPD/AdaptationSetStream.h"
#include "../Input/IDASHReceiverObserver.h"
namespace libdash
{
namespace framework
{
namespace adaptation
{
class LinUcbAdaptation : public AbstractAdaptationLogic
{
public:
LinUcbAdaptation (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, bool isVid,
double arg1, double arg2, double arg3, double arg4, double arg5, double arg6);
virtual ~LinUcbAdaptation();
virtual LogicType GetType ();
virtual bool IsUserDependent ();
virtual bool IsRateBased ();
virtual bool IsBufferBased ();
virtual void BitrateUpdate(uint64_t bps);
virtual void SegmentPositionUpdate(uint32_t qualitybps);
virtual void DLTimeUpdate (double time);
virtual void BufferUpdate (uint32_t bufferFill);
void SetBitrate (uint32_t bufferFill);
uint64_t GetBitrate ();
virtual void SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager);
void NotifyBitrateChange ();
void OnEOS (bool value);
virtual void OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec);
void CheckedByDASHReceiver();
int getQualityFromThroughput(uint64_t bps);
int getQualityFromBufferLevel(double bufferLevelSec);
private:
enum LinUcbState
{
ONE_BITRATE, // If one bitrate (or init failed), always NO_CHANGE
STARTUP, // Download fragments at most recently measured throughput
STARTUP_NO_INC, // If quality increased then decreased during startup, then quality cannot be increased.
STEADY // The buffer is primed (should be above bufferTarget)
};
bool initState;
double bufferMaxSizeSeconds; // Usually set to 30s
double bufferTargetSeconds; // It is passed as an init parameter.
// It states the difference between STARTUP and STEADY
// 12s following dash.js implementation
double linUcbBufferTargetSeconds; // LINUCB introduces a virtual buffer level in order to make quality decisions
// as it was filled (instead of the actual bufferTargetSeconds)
double linUcbBufferMaxSeconds; // When using the virtual buffer, it must be capped.
uint32_t bufferTargetPerc; // Computed considering a bufferSize = 30s
double totalDuration; // Total video duration in seconds (taken from MPD)
double segmentDuration; // Segment duration in seconds
std::vector<uint64_t> availableBitrates;
std::vector<double> utilityVector;
uint32_t bitrateCount; // Number of available bitrates
LinUcbState linUcbState; // Keeps track of LinUcb state
// LinUcb Vp and gp (multiplied by the segment duration 'p')
// They are dimensioned such that log utility would always prefer
// - the lowest bitrate when bufferLevel = segmentDuration
// - the highest bitrate when bufferLevel = bufferTarget
double Vp;
double gp;
bool safetyGuarantee;
double maxRtt;
double virtualBuffer;
uint64_t currentBitrate;
int currentQuality;
uint64_t batchBw;
int batchBwCount;
std::vector<uint64_t> batchBwSamples;
uint64_t instantBw;
uint64_t averageBw;
double lastDownloadTimeInstant;
double currentDownloadTimeInstant;
double lastSegmentDownloadTime;
uint32_t lastBufferFill;
bool bufferEOS;
bool shouldAbort;
double alphaRate;
bool isCheckedForReceiver;
sampleplayer::managers::IMultimediaManagerBase *multimediaManager;
dash::mpd::IRepresentation *representation;
std::map<int, std::vector<int>> rttMap;
std::map<int, std::vector<int>> ecnMap;
std::map<int, std::vector<int>> numHopsMap;
std::map<int, int> qualityHistory;
unsigned long long int rebufferStart;
unsigned long long int rebufferEnd;
double cumQoE;
double qoe_w1;
double qoe_w2;
double qoe_w3;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_LINUCB_H_ */
| 6,415 | 55.778761 | 174 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/AdaptationLogicFactory.cpp
|
/*
* AdaptationLogicFactory.cpp
*****************************************************************************
* Copyright (C) 2013, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "AdaptationLogicFactory.h"
#include<stdio.h>
using namespace libdash::framework::adaptation;
using namespace dash::mpd;
IAdaptationLogic* AdaptationLogicFactory::Create(LogicType logic, IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet,bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6)
{
Debug("Adaptation Logic for %s: ", isVid ? "video" : "audio");
switch(logic)
{
case Manual:
{
Debug("Manual\n");
return new ManualAdaptation (mpd, period, adaptationSet, isVid);
}
case AlwaysLowest:
{
Debug("Always lowest\n");
return new AlwaysLowestLogic (mpd, period, adaptationSet, isVid);
}
case RateBased:
{
Debug("Rate based\n");
return new RateBasedAdaptation (mpd,period,adaptationSet, isVid, arg1);
}
case BufferBased:
{
Debug("Buffer based\n");
return new BufferBasedAdaptation (mpd,period,adaptationSet, isVid, arg1, arg2, arg3, arg4, arg5, arg6);
}
case BufferRateBased:
{
Debug("Buffer Rate based\n");
return new BufferBasedAdaptationWithRateBased (mpd,period,adaptationSet, isVid, arg1, arg2, arg3, arg4, arg5, arg6);
}
case BufferBasedThreeThreshold:
{
Debug("Buffer based 3 threshold\n");
return new BufferBasedThreeThresholdAdaptation (mpd,period,adaptationSet, isVid, arg1, arg2, arg3, arg4, arg5, arg6);
}
case Panda:
{
Debug("Panda\n");
return new PandaAdaptation(mpd, period, adaptationSet, isVid, arg1, arg2, arg3, arg4, arg5, arg6);
}
case FOOBAR:
{
Debug("FOOBAR\n");
return new FOOBARAdaptation(mpd, period, adaptationSet, isVid, arg1, arg2, arg3, arg4, arg5, arg6);
}
case Bola:
{
Debug("Bola\n");
return new BolaAdaptation(mpd, period, adaptationSet, isVid, arg1, arg2, arg3, arg4, arg5, arg6);
}
case SparseBayesUcb:
{
Debug("Sparse Bayes UCB\n");
return new SparseBayesUcbAdaptation(mpd, period, adaptationSet, isVid, arg1, arg2, arg3, arg4, arg5, arg6);
}
case SparseBayesUcbOse:
{
Debug("Sparse Bayes UCB OSE\n");
return new SparseBayesUcbOseAdaptation(mpd, period, adaptationSet, isVid, arg1, arg2, arg3, arg4, arg5, arg6);
}
case SparseBayesUcbSvi:
{
Debug("Sparse Bayes UCB SVI\n");
return new SparseBayesUcbSviAdaptation(mpd, period, adaptationSet, isVid, arg1, arg2, arg3, arg4, arg5, arg6);
}
case LinUcb:
{
Debug("LinUCB\n");
return new LinUcbAdaptation(mpd, period, adaptationSet, isVid, arg1, arg2, arg3, arg4, arg5, arg6);
}
default:
{
Debug("default => return Manual\n");
return new ManualAdaptation (mpd, period, adaptationSet, isVid);
}
} }
| 3,476 | 35.989362 | 213 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/SparseBayesUcb.h
|
/*
* SparseBayesUcb.h
* By Trevor Ballard and Bastian Alt, <[email protected]>, <[email protected]>
*
* Adapted from code by Michele Tortelli and Jacques Samain, whose copyright is
* reproduced below.
*
*****************************************************************************
* Copyright (C) 2016,
* Michele Tortelli and Jacques Samain, <[email protected]>, <[email protected]>
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_SPARSEBAYESUCB_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_SPARSEBAYESUCB_H_
#include "AbstractAdaptationLogic.h"
#include "../MPD/AdaptationSetStream.h"
#include "../Input/IDASHReceiverObserver.h"
namespace libdash
{
namespace framework
{
namespace adaptation
{
class SparseBayesUcbAdaptation : public AbstractAdaptationLogic
{
public:
SparseBayesUcbAdaptation (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6);
virtual ~SparseBayesUcbAdaptation();
virtual LogicType GetType ();
virtual bool IsUserDependent ();
virtual bool IsRateBased ();
virtual bool IsBufferBased ();
virtual void BitrateUpdate(uint64_t bps);
virtual void SegmentPositionUpdate(uint32_t qualitybps);
virtual void DLTimeUpdate (double time);
virtual void BufferUpdate (uint32_t bufferFill);
void SetBitrate (uint32_t bufferFill);
uint64_t GetBitrate ();
virtual void SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager);
void NotifyBitrateChange ();
void OnEOS (bool value);
virtual void OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec);
void CheckedByDASHReceiver();
int getQualityFromThroughput(uint64_t bps);
int getQualityFromBufferLevel(double bufferLevelSec);
private:
enum SparseBayesUcbState
{
ONE_BITRATE, // If one bitrate (or init failed), always NO_CHANGE
STARTUP, // Download fragments at most recently measured throughput
STARTUP_NO_INC, // If quality increased then decreased during startup, then quality cannot be increased.
STEADY // The buffer is primed (should be above bufferTarget)
};
bool initState;
double bufferMaxSizeSeconds; // Usually set to 30s
double bufferTargetSeconds; // It is passed as an init parameter.
// It states the difference between STARTUP and STEADY
// 12s following dash.js implementation
double sparseBayesUcbBufferTargetSeconds; // SPARSEBAYESUCB introduces a virtual buffer level in order to make quality decisions
// as it was filled (instead of the actual bufferTargetSeconds)
double sparseBayesUcbBufferMaxSeconds; // When using the virtual buffer, it must be capped.
uint32_t bufferTargetPerc; // Computed considering a bufferSize = 30s
double totalDuration; // Total video duration in seconds (taken from MPD)
double segmentDuration; // Segment duration in seconds
std::vector<uint64_t> availableBitrates;
std::vector<double> utilityVector;
uint32_t bitrateCount; // Number of available bitrates
SparseBayesUcbState sparseBayesUcbState; // Keeps track of SparseBayesUcb state
// SparseBayesUcb Vp and gp (multiplied by the segment duration 'p')
// They are dimensioned such that log utility would always prefer
// - the lowest bitrate when bufferLevel = segmentDuration
// - the highest bitrate when bufferLevel = bufferTarget
double Vp;
double gp;
bool safetyGuarantee;
double maxRtt;
double virtualBuffer;
uint64_t currentBitrate;
int currentQuality;
uint64_t batchBw;
int batchBwCount;
std::vector<uint64_t> batchBwSamples;
uint64_t instantBw;
uint64_t averageBw;
double lastDownloadTimeInstant;
double currentDownloadTimeInstant;
double lastSegmentDownloadTime;
uint32_t lastBufferFill;
bool bufferEOS;
bool shouldAbort;
double alphaRate;
bool isCheckedForReceiver;
sampleplayer::managers::IMultimediaManagerBase *multimediaManager;
dash::mpd::IRepresentation *representation;
std::map<int, std::vector<int>> rttMap;
std::map<int, std::vector<int>> ecnMap;
std::map<int, std::vector<int>> numHopsMap;
std::map<int, int> qualityHistory;
unsigned long long int rebufferStart;
unsigned long long int rebufferEnd;
double cumQoE;
double qoe_w1;
double qoe_w2;
double qoe_w3;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_SPARSEBAYESUCB_H_ */
| 6,479 | 56.857143 | 232 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/AbstractAdaptationLogic.h
|
/*
* AbstractAdaptationLogic.h
*****************************************************************************
* Copyright (C) 2013, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_ABSTRACTADAPTATIONLOGIC_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_ABSTRACTADAPTATIONLOGIC_H_
#include "IAdaptationLogic.h"
#include "IMPD.h"
namespace libdash
{
namespace framework
{
namespace adaptation
{
class AbstractAdaptationLogic : public IAdaptationLogic
{
public:
AbstractAdaptationLogic (dash::mpd::IMPD *mpd, dash::mpd::IPeriod* period, dash::mpd::IAdaptationSet *adaptationSet, bool isVideo);
virtual ~AbstractAdaptationLogic ();
virtual uint32_t GetPosition ();
virtual void SetPosition (uint32_t segmentNumber);
virtual dash::mpd::IRepresentation* GetRepresentation ();
virtual void SetRepresentation (dash::mpd::IPeriod *period,
dash::mpd::IAdaptationSet *adaptationSet,
dash::mpd::IRepresentation *representation);
virtual LogicType GetType () = 0;
virtual bool IsUserDependent () = 0;
virtual bool IsRateBased () = 0;
virtual bool IsBufferBased () = 0;
virtual void BitrateUpdate (uint64_t) = 0;
virtual void SegmentPositionUpdate (uint32_t qualitybps) = 0;
virtual void DLTimeUpdate (double time) = 0;
virtual void BufferUpdate (uint32_t) = 0;
virtual void OnEOS (bool value)= 0;
virtual void OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec) = 0;
virtual void CheckedByDASHReceiver() =0;
protected:
dash::mpd::IMPD *mpd;
dash::mpd::IPeriod *period;
dash::mpd::IAdaptationSet *adaptationSet;
dash::mpd::IRepresentation *representation;
uint32_t segmentNumber;
bool isVideo;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_ABSTRACTADAPTATIONLOGIC_H_ */
| 3,045 | 48.934426 | 182 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/RateBasedAdaptation.cpp
|
/*
* RateBasedAdaptation.cpp
*****************************************************************************
* Copyright (C) 2016,
* Jacques Samain <[email protected]>
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "RateBasedAdaptation.h"
#include<stdio.h>
using namespace dash::mpd;
using namespace libdash::framework::adaptation;
using namespace libdash::framework::input;
using namespace libdash::framework::mpd;
RateBasedAdaptation::RateBasedAdaptation (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, bool isVid, double arg1) :
AbstractAdaptationLogic (mpd, period, adaptationSet, isVid)
{
std::vector<IRepresentation* > representations = this->adaptationSet->GetRepresentation();
this->availableBitrates.clear();
for(size_t i = 0; i < representations.size(); i++)
{
this->availableBitrates.push_back((uint64_t)(representations.at(i)->GetBandwidth()));
}
this->currentBitrate = this->availableBitrates.at(0);
this->representation = representations.at(0);
this->multimediaManager = NULL;
if(arg1 != 0 && arg1 <= 1)
this->alpha = arg1;
else
this->alpha = 0.85;
L("RateBasedParams:\t%f\n",alpha);
this->averageBw = 0;
}
RateBasedAdaptation::~RateBasedAdaptation ()
{
}
LogicType RateBasedAdaptation::GetType ()
{
return adaptation::RateBased;
}
bool RateBasedAdaptation::IsUserDependent ()
{
return false;
}
bool RateBasedAdaptation::IsRateBased ()
{
return true;
}
bool RateBasedAdaptation::IsBufferBased ()
{
return false;
}
void RateBasedAdaptation::SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager)
{
this->multimediaManager = _mmManager;
}
void RateBasedAdaptation::NotifyBitrateChange ()
{
if(this->multimediaManager->IsStarted() && !this->multimediaManager->IsStopping())
if(this->isVideo)
this->multimediaManager->SetVideoQuality(this->period, this->adaptationSet, this->representation);
else
this->multimediaManager->SetAudioQuality(this->period, this->adaptationSet, this->representation);
}
uint64_t RateBasedAdaptation::GetBitrate ()
{
return this->currentBitrate;
}
void RateBasedAdaptation::SetBitrate (uint64_t bps)
{
std::vector<IRepresentation *> representations;
representations = this->adaptationSet->GetRepresentation();
size_t i = 0;
this->ewma(bps);
for(i = 0;i < representations.size();i++)
{
if(representations.at(i)->GetBandwidth() > this->averageBw)
{
if(i > 0)
i--;
break;
}
}
if((size_t)i == (size_t)(representations.size()))
i = i-1;
L("ADAPTATION_LOGIC:\tFor %s:\tBW_estimation(ewma): %lu, choice: %lu\n", (this->isVideo ? "video" : "audio"), this->averageBw, i);
this->representation = representations.at(i);
this->currentBitrate = this->representation->GetBandwidth();
}
void RateBasedAdaptation::BitrateUpdate (uint64_t bps)
{
Debug("Rate Based adaptation: speed received: %lu\n", bps);
this->SetBitrate(bps);
this->NotifyBitrateChange();
}
void RateBasedAdaptation::SegmentPositionUpdate (uint32_t qualitybps)
{
}
void RateBasedAdaptation::DLTimeUpdate (double time)
{
}
void RateBasedAdaptation::ewma (uint64_t bps)
{
if(averageBw)
{
averageBw = alpha*averageBw + (1-alpha)*bps;
}
else
{
averageBw = bps;
}
}
void RateBasedAdaptation::OnEOS (bool value)
{
}
void RateBasedAdaptation::OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec)
{
}
void RateBasedAdaptation::CheckedByDASHReceiver ()
{
}
void RateBasedAdaptation::BufferUpdate (uint32_t bufferfill)
{
}
| 3,809 | 25.09589 | 158 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/AbstractAdaptationLogic.cpp
|
/*
* AbstractAdaptationLogic.cpp
*****************************************************************************
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "AbstractAdaptationLogic.h"
using namespace libdash::framework::adaptation;
using namespace dash::mpd;
AbstractAdaptationLogic::AbstractAdaptationLogic (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, bool isVid) :
mpd (mpd),
period (period),
adaptationSet (adaptationSet),
representation (NULL),
isVideo (isVid)
{
}
AbstractAdaptationLogic::~AbstractAdaptationLogic ()
{
}
uint32_t AbstractAdaptationLogic::GetPosition ()
{
return 0;
}
void AbstractAdaptationLogic::SetPosition (uint32_t segmentNumber)
{
this->segmentNumber = segmentNumber;
}
IRepresentation* AbstractAdaptationLogic::GetRepresentation ()
{
return this->representation;
}
void AbstractAdaptationLogic::SetRepresentation (IPeriod *period, IAdaptationSet *adaptationSet, IRepresentation *representation)
{
this->period = period;
this->adaptationSet = adaptationSet;
this->representation = representation;
}
| 1,662 | 34.382979 | 158 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/Panda.h
|
/*
* Panda.h
*
* Created on: Oct 17, 2016
* Author: ndnops
*/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_PANDA_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_PANDA_H_
#include "AbstractAdaptationLogic.h"
#include "../MPD/AdaptationSetStream.h"
#include "../Input/IDASHReceiverObserver.h"
#include <list>
namespace libdash
{
namespace framework
{
namespace adaptation
{
class PandaAdaptation : public AbstractAdaptationLogic
{
public:
PandaAdaptation(dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, bool isVid,
double arg1, double arg2, double arg3, double arg4, double arg5, double arg6);
virtual ~PandaAdaptation();
virtual LogicType GetType ();
virtual bool IsUserDependent ();
virtual bool IsRateBased ();
virtual bool IsBufferBased ();
virtual void BitrateUpdate (uint64_t bps);
void SegmentPositionUpdate(uint32_t qualitybps);
virtual void DLTimeUpdate (double time);
virtual void BufferUpdate (uint32_t bufferFill);
void SetBitrate (uint64_t bufferFill);
uint64_t GetBitrate ();
virtual void SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager);
void NotifyBitrateChange ();
void OnEOS (bool value);
virtual void OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec);
void CheckedByDASHReceiver();
void Quantizer ();
void QuantizerExtended ();
private:
double ComputeInstability ();
double currentInstability;
uint64_t currentBitrate;
uint64_t currentBitrateVirtual;
std::vector<uint64_t> availableBitrates;
sampleplayer::managers::IMultimediaManagerBase *multimediaManager;
dash::mpd::IRepresentation *representation;
uint64_t averageBw; // Classic EWMA
uint64_t instantBw;
uint64_t smoothBw; // Panda paper smoothed y[n]
uint64_t targetBw; // Panda paper x[n] bw estimation
double param_Alpha;
double alpha_ewma;
double param_Epsilon;
double param_K;
double param_W;
double param_Beta;
double param_Bmin;
double interTime; // Actual inter time
double targetInterTime; // Target inter time
double downloadTime;
uint32_t bufferLevel;
uint32_t lastBufferLevel;
double bufferMaxSizeSeconds; // Usually set to 60s
double bufferLevelSeconds; // Current buffer level [s]
int segPos;
bool extMPDuse;
int historylength;
std::list<uint64_t> history;
double param_instability;
int localSegVariance;
double segmentDuration;
double deltaUp;
double deltaDown;
size_t current;
std::map<int, int> qualityHistory;
unsigned long long int rebufferStart;
unsigned long long int rebufferEnd;
double cumQoE;
double qoe_w1;
double qoe_w2;
double qoe_w3;
};
} /* namespace adaptation */
} /* namespace framework */
} /* namespace libdash */
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_PANDA_H_ */
| 4,453 | 40.626168 | 174 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/Panda.cpp
|
/*
* Panda.cpp
*****************************************************************************
* Based on paper "Probe and Adapt: Adaptation for HTTP Video Streaming At Scale", Zhi Li et al.
*
* Copyright (C) 2016,
* Jacques Samain <[email protected]>
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "Panda.h"
#include <stdio.h>
#include <iostream>
using namespace dash::mpd;
using namespace libdash::framework::adaptation;
using namespace libdash::framework::input;
using namespace libdash::framework::mpd;
PandaAdaptation::PandaAdaptation(IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6) :
AbstractAdaptationLogic (mpd, period, adaptationSet, isVid)
{
// this->param_Alpha = ((arg1 < 1) ? ((arg1 >= 0) ? arg1 : 0.8) : 0.8);
this->param_Alpha = 0.2;
this->param_Beta = 0.2;
this->param_K = 0.14;
this->param_W = 300000;
this->param_Epsilon = 0.15; //safety threshhold (changed from 0.15 to 0.2(5)) without MPD extension
//Extended MPD additions + parameter
this->segPos = 0;
this->historylength = 10; //parameter for the Instability over the last x segments
this->param_instability = 0.03; //instability threshold (turn off by value = 1, good value around 0.05)
this->localSegVariance = 3; //parameter on how many segments into the future have to be feasible by the current bw (turn off by value = 0)
// Set QoE weights
this->qoe_w1 = arg4;
this->qoe_w2 = arg5;
this->qoe_w3 = arg6;
this->targetBw = 0;
this->targetInterTime = 0.0;
this->averageBw = 0;
this->smoothBw = 0;
this->instantBw = 0;
this->targetBw = 0;
this->targetInterTime = 0.0;
this->interTime = 0.0;
this->segmentDuration = 2.0;
this->bufferMaxSizeSeconds = 20.0; //changed from 60s to 20s (HAS TO BE CHANGED IN MultimediaManager.cpp !)
if(arg1) {
if(arg1 >= 0 && arg1 <= 1) {
this->alpha_ewma = arg1;
}
else
this->alpha_ewma = 0.8;
}
else {
Debug("EWMA Alpha parameter NOT SPECIFIED!\n");
}
/// Set 'param_Bmin'
if(arg2) {
if(arg2 > 0 && arg2 < (int)bufferMaxSizeSeconds) {
this->param_Bmin = (double)arg2;
}
else
this->param_Bmin = 44;
}
else {
Debug("bufferTarget NOT SPECIFIED!\n");
}
this->bufferLevel = 0;
this->bufferLevelSeconds = 0.0;
//this->bufferMaxSizeSeconds = 60.0;
this->rebufferStart = 0;
this->rebufferEnd = 0;
this->downloadTime = 0.0;
this->isVideo = isVid;
this->mpd = mpd;
this->adaptationSet = adaptationSet;
this->period = period;
this->multimediaManager = NULL;
this->representation = NULL;
this->currentBitrate = 0;
this->current = 0;
// Retrieve the available bitrates
std::vector<IRepresentation* > representations = this->adaptationSet->GetRepresentation();
this->extMPDuse = representations.at(0)->IsExtended();
L("Extended MPD file used: %s\n", extMPDuse? "yes": "no");
this->availableBitrates.clear();
L("PANDA Available Bitrates...\n");
for(size_t i = 0; i < representations.size(); i++)
{
this->availableBitrates.push_back((uint64_t)(representations.at(i)->GetBandwidth()));
L("%d - %I64u bps\n", i, this->availableBitrates[i]);
if(false)
{
for(int j=1; j <= representations.at(i)->GetSegmentSizes().size(); j++)
{
if(representations.at(i)->GetSegmentSizes().count(std::to_string(j)) == 1)
L("\tSegment No. %d - %d bits per second\n", j, representations.at(i)->GetSpecificSegmentSize(std::to_string(j)));
else
L("Failed to load size from Segment %d", j);
}
}
}
this->representation = this->adaptationSet->GetRepresentation().at(0);
this->currentBitrate = (uint64_t) this->representation->GetBandwidth();
this->currentBitrateVirtual = (uint64_t) this->representation->GetBandwidth();
L("Panda parameters: K= %f, Bmin = %f, alpha = %f, beta = %f, W = %f\n", param_K, param_Bmin, param_Alpha, param_Beta, param_W);
}
PandaAdaptation::~PandaAdaptation() {
}
LogicType PandaAdaptation::GetType ()
{
return adaptation::Panda;
}
bool PandaAdaptation::IsUserDependent ()
{
return false;
}
bool PandaAdaptation::IsRateBased ()
{
return true;
}
bool PandaAdaptation::IsBufferBased ()
{
return true;
}
void PandaAdaptation::SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager)
{
this->multimediaManager = _mmManager;
}
void PandaAdaptation::NotifyBitrateChange ()
{
if(this->multimediaManager->IsStarted() && !this->multimediaManager->IsStopping())
if(this->isVideo)
this->multimediaManager->SetVideoQuality(this->period, this->adaptationSet, this->representation);
else
this->multimediaManager->SetAudioQuality(this->period, this->adaptationSet, this->representation);
}
uint64_t PandaAdaptation::GetBitrate ()
{
return this->currentBitrate;
}
void PandaAdaptation::Quantizer ()
{
this->deltaUp = this->param_W + this->param_Epsilon * (double)this->smoothBw;
this->deltaDown = this->param_W;
L("** DELTA UP:\t%f\n", this->deltaUp);
uint64_t smoothBw_UP = this->smoothBw - this->deltaUp;
uint64_t smoothBw_DOWN = this->smoothBw - this->deltaDown;
L("** Smooth-BW UP:\t%d\t Smooth-BW DOWN:\t%d\n", smoothBw_UP, smoothBw_DOWN);
std::vector<IRepresentation *> representations;
representations = this->adaptationSet->GetRepresentation();
uint32_t numQualLevels = representations.size();
// We have to find bitrateMin and bitrateMax
uint64_t bitrateDown, bitrateUp;
// DOWN
uint32_t iDown = 0;
uint32_t i_d,i_u;
for (i_d = 0; i_d < this->availableBitrates.size(); ++i_d) {
if (this->availableBitrates[i_d] > smoothBw_DOWN) {
break;
}
}
if(i_d > 0)
iDown = i_d-1;
else
iDown = 0;
bitrateDown = (uint64_t) representations.at(iDown)->GetBandwidth();
L("** Bitrate DOWN:\t%d\t at Quality:\t%d\n", bitrateDown, iDown);
// UP
uint32_t iUp = 0;
for (i_u = 0; i_u < this->availableBitrates.size(); ++i_u) {
if (this->availableBitrates[i_u] > smoothBw_UP) {
break;
}
}
if(i_u > 0)
iUp = i_u-1;
else
iUp = 0;
bitrateUp = (uint64_t) representations.at(iUp)->GetBandwidth();
L("** Bitrate UP:\t%d\t at Quality:\t%d\n", bitrateUp, iUp);
L("** Current RATE:\t%d\n Current QUALITY:\t%d\n", this->currentBitrate, this->current);
// Next bitrate computation
if(this->currentBitrate < bitrateUp)
{
this->currentBitrate = bitrateUp;
this->current = iUp;
}
else if(this->currentBitrate <= bitrateDown && this->currentBitrate >= bitrateUp)
{
L("** CURRENT UNCHANGED **\n");
}
else
{
this->currentBitrate = bitrateDown;
this->current = iDown;
}
this->representation = this->adaptationSet->GetRepresentation().at(this->current);
}
void PandaAdaptation::QuantizerExtended ()
{
this->deltaUp = this->param_W + this->param_Epsilon * (double)this->smoothBw; // window of acceptable video rates (high impact on stability when extd MPD used)
this->deltaDown = this->param_W;
L("** DELTA UP:\t%f\n", this->deltaUp);
uint64_t smoothBw_UP = this->smoothBw - this->deltaUp;
uint64_t smoothBw_DOWN = this->smoothBw - this->deltaDown;
L("** Smooth-BW UP:\t%d\t Smooth-BW DOWN:\t%d\n", smoothBw_UP, smoothBw_DOWN);
std::vector<IRepresentation *> representations;
representations = this->adaptationSet->GetRepresentation();
uint32_t numQualLevels = representations.size();
// We have to find bitrateMin and bitrateMax
uint64_t bitrateDown, bitrateUp, bitrateDownSegment, bitrateUpSegment;
// DOWN
uint32_t iDown = 0;
uint32_t i_d;
uint64_t realbps;
for (i_d = 0; i_d < this->availableBitrates.size(); ++i_d) {
realbps = representations.at(i_d)->GetSpecificSegmentSize(std::to_string(segPos+1));
if (realbps > smoothBw_DOWN) {
break;
}
}
if(i_d > 0)
iDown = i_d-1;
else
iDown = 0;
bitrateDown = (uint64_t) representations.at(iDown)->GetBandwidth();
bitrateDownSegment = representations.at(iDown)->GetSpecificSegmentSize(std::to_string(segPos+1));
L("** Bitrate DOWN: (avg)\t%d\t (specific)\t%d\t at Quality:\t%d\n", bitrateDown, bitrateDownSegment, iDown);
// UP
uint32_t iUp = 0;
uint32_t i_u;
for (i_u = 0; i_u < this->availableBitrates.size(); ++i_u) {
realbps = representations.at(i_u)->GetSpecificSegmentSize(std::to_string(segPos+1));
if (realbps > smoothBw_UP) {
break;
}
}
if(i_u > 0)
iUp = i_u-1;
else
iUp = 0;
bitrateUp = (uint64_t) representations.at(iUp)->GetBandwidth();
bitrateUpSegment = representations.at(iUp)->GetSpecificSegmentSize(std::to_string(segPos+1));
L("** Bitrate UP: (avg)\t%d\t (specific)\t%d\t at Quality:\t%d\n", bitrateUp, bitrateUpSegment, iUp);
L("** Current RATE:\t%d\n Current QUALITY:\t%d\n", this->currentBitrate, this->current);
//Looking into the future
bool singleOutlier = false;
for(int i = 2; i < this->localSegVariance + 2; i++)
{
uint64_t bitrateUpSegmentNext = representations.at(iUp)->GetSpecificSegmentSize(std::to_string(segPos+i)); //real bps of i'th segment after current segment
if (bitrateUpSegmentNext > smoothBw_UP)
{
singleOutlier = true;
break;
}
}
// Next bitrate computation
if(this->currentBitrate < bitrateUp)
{
if(this->currentInstability < this->param_instability && !singleOutlier)
{
this->currentBitrateVirtual = bitrateUp;
this->current = iUp;
std::cout << "[UP] " << bitrateUp << " /real :" << bitrateUpSegment << " Instability: " << this->currentInstability << "\n";
} else
{
std::cout << "[NOT UP]" << bitrateUp << " /real: " << bitrateUpSegment << " Instability: " << this->currentInstability << "\n";
L("** CURRENT UNCHANGED because of INSTABILITY **\n");
}
}
else if(this->currentBitrate <= bitrateDown && this->currentBitrate >= bitrateUp)
{
L("** CURRENT UNCHANGED **\n");
std::cout << "[UNCHANGED]" << bitrateDown << " >= " << this->currentBitrate << " >= " << bitrateUp << " Instability: " << this->currentInstability << "\n";
}
else if(this->currentBitrate > bitrateDown)
{
this->currentBitrateVirtual = bitrateDown;
this->current = iDown;
std::cout << "[DOWN]" << bitrateDown << " /real: " << bitrateDownSegment << " Instability: " << this->currentInstability << "\n";
}
this->representation = this->adaptationSet->GetRepresentation().at(this->current);
}
void PandaAdaptation::SetBitrate (uint64_t bps)
{
// 1. Calculating the targetBW
if(this->targetBw)
{
//this->targetBw = this->targetBw + param_K * this->interTime * (param_W - ((this->targetBw - bps + this->param_W) > 0 ? this->targetBw - bps + this->param_W: 0));
if ((double)this->targetBw - (double)bps + this->param_W > 0)
this->targetBw = this->targetBw + (uint64_t)(param_K * this->interTime * (param_W - ((double)this->targetBw - (double)bps + this->param_W)));
else
this->targetBw = this->targetBw + (uint64_t)(param_K * this->interTime * param_W);
}
else
this->targetBw = bps;
L("** INSTANTANEOUS BW:\t%d\n", bps);
L("** CLASSIC EWMA BW:\t%d\n", this->averageBw);
L("** PANDA TARGET BW:\t%d\n", this->targetBw);
// 2. Calculating the smoothBW
if(this->interTime)
this->smoothBw = (uint64_t)((double)this->smoothBw - this->param_Alpha * this->interTime * ((double)this->smoothBw - (double)this->targetBw));
else
this->smoothBw = this->targetBw;
L("** PANDA SMOOTH BW:\t%d\n", this->smoothBw);
// 3. Quantization
if(extMPDuse)
this->QuantizerExtended();
else
this->Quantizer();
L("ADAPTATION_LOGIC:\tFor %s:\tlast_buffer: %f\tbuffer_level: %f, instantaneousBw: %lu, AverageBW: %lu, choice: %d\n",isVideo ? "video" : "audio",(double)lastBufferLevel/100 , (double)bufferLevel/100, this->instantBw, this->averageBw , this->current);
this->lastBufferLevel = this->bufferLevel;
// 4. Computing the "actual inter time"
this->bufferLevelSeconds = (double)( (this->bufferLevel * this->bufferMaxSizeSeconds) *1./100);
this->targetInterTime = ((double)this->currentBitrate * segmentDuration) * 1./this->smoothBw + param_Beta * (this->bufferLevelSeconds - param_Bmin);
L("** TARGET INTER TIME:\t%f\n", this->targetInterTime);
L("** DOWNLOAD TIME:\t%f\n", this->downloadTime);
this->targetInterTime = (this->targetInterTime > 0) ? this->targetInterTime : 0.0;
this->interTime = this->targetInterTime > this->downloadTime ? this->targetInterTime : this->downloadTime;
L("** ACTUAL INTER TIME:\t%f\n", this->interTime);
this->multimediaManager->SetTargetDownloadingTime(this->isVideo, interTime);
}
void PandaAdaptation::BitrateUpdate (uint64_t bps)
{
this->instantBw = bps;
// Avg bandwidth estimate with EWMA
if(this->averageBw == 0)
{
this->averageBw = bps;
}
else
{
this->averageBw = this->alpha_ewma*this->averageBw + (1 - this->alpha_ewma)*bps;
}
this->SetBitrate(bps);
this->NotifyBitrateChange(); //HERE is the update for the Multimedia Manager (triggers "setVideoQuality")
}
void PandaAdaptation::SegmentPositionUpdate (uint32_t qualitybps)
{
this->segPos++;
this->currentBitrate = (uint64_t)qualitybps;
std::cout << "Pos: " << segPos << " with " << this->currentBitrate << "\n";
history.push_back(this->currentBitrate); //build up the history
if(history.size() > historylength) //only history over last k segments (k=historylength)
history.pop_front();
this->currentInstability = this->ComputeInstability();
}
double PandaAdaptation::ComputeInstability ()
{
int64_t numerator = 0;
int64_t denominator = 0;
int64_t last_rate = history.front();
double weight = 1.0;
for(uint64_t rate : history)
{
numerator = numerator + abs(((int64_t)rate - last_rate) * weight);
denominator = denominator + ((int64_t)rate * weight);
last_rate = (int64_t)rate;
}
double instability = numerator / (double)denominator;
return instability;
}
void PandaAdaptation::DLTimeUpdate (double time)
{
this->downloadTime = time;
}
void PandaAdaptation::BufferUpdate (uint32_t bufferFill)
{
if (bufferFill == (uint32_t)0 && this->rebufferStart == 0) {
this->rebufferStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
this->rebufferEnd = 0;
}
else if (this->rebufferEnd == 0 && this->rebufferStart != 0) {
this->rebufferEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
}
this->bufferLevel = bufferFill;
}
void PandaAdaptation::OnEOS (bool value)
{
}
void PandaAdaptation::OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec)
{
std::vector<IRepresentation*> representations = this->adaptationSet->GetRepresentation();
int numArms = (int)representations.size();
uint32_t bufferFill = (uint32_t)(bufferFillPct * (double)100);
std::cout << "stat-begin" << std::endl;
std::cout << "stat-nonbandit" << std::endl;
std::cout << "stat-qual " << quality << std::endl;
///////////////////
// Calculate QoE //
///////////////////
// 1. Base quality (kbps)
// 2. Decline in quality (kbps)
// 3. Time spent rebuffering (ms)
// 1. Base quality
int baseQuality = (int)(this->availableBitrates[quality] / (uint64_t)1000);
std::cout << "stat-qoebase " << baseQuality << std::endl;
// 2. Decline in quality
this->qualityHistory[segNum] = quality;
int qualityDecline = 0;
if (this->qualityHistory[segNum] < this->qualityHistory[segNum-1]) {
int prevQuality = (int)(this->availableBitrates[this->qualityHistory[segNum-1]]/(uint64_t)1000);
int currQuality = (int)(this->availableBitrates[quality]/(uint64_t)1000);
qualityDecline = prevQuality - currQuality;
}
std::cout << "stat-qoedecl " << qualityDecline << std::endl;
// 3. Time spent rebuffering
// We just got a new segment so rebuffering has stopped
// If it occurred, we need to know for how long
int rebufferTime = 0;
if (this->rebufferStart != 0) {
if (this->rebufferEnd == 0) {
this->rebufferEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
}
rebufferTime = (int)(this->rebufferEnd - this->rebufferStart);
this->rebufferStart = 0;
}
std::cout << "stat-qoerebuffms " << rebufferTime << std::endl;
// Put it all together for the reward
// The weight of 3 comes from the SIGCOMM paper; they use 3000 because their
// rebufferTime is in seconds, but ours is milliseconds
double reward = (this->qoe_w1*(double)baseQuality) - (this->qoe_w2*(double)qualityDecline) - (this->qoe_w3*(double)rebufferTime*(double)rebufferTime);
this->cumQoE += reward;
std::cout << "stat-qoeseg " << reward << std::endl;
std::cout << "stat-qoecum " << this->cumQoE << std::endl;
}
void PandaAdaptation::CheckedByDASHReceiver ()
{
}
| 17,224 | 31.809524 | 252 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/FOOBAR.cpp
|
/*
* FOOBAR.cpp
*
*****************************************************************************/
#include "FOOBAR.h"
#include<stdio.h>
using namespace dash::mpd;
using namespace libdash::framework::adaptation;
using namespace libdash::framework::input;
using namespace libdash::framework::mpd;
FOOBARAdaptation::FOOBARAdaptation(IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6) :
AbstractAdaptationLogic (mpd, period, adaptationSet, isVid)
{
this->param_Alpha = 0.2;
this->param_Beta = 0.2;
this->param_K = 0.14;
this->param_W = 300000;
this->param_Epsilon = 0.2; //safety threshhold changed from 0.15 to 0.2(5)
this->targetBw = 0;
this->targetInterTime = 0.0;
this->averageBw = 0;
this->smoothBw = 0;
this->instantBw = 0;
this->targetBw = 0;
this->targetInterTime = 0.0;
this->interTime = 0.0;
this->segmentDuration = 2.0;
this->bufferMaxSizeSeconds = 20.0;
if(arg1) {
if(arg1 >= 0 && arg1 <= 1) {
this->alpha_ewma = arg1;
}
else
this->alpha_ewma = 0.8;
}
else {
Debug("EWMA Alpha parameter NOT SPECIFIED!\n");
}
// Set 'param_Bmin'
if(arg2) {
if(arg2 > 0 && arg2 < (int)bufferMaxSizeSeconds) {
this->param_Bmin = (double)arg2;
}
else
this->param_Bmin = 44;
}
else {
Debug("bufferTarget NOT SPECIFIED!\n");
}
this->bufferLevel = 0;
this->bufferLevelSeconds = 0.0;
this->downloadTime = 0.0;
this->isVideo = isVid;
this->mpd = mpd;
this->adaptationSet = adaptationSet;
this->period = period;
this->multimediaManager = NULL;
this->representation = NULL;
this->currentBitrate = 0;
this->current = 0;
// Retrieve the available bitrates
std::vector<IRepresentation* > representations = this->adaptationSet->GetRepresentation();
this->availableBitrates.clear();
L("FOOBAR Available Bitrates...\n");
for(size_t i = 0; i < representations.size(); i++)
{
this->availableBitrates.push_back((uint64_t)(representations.at(i)->GetBandwidth()));
L("%d - %I64u bps\n", i+1, this->availableBitrates[i]);
}
this->representation = this->adaptationSet->GetRepresentation().at(0);
this->currentBitrate = (uint64_t) this->representation->GetBandwidth();
L("FOOBAR parameters: K= %f, Bmin = %f, alpha = %f, beta = %f, W = %f\n", param_K, param_Bmin, param_Alpha, param_Beta, param_W);
}
FOOBARAdaptation::~FOOBARAdaptation() {
}
LogicType FOOBARAdaptation::GetType ()
{
return adaptation::FOOBAR;
}
bool FOOBARAdaptation::IsUserDependent ()
{
return false;
}
bool FOOBARAdaptation::IsRateBased ()
{
return true;
}
bool FOOBARAdaptation::IsBufferBased ()
{
return true;
}
void FOOBARAdaptation::SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager)
{
this->multimediaManager = _mmManager;
}
void FOOBARAdaptation::NotifyBitrateChange ()
{
if(this->multimediaManager->IsStarted() && !this->multimediaManager->IsStopping())
if(this->isVideo)
this->multimediaManager->SetVideoQuality(this->period, this->adaptationSet, this->representation);
else
this->multimediaManager->SetAudioQuality(this->period, this->adaptationSet, this->representation);
}
uint64_t FOOBARAdaptation::GetBitrate ()
{
return this->currentBitrate;
}
void FOOBARAdaptation::Quantizer ()
{
this->deltaUp = this->param_W + this->param_Epsilon * (double)this->smoothBw;
this->deltaDown = this->param_W;
L("** DELTA UP:\t%f\n", this->deltaUp);
uint64_t smoothBw_UP = this->smoothBw - this->deltaUp;
uint64_t smoothBw_DOWN = this->smoothBw - this->deltaDown;
L("** Smooth-BW UP:\t%d\t Smooth-BW DOWN:\t%d\n", smoothBw_UP, smoothBw_DOWN);
std::vector<IRepresentation *> representations;
representations = this->adaptationSet->GetRepresentation();
uint32_t numQualLevels = representations.size();
// We have to find bitrateMin and bitrateMax
uint64_t bitrateDown, bitrateUp;
// DOWN
uint32_t iDown = 0;
uint32_t i_d,i_u;
for (i_d = 0; i_d < this->availableBitrates.size(); ++i_d) {
if (this->availableBitrates[i_d] > smoothBw_DOWN) {
break;
}
}
if(i_d > 0)
iDown = i_d-1;
else
iDown = 0;
bitrateDown = (uint64_t) representations.at(iDown)->GetBandwidth();
L("** Bitrate DOWN:\t%d\t at Quality:\t%d\n", bitrateDown, iDown);
// UP
uint32_t iUp = 0;
for (i_u = 0; i_u < this->availableBitrates.size(); ++i_u) {
if (this->availableBitrates[i_u] > smoothBw_UP) {
break;
}
}
if(i_u > 0)
iUp = i_u-1;
else
iUp = 0;
bitrateUp = (uint64_t) representations.at(iUp)->GetBandwidth();
L("** Bitrate UP:\t%d\t at Quality:\t%d\n", bitrateUp, iUp);
L("** Current RATE:\t%d\n Current QUALITY:\t%d\n", this->currentBitrate, this->current);
// Next bitrate computation
if(this->currentBitrate < bitrateUp)
{
this->currentBitrate = bitrateUp;
this->current = iUp;
}
else if(this->currentBitrate <= bitrateDown && this->currentBitrate >= bitrateUp)
{
L("** CURRENT UNCHANGED **\n");
}
else
{
this->currentBitrate = bitrateDown;
this->current = iDown;
}
this->representation = this->adaptationSet->GetRepresentation().at(this->current);
}
void FOOBARAdaptation::SetBitrate (uint64_t bps)
{
// 1. Calculating the targetBW
if(this->targetBw)
{
//this->targetBw = this->targetBw + param_K * this->interTime * (param_W - ((this->targetBw - bps + this->param_W) > 0 ? this->targetBw - bps + this->param_W: 0));
if ((double)this->targetBw - (double)bps + this->param_W > 0)
this->targetBw = this->targetBw + (uint64_t)(param_K * this->interTime * (param_W - ((double)this->targetBw - (double)bps + this->param_W)));
else
this->targetBw = this->targetBw + (uint64_t)(param_K * this->interTime * param_W);
}
else
this->targetBw = bps;
L("** INSTANTANEOUS BW:\t%d\n", bps);
L("** CLASSIC EWMA BW:\t%d\n", this->averageBw);
L("** FOOBAR TARGET BW:\t%d\n", this->targetBw);
// 2. Calculating the smoothBW
if(this->interTime)
this->smoothBw = (uint64_t)((double)this->smoothBw - this->param_Alpha * this->interTime * ((double)this->smoothBw - (double)this->targetBw));
else
this->smoothBw = this->targetBw;
L("** FOOBAR SMOOTH BW:\t%d\n", this->smoothBw);
// 3. Quantization
this->Quantizer();
L("ADAPTATION_LOGIC:\tFor %s:\tlast_buffer: %f\tbuffer_level: %f, instantaneousBw: %lu, AverageBW: %lu, choice: %d\n",isVideo ? "video" : "audio",(double)lastBufferLevel/100 , (double)bufferLevel/100, this->instantBw, this->averageBw , this->current);
this->lastBufferLevel = this->bufferLevel;
// 4. Computing the "actual inter time"
this->bufferLevelSeconds = (double)( (this->bufferLevel * this->bufferMaxSizeSeconds) *1./100);
this->targetInterTime = ((double)this->currentBitrate * segmentDuration) * 1./this->smoothBw + param_Beta * (this->bufferLevelSeconds - param_Bmin);
L("** TARGET INTER TIME:\t%f\n", this->targetInterTime);
L("** DOWNLOAD TIME:\t%f\n", this->downloadTime);
this->targetInterTime = (this->targetInterTime > 0) ? this->targetInterTime : 0.0;
this->interTime = this->targetInterTime > this->downloadTime ? this->targetInterTime : this->downloadTime;
L("** ACTUAL INTER TIME:\t%f\n", this->interTime);
this->multimediaManager->SetTargetDownloadingTime(this->isVideo, interTime);
}
void FOOBARAdaptation::BitrateUpdate (uint64_t bps)
{
this->instantBw = bps;
// Avg bandwidth estimate with EWMA
if(this->averageBw == 0)
{
this->averageBw = bps;
}
else
{
this->averageBw = this->alpha_ewma*this->averageBw + (1 - this->alpha_ewma)*bps;
}
this->SetBitrate(bps);
this->NotifyBitrateChange(); //HERE is the update for the Multimedia Manager (triggers "setVideoQuality")
}
void FOOBARAdaptation::SegmentPositionUpdate (uint32_t qualitybps)
{
}
void FOOBARAdaptation::DLTimeUpdate (double time)
{
this->downloadTime = time;
}
void FOOBARAdaptation::BufferUpdate (uint32_t bufferfill)
{
this->bufferLevel = bufferfill;
}
void FOOBARAdaptation::OnEOS (bool value)
{
}
void FOOBARAdaptation::OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec)
{
}
void FOOBARAdaptation::CheckedByDASHReceiver ()
{
}
| 8,291 | 27.593103 | 252 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/AlwaysLowestLogic.h
|
/*
* AlwaysLowestLogic.h
*****************************************************************************
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_ALWAYSLOWESTLOGIC_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_ALWAYSLOWESTLOGIC_H_
#include "IMPD.h"
#include "AbstractAdaptationLogic.h"
namespace libdash
{
namespace framework
{
namespace adaptation
{
class AlwaysLowestLogic : public AbstractAdaptationLogic
{
public:
AlwaysLowestLogic (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, bool isVid);
virtual ~AlwaysLowestLogic ();
virtual LogicType GetType ();
virtual bool IsUserDependent();
virtual bool IsRateBased();
virtual bool IsBufferBased();
virtual void BitrateUpdate(uint64_t);
virtual void SegmentPositionUpdate(uint32_t qualitybps);
virtual void DLTimeUpdate(double time);
virtual void BufferUpdate(uint32_t);
virtual void SetMultimediaManager(sampleplayer::managers::IMultimediaManagerBase *mmM);
virtual void OnEOS(bool value);
virtual void OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec);
virtual void CheckedByDASHReceiver();
private:
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_ALWAYSLOWESTLOGIC_H_ */
| 1,991 | 37.307692 | 162 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/BufferBasedAdaptationWithRateBased.h
|
/*
* RateBasedAdaptation.h
*****************************************************************************
* Copyright (C) 2016,
* Jacques Samain <[email protected]>
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_BUFFERBASEDADAPTATIONRATE_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_BUFFERBASEDADAPTATIONRATE_H_
#include "AbstractAdaptationLogic.h"
#include "../MPD/AdaptationSetStream.h"
#include "../Input/IDASHReceiverObserver.h"
namespace libdash
{
namespace framework
{
namespace adaptation
{
class BufferBasedAdaptationWithRateBased : public AbstractAdaptationLogic
{
public:
BufferBasedAdaptationWithRateBased (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6);
virtual ~BufferBasedAdaptationWithRateBased ();
virtual LogicType GetType ();
virtual bool IsUserDependent ();
virtual bool IsRateBased ();
virtual bool IsBufferBased ();
virtual void BitrateUpdate (uint64_t bps);
virtual void SegmentPositionUpdate(uint32_t qualitybps);
virtual void DLTimeUpdate (double time);
virtual void BufferUpdate (uint32_t bufferFill);
void SetBitrate (uint32_t bufferFill);
uint64_t GetBitrate ();
virtual void SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager);
void NotifyBitrateChange ();
void OnEOS (bool value);
virtual void OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec);
void CheckedByDASHReceiver();
private:
uint64_t currentBitrate;
std::vector<uint64_t> availableBitrates;
sampleplayer::managers::IMultimediaManagerBase *multimediaManager;
dash::mpd::IRepresentation *representation;
uint32_t reservoirThreshold;
uint32_t maxThreshold;
uint32_t lastBufferFill;
int m_count;
int switchUpThreshold;
bool bufferEOS;
bool shouldAbort;
double alphaRate;
uint64_t averageBw;
uint64_t instantBw;
int myQuality;
double slackParam;
bool isCheckedForReceiver;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_BUFFERBASEDADAPTATIONRATE_H_ */
| 3,292 | 46.042857 | 242 |
h
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/SparseBayesUcb.cpp
|
/*
* SparseBayesUcb.cpp
* By Trevor Ballard and Bastian Alt, <[email protected]>, <[email protected]>
*
* Adapted from code by Michele Tortelli and Jacques Samain, whose copyright is
* reproduced below.
*
*****************************************************************************
* Copyright (C) 2016
* Michele Tortelli and Jacques Samain, <[email protected]>, <[email protected]>
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "SparseBayesUcb.h"
#include <stdio.h>
#include <math.h>
#include <chrono>
#include <string>
#include <stdint.h>
#include <iostream>
#include <sstream>
#include <chrono>
#include <inttypes.h>
#include <stdlib.h>
#include <stdarg.h>
#include <algorithm>
#include <inttypes.h>
#include <time.h>
#include <limits.h>
#include <errno.h>
#include <Python.h>
#include <chrono>
#include <thread>
const double MINIMUM_BUFFER_LEVEL_SPACING = 5.0; // The minimum space required between buffer levels (in seconds).
const uint32_t THROUGHPUT_SAMPLES = 3; // Number of samples considered for throughput estimate.
const double SAFETY_FACTOR = 0.9; // Safety factor used with bandwidth estimate.
static PyObject *pName, *pModule, *pDict, *pFuncChoose, *pFuncUpdate;
static int gil_init = 0;
using namespace dash::mpd;
using namespace libdash::framework::adaptation;
using namespace libdash::framework::input;
using namespace libdash::framework::mpd;
using std::bind;
using std::placeholders::_1;
using std::placeholders::_2;
using duration_in_seconds = std::chrono::duration<double, std::ratio<1, 1> >;
SparseBayesUcbAdaptation::SparseBayesUcbAdaptation (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, bool isVid, double arg1, double arg2, double arg3, double arg4, double arg5, double arg6) : AbstractAdaptationLogic (mpd, period, adaptationSet, isVid)
{
// Set SparseBayesUcb init STATE
this->initState = true;
this->sparseBayesUcbState = STARTUP;
this->lastDownloadTimeInstant = 0.0;
this->currentDownloadTimeInstant = 0.0;
//this->lastSegmentDownloadTime = 0.0;
this->currentQuality = 0;
this->cumQoE = 0.0;
this->bufferMaxSizeSeconds = 20.0; // It is 'bufferMax' in dash.js implementation
// Find a way to retrieve the value without hard coding it
// Set QoE weights
this->qoe_w1 = arg4;
this->qoe_w2 = arg5;
this->qoe_w3 = arg6;
// Set alpha for the EWMA (bw estimate)
this->alphaRate = 0.8;
this->bufferTargetSeconds = 12.0; // 12s (dash.js implementation) corresponds to 40% with a buffer of 30s
/// Retrieve available bitrates
std::vector<IRepresentation* > representations = this->adaptationSet->GetRepresentation();
this->availableBitrates.clear();
//L("SPARSEBAYESUCB Available Bitrates...\n");
for(size_t i = 0; i < representations.size(); i++)
{
this->availableBitrates.push_back((uint64_t)(representations.at(i)->GetBandwidth()));
//L("%d - %I64u bps\n", i+1, this->availableBitrates[i]);
}
// Check if they are in increasing order (i.e., bitrate[0] <= bitrate[1], etc.)
this->bitrateCount = this->availableBitrates.size();
// We check if we have only one birate value or if the bitrate list is irregular (i.e., it is not strictly increasing)
if (this->bitrateCount < 2 || this->availableBitrates[0] >= this->availableBitrates[1] || this->availableBitrates[this->bitrateCount - 2] >= this->availableBitrates[this->bitrateCount - 1]) {
this->sparseBayesUcbState = ONE_BITRATE;
// return 0; // Check if exit with a message is necessary
}
// Check if the following is correct
this->totalDuration = TimeResolver::GetDurationInSec(this->mpd->GetMediaPresentationDuration());
//this->segmentDuration = (double) (representations.at(0)->GetSegmentTemplate()->GetDuration() / representations.at(0)->GetSegmentTemplate()->GetTimescale() );
this->segmentDuration = 2.0;
//L("Total Duration - SPARSEBAYESUCB:\t%f\nSegment Duration - SPARSEBAYESUCB:\t%f\n",this->totalDuration, this->segmentDuration);
// if not correct --> segmentDuration = 2.0;
// Compute the SPARSEBAYESUCB Buffer Target
this->sparseBayesUcbBufferTargetSeconds = this->bufferTargetSeconds;
if (this->sparseBayesUcbBufferTargetSeconds < this->segmentDuration + MINIMUM_BUFFER_LEVEL_SPACING)
{
this->sparseBayesUcbBufferTargetSeconds = this->segmentDuration + MINIMUM_BUFFER_LEVEL_SPACING;
}
//L("SPARSEBAYESUCB Buffer Target Seconds:\t%f\n",this->sparseBayesUcbBufferTargetSeconds);
// Compute UTILTY vector, Vp, and gp
//L("SPARSEBAYESUCB Utility Values...\n");
double utility_tmp;
for (uint32_t i = 0; i < this->bitrateCount; ++i) {
utility_tmp = log(((double)this->availableBitrates[i] * (1./(double)this->availableBitrates[0])));
if(utility_tmp < 0)
utility_tmp = 0;
this->utilityVector.push_back( log(((double)this->availableBitrates[i] * (1./(double)this->availableBitrates[0]))));
//L("%d - %f\n", i+1, this->utilityVector[i]);
}
this->Vp = (this->sparseBayesUcbBufferTargetSeconds - this->segmentDuration) / this->utilityVector[this->bitrateCount - 1];
this->gp = 1.0 + this->utilityVector[this->bitrateCount - 1] / (this->sparseBayesUcbBufferTargetSeconds / this->segmentDuration - 1.0);
//L("SPARSEBAYESUCB Parameters:\tVp: %f\tgp: %f\n",this->Vp, this->gp);
/* If bufferTargetSeconds (not sparseBayesUcbBufferTargetSecond) is large enough, we might guarantee that SparseBayesUcb will never rebuffer
* unless the network bandwidth drops below the lowest encoded bitrate level. For this to work, SparseBayesUcb needs to use the real buffer
* level without the additional virtualBuffer. Also, for this to work efficiently, we need to make sure that if the buffer level
* drops to one fragment during a download, the current download does not have more bits remaining than the size of one fragment
* at the lowest quality*/
this->maxRtt = 0.2; // Is this reasonable?
if(this->sparseBayesUcbBufferTargetSeconds == this->bufferTargetSeconds) {
this->safetyGuarantee = true;
}
if (this->safetyGuarantee) {
//L("SPARSEBAYESUCB SafetyGuarantee...\n");
// we might need to adjust Vp and gp
double VpNew = this->Vp;
double gpNew = this->gp;
for (uint32_t i = 1; i < this->bitrateCount; ++i) {
double threshold = VpNew * (gpNew - this->availableBitrates[0] * this->utilityVector[i] / (this->availableBitrates[i] - this->availableBitrates[0]));
double minThreshold = this->segmentDuration * (2.0 - this->availableBitrates[0] / this->availableBitrates[i]) + maxRtt;
if (minThreshold >= this->bufferTargetSeconds) {
safetyGuarantee = false;
break;
}
if (threshold < minThreshold) {
VpNew = VpNew * (this->bufferTargetSeconds - minThreshold) / (this->bufferTargetSeconds - threshold);
gpNew = minThreshold / VpNew + this->utilityVector[i] * this->availableBitrates[0] / (this->availableBitrates[i] - this->availableBitrates[0]);
}
}
if (safetyGuarantee && (this->bufferTargetSeconds - this->segmentDuration) * VpNew / this->Vp < MINIMUM_BUFFER_LEVEL_SPACING) {
safetyGuarantee = false;
}
if (safetyGuarantee) {
this->Vp = VpNew;
this->gp = gpNew;
}
}
//L("SPARSEBAYESUCB New Parameters:\tVp: %f\tgp: %f\n",this->Vp, this->gp);
// Capping of the virtual buffer (when using it)
this->sparseBayesUcbBufferMaxSeconds = this->Vp * (this->utilityVector[this->bitrateCount - 1] + this->gp);
//L("SPARSEBAYESUCB Max Buffer Seconds:\t%f\n",this->sparseBayesUcbBufferMaxSeconds);
this->virtualBuffer = 0.0; // Check if we should use either the virtualBuffer or the safetyGuarantee
this->instantBw = 0;
this->averageBw = 0;
this->batchBw = 0; // Computed every THROUGHPUT_SAMPLES samples (average)
this->batchBwCount = 0;
this->multimediaManager = NULL;
this->lastBufferFill = 0; // (?)
this->bufferEOS = false;
this->shouldAbort = false;
this->isCheckedForReceiver = false;
this->representation = representations.at(0);
this->currentBitrate = (uint64_t) this->representation->GetBandwidth();
this->rebufferStart = 0;
this->rebufferEnd = 0;
Py_Initialize();
PyRun_SimpleString("import sys; sys.path.append('/'); import run_bandits");
pName = PyUnicode_FromString("run_bandits");
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFuncChoose = PyDict_GetItemString(pDict, "choose");
pFuncUpdate = PyDict_GetItemString(pDict, "update");
//L("SPARSEBAYESUCB Init Params - \tAlpha: %f \t BufferTarget: %f\n",this->alphaRate, this->bufferTargetSeconds);
//L("SPARSEBAYESUCB Init Current BitRate - %I64u\n",this->currentBitrate);
Debug("Buffer Adaptation SPARSEBAYESUCB: STARTED\n");
}
SparseBayesUcbAdaptation::~SparseBayesUcbAdaptation ()
{
Py_DECREF(pModule);
Py_DECREF(pName);
Py_Finalize();
}
LogicType SparseBayesUcbAdaptation::GetType ()
{
return adaptation::BufferBased;
}
bool SparseBayesUcbAdaptation::IsUserDependent ()
{
return false;
}
bool SparseBayesUcbAdaptation::IsRateBased ()
{
return true;
}
bool SparseBayesUcbAdaptation::IsBufferBased ()
{
return true;
}
void SparseBayesUcbAdaptation::SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager)
{
this->multimediaManager = _mmManager;
}
void SparseBayesUcbAdaptation::NotifyBitrateChange ()
{
if(this->multimediaManager)
if(this->multimediaManager->IsStarted() && !this->multimediaManager->IsStopping())
if(this->isVideo)
this->multimediaManager->SetVideoQuality(this->period, this->adaptationSet, this->representation);
else
this->multimediaManager->SetAudioQuality(this->period, this->adaptationSet, this->representation);
//Should Abort is done here to avoid race condition with DASHReceiver::DoBuffering()
if(this->shouldAbort)
{
//L("Aborting! To avoid race condition.");
//printf("Sending Abort request\n");
this->multimediaManager->ShouldAbort(this->isVideo);
//printf("Received Abort request\n");
}
this->shouldAbort = false;
}
uint64_t SparseBayesUcbAdaptation::GetBitrate ()
{
return this->currentBitrate;
}
int SparseBayesUcbAdaptation::getQualityFromThroughput(uint64_t bps) {
int q = 0;
for (int i = 0; i < this->availableBitrates.size(); ++i) {
if (this->availableBitrates[i] > bps) {
break;
}
q = i;
}
return q;
}
int SparseBayesUcbAdaptation::getQualityFromBufferLevel(double bufferLevelSec) {
int quality = this->bitrateCount - 1;
double score = 0.0;
for (int i = 0; i < this->bitrateCount; ++i) {
double s = (this->utilityVector[i] + this->gp - bufferLevelSec / this->Vp) / this->availableBitrates[i];
if (s > score) {
score = s;
quality = i;
}
}
return quality;
}
void SparseBayesUcbAdaptation::SetBitrate (uint32_t bufferFill)
{
int result = 0;
PyObject *pArgs, *pValue;
std::vector<IRepresentation*> representations = this->adaptationSet->GetRepresentation();
int numArms = (int)representations.size();
pValue = PyList_New(0);
for (int i=0; i<numArms; i++) {
PyObject* pTemp = PyList_New(0);
// for bufferFill
PyList_Append(pTemp, PyFloat_FromDouble((double)bufferFill/(double)100));
// for RTT
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> rttVec = this->rttMap[i];
for (int j=0; j<rttVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)rttVec[j]));
}
// for num hops
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> numHopsVec = this->numHopsMap[i];
for (int j=0; j<numHopsVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)numHopsVec[j]));
}
PyList_Append(pValue, pTemp);
Py_XDECREF(pTemp);
}
pArgs = PyTuple_New(2);
PyTuple_SetItem(pArgs, 0, PyUnicode_FromString("sbu"));
PyTuple_SetItem(pArgs, 1, pValue);
if (!gil_init) {
gil_init = 1;
PyEval_InitThreads();
PyEval_SaveThread();
}
// 2: Execute
PyGILState_STATE state = PyGILState_Ensure();
unsigned long long int execStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
pValue = PyObject_CallObject(pFuncChoose, pArgs);
unsigned long long int execEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
result = (int)PyLong_AsLong(pValue);
Py_XDECREF(pArgs);
Py_XDECREF(pValue);
PyGILState_Release(state);
int duration = (int)(execEnd - execStart);
std::cout << "stat-begin" << std::endl;
std::cout << "stat-chexecms " << duration << std::endl;
std::cout << "stat-chqual " << result << std::endl;
if (result < 0 || result > numArms-1) {
std::cout << "ERROR: Result was out of bounds. Using quality of 2." << std::endl;
result = 2;
}
this->currentQuality = result;
this->representation = this->adaptationSet->GetRepresentation().at(this->currentQuality);
this->currentBitrate = (uint64_t) this->availableBitrates[this->currentQuality];
//L("STEADY - Current Bitrate:\t%I64u\n", this->currentBitrate);
//L("ADAPTATION_LOGIC:\tFor %s:\tlast_buffer: %f\tbuffer_level: %f, instantaneousBw: %lu, AverageBW: %lu, choice: %d\n",isVideo ? "video" : "audio",(double)lastBufferFill/100 , (double)bufferFill/100, this->instantBw, this->averageBw , this->currentQuality);
this->lastBufferFill = bufferFill;
}
void SparseBayesUcbAdaptation::BitrateUpdate(uint64_t bps)
{
}
void SparseBayesUcbAdaptation::SegmentPositionUpdate (uint32_t qualitybps)
{
//L("Called SegmentPositionUpdate\n");
}
void SparseBayesUcbAdaptation::DLTimeUpdate (double time)
{
auto m_now = std::chrono::system_clock::now();
auto m_now_sec = std::chrono::time_point_cast<std::chrono::seconds>(m_now);
auto now_value = m_now_sec.time_since_epoch();
double dl_instant = now_value.count();
//this->lastSegmentDownloadTime = time;
//this->currentDownloadTimeInstant = std::chrono::duration_cast<duration_in_seconds>(system_clock::now()).count();
this->currentDownloadTimeInstant = dl_instant;
}
void SparseBayesUcbAdaptation::OnEOS (bool value)
{
this->bufferEOS = value;
}
void SparseBayesUcbAdaptation::OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec)
{
std::vector<IRepresentation*> representations = this->adaptationSet->GetRepresentation();
int numArms = (int)representations.size();
uint32_t bufferFill = (uint32_t)(bufferFillPct * (double)100);
std::cout << "stat-qual " << quality << std::endl;
////////////////
// Update MAB //
////////////////
// First calculate the real QoE for the segment:
// 1. Base quality (kbps)
// 2. Decline in quality (kbps)
// 3. Time spent rebuffering (ms)
// 1. Base quality
int baseQuality = (int)(this->availableBitrates[quality] / (uint64_t)1000);
std::cout << "stat-qoebase " << baseQuality << std::endl;
// 2. Decline in quality
this->qualityHistory[segNum] = quality;
int qualityDecline = 0;
if (this->qualityHistory[segNum] < this->qualityHistory[segNum-1]) {
int prevQuality = (int)(this->availableBitrates[this->qualityHistory[segNum-1]]/(uint64_t)1000);
int currQuality = (int)(this->availableBitrates[quality]/(uint64_t)1000);
qualityDecline = prevQuality - currQuality;
}
std::cout << "stat-qoedecl " << qualityDecline << std::endl;
// 3. Time spent rebuffering
// We just got a new segment so rebuffering has stopped
// If it occurred, we need to know for how long
int rebufferTime = 0;
if (this->rebufferStart != 0) {
if (this->rebufferEnd == 0) {
this->rebufferEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
}
rebufferTime = (int)(this->rebufferEnd - this->rebufferStart);
this->rebufferStart = 0;
}
std::cout << "stat-qoerebuffms " << rebufferTime << std::endl;
// Put it all together for the reward
// The weight of 3 comes from the SIGCOMM paper; they use 3000 because their
// rebufferTime is in seconds, but ours is milliseconds
double reward = (this->qoe_w1*(double)baseQuality) - (this->qoe_w2*(double)qualityDecline) - (this->qoe_w3*(double)rebufferTime*(double)rebufferTime);
this->cumQoE += reward;
std::cout << "stat-qoeseg " << reward << std::endl;
std::cout << "stat-qoecum " << this->cumQoE << std::endl;
// If we're still in the first K iterations, we have to try all arms. Try the one
// corresponding to this segment
// TODO would be better to put in SetBitrate, but that'd take a bit of refactoring
/*
if (segNum < numArms) {
//L("stat-initarms %d\n", segNum);
this->currentQuality = segNum;
this->representation = this->adaptationSet->GetRepresentation().at(this->currentQuality);
this->currentBitrate = (uint64_t) this->availableBitrates[this->currentQuality];
this->lastBufferFill = bufferFill;
//L("STEADY - Current Bitrate:\t%I64u\n", this->currentBitrate);
this->qualityHistory[segNum] = quality;
this->rttMap[quality] = rttVec;
this->ecnMap[quality] = ecnVec;
this->numHopsMap[quality] = numHopsVec;
this->NotifyBitrateChange();
}
else {
*/
// 1: Build args
int result = 0;
PyObject *pArgs, *pValue;
pValue = PyList_New(0);
for (int i=0; i<numArms; i++) {
PyObject* pTemp = PyList_New(0);
PyList_Append(pTemp, PyFloat_FromDouble(bufferFillPct));
// for RTT
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> tempRttVec = this->rttMap[i];
for (int j=0; j<tempRttVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)tempRttVec[j]));
}
/*
// for ECN
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> tempEcnVec = this->ecnMap[i];
for (int j=0; j<tempEcnVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)tempEcnVec[j]));
}
*/
// for num hops
PyList_Append(pTemp, PyUnicode_FromString("DELIM"));
std::vector<int> tempNumHopsVec = this->numHopsMap[i];
for (int j=0; j<tempNumHopsVec.size(); j++) {
PyList_Append(pTemp, PyFloat_FromDouble((double)tempNumHopsVec[j]));
}
PyList_Append(pValue, pTemp);
Py_XDECREF(pTemp);
}
pArgs = PyTuple_New(5);
PyTuple_SetItem(pArgs, 0, PyUnicode_FromString("sbu"));
// context
PyTuple_SetItem(pArgs, 1, pValue);
// last quality (action)
PyTuple_SetItem(pArgs, 2, PyLong_FromLong((long)quality));
// reward
PyTuple_SetItem(pArgs, 3, PyFloat_FromDouble(reward));
// timestep
PyTuple_SetItem(pArgs, 4, PyLong_FromLong((long)segNum));
if (!gil_init) {
std::cout << "WARNING: setting gil_init in BitrateUpdate" << std::endl;
gil_init = 1;
PyEval_InitThreads();
PyEval_SaveThread();
}
// 2: Execute
PyGILState_STATE state = PyGILState_Ensure();
unsigned long long int execStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
pValue = PyObject_CallObject(pFuncUpdate, pArgs);
unsigned long long int execEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
result = (int)PyLong_AsLong(pValue);
Py_XDECREF(pArgs);
Py_XDECREF(pValue);
PyGILState_Release(state);
int duration = (int)(execEnd - execStart);
std::cout << "stat-updexecms " << duration << std::endl;
if (result != 1) {
std::cout << "WARNING: Update MAB failed" << std::endl;
}
/////////////////////////////
// Update internal context //
/////////////////////////////
this->rttMap[quality] = rttVec;
//this->ecnMap[quality] = ecnVec;
this->numHopsMap[quality] = numHopsVec;
// Run MAB using the new context
this->SetBitrate(bufferFill);
this->NotifyBitrateChange();
//} <--- the commented out else statement
}
void SparseBayesUcbAdaptation::CheckedByDASHReceiver ()
{
//L("CheckedByDASHReceiver called\n");
this->isCheckedForReceiver = false;
}
void SparseBayesUcbAdaptation::BufferUpdate (uint32_t bufferFill)
{
if (bufferFill == (uint32_t)0 && this->rebufferStart == 0) {
this->rebufferStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
this->rebufferEnd = 0;
//L("Buffer is at 0; rebuffering has begun and playback has stalled\n");
}
else if (this->rebufferEnd == 0 && this->rebufferStart != 0) {
this->rebufferEnd = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
//L("Stopped rebuffering; resuming playback\n");
}
}
| 22,041 | 38.715315 | 262 |
cpp
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/Bola.h
|
/*
* Bola.h
*****************************************************************************
* Copyright (C) 2016,
* Michele Tortelli and Jacques Samain, <[email protected]>, <[email protected]>
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef LIBDASH_FRAMEWORK_ADAPTATION_BOLA_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_BOLA_H_
#include "AbstractAdaptationLogic.h"
#include "../MPD/AdaptationSetStream.h"
#include "../Input/IDASHReceiverObserver.h"
namespace libdash
{
namespace framework
{
namespace adaptation
{
class BolaAdaptation : public AbstractAdaptationLogic
{
public:
BolaAdaptation (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, bool isVid,
double arg1, double arg2, double arg3, double arg4, double arg5, double arg6);
virtual ~BolaAdaptation();
virtual LogicType GetType ();
virtual bool IsUserDependent ();
virtual bool IsRateBased ();
virtual bool IsBufferBased ();
virtual void BitrateUpdate (uint64_t bps);
virtual void SegmentPositionUpdate(uint32_t qualitybps);
virtual void DLTimeUpdate (double time);
virtual void BufferUpdate (uint32_t bufferFill);
void SetBitrate (uint32_t bufferFill);
uint64_t GetBitrate ();
virtual void SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *_mmManager);
void NotifyBitrateChange ();
void OnEOS (bool value);
virtual void OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec);
void CheckedByDASHReceiver();
int getQualityFromThroughput(uint64_t bps);
int getQualityFromBufferLevel(double bufferLevelSec);
private:
enum BolaState
{
ONE_BITRATE, // If one bitrate (or init failed), always NO_CHANGE
STARTUP, // Download fragments at most recently measured throughput
STARTUP_NO_INC, // If quality increased then decreased during startup, then quality cannot be increased.
STEADY // The buffer is primed (should be above bufferTarget)
};
bool initState;
double bufferMaxSizeSeconds; // Usually set to 30s
double bufferTargetSeconds; // It is passed as an init parameter.
// It states the difference between STARTUP and STEADY
// 12s following dash.js implementation
double bolaBufferTargetSeconds; // BOLA introduces a virtual buffer level in order to make quality decisions
// as it was filled (instead of the actual bufferTargetSeconds)
double bolaBufferMaxSeconds; // When using the virtual buffer, it must be capped.
uint32_t bufferTargetPerc; // Computed considering a bufferSize = 30s
double totalDuration; // Total video duration in seconds (taken from MPD)
double segmentDuration; // Segment duration in seconds
std::vector<uint64_t> availableBitrates;
std::vector<double> utilityVector;
uint32_t bitrateCount; // Number of available bitrates
BolaState bolaState; // Keeps track of Bola state
// Bola Vp and gp (multiplied by the segment duration 'p')
// They are dimensioned such that log utility would always prefer
// - the lowest bitrate when bufferLevel = segmentDuration
// - the highest bitrate when bufferLevel = bufferTarget
double Vp;
double gp;
bool safetyGuarantee;
double maxRtt;
double virtualBuffer;
uint64_t currentBitrate;
int currentQuality;
uint64_t batchBw;
int batchBwCount;
std::vector<uint64_t> batchBwSamples;
uint64_t instantBw;
uint64_t averageBw;
double lastDownloadTimeInstant;
double currentDownloadTimeInstant;
double lastSegmentDownloadTime;
uint32_t lastBufferFill;
bool bufferEOS;
bool shouldAbort;
double alphaRate;
bool isCheckedForReceiver;
std::map<int, int> qualityHistory;
unsigned long long int rebufferStart;
unsigned long long int rebufferEnd;
double cumQoE;
double qoe_w1;
double qoe_w2;
double qoe_w3;
sampleplayer::managers::IMultimediaManagerBase *multimediaManager;
dash::mpd::IRepresentation *representation;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_BOLA_H_ */
| 5,989 | 46.92 | 174 |
h
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.