repo
stringlengths 1
152
⌀ | file
stringlengths 15
205
| code
stringlengths 0
41.6M
| file_length
int64 0
41.6M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 90
values |
---|---|---|---|---|---|---|
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-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 |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/ManualAdaptation.cpp | /*
* ManualAdaptation.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 "ManualAdaptation.h"
using namespace dash::mpd;
using namespace libdash::framework::adaptation;
using namespace libdash::framework::input;
using namespace libdash::framework::mpd;
ManualAdaptation::ManualAdaptation (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, bool isVid) :
AbstractAdaptationLogic (mpd, period, adaptationSet, isVid)
{
}
ManualAdaptation::~ManualAdaptation ()
{
}
LogicType ManualAdaptation::GetType ()
{
return adaptation::Manual;
}
bool ManualAdaptation::IsUserDependent ()
{
return true;
}
bool ManualAdaptation::IsRateBased ()
{
return false;
}
bool ManualAdaptation::IsBufferBased ()
{
return false;
}
void ManualAdaptation::BitrateUpdate (uint64_t bps)
{
}
void ManualAdaptation::SegmentPositionUpdate (uint32_t qualitybps)
{
}
void ManualAdaptation::DLTimeUpdate (double time)
{
}
void ManualAdaptation::BufferUpdate (uint32_t bufferfill)
{
}
void ManualAdaptation::OnEOS (bool value)
{
}
void ManualAdaptation::OnSegmentDownloaded (double bufferFillPct, int segNum, int quality, std::vector<int> rttVec, std::vector<int> numHopsVec)
{
}
void ManualAdaptation::CheckedByDASHReceiver ()
{
}
void ManualAdaptation::SetMultimediaManager (sampleplayer::managers::IMultimediaManagerBase *mmM)
{
}
| 1,803 | 23.378378 | 155 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Adaptation/BufferBasedAdaptation.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_BUFFERBASEDADAPTATION_H_
#define LIBDASH_FRAMEWORK_ADAPTATION_BUFFERBASEDADAPTATION_H_
#include "AbstractAdaptationLogic.h"
#include "../MPD/AdaptationSetStream.h"
#include "../Input/IDASHReceiverObserver.h"
namespace libdash
{
namespace framework
{
namespace adaptation
{
class BufferBasedAdaptation : public AbstractAdaptationLogic
{
public:
BufferBasedAdaptation (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 ~BufferBasedAdaptation ();
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;
bool bufferEOS;
bool shouldAbort;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_BUFFERBASEDADAPTATION_H_ */
| 2,885 | 45.548387 | 236 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/IDASHReceiverObserver.h | /*
* IDASHReceiverObserver.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_INPUT_IDASHRECEIVEROBSERVER_H_
#define LIBDASH_FRAMEWORK_INPUT_IDASHRECEIVEROBSERVER_H_
namespace libdash
{
namespace framework
{
namespace input
{
class IDASHReceiverObserver
{
public:
virtual ~IDASHReceiverObserver () {}
virtual void OnSegmentDownloaded () = 0;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_INPUT_IDASHRECEIVEROBSERVER_H_ */
| 938 | 28.34375 | 79 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/MediaObjectDecoder.h | /*
* MediaObjectDecoder.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_INPUT_MEDIAOBJECTDECODER_H_
#define LIBDASH_FRAMEWORK_INPUT_MEDIAOBJECTDECODER_H_
#include "../Portable/MultiThreading.h"
#include "../Input/IDataReceiver.h"
#include "../Input/IMediaObjectDecoderObserver.h"
#include "../../Decoder/IAudioObserver.h"
#include "../../Decoder/IVideoObserver.h"
#include "../../Decoder/LibavDecoder.h"
#include "MediaObject.h"
namespace libdash
{
namespace framework
{
namespace input
{
class MediaObjectDecoder : public IDataReceiver, public sampleplayer::decoder::IAudioObserver, public sampleplayer::decoder::IVideoObserver
{
public:
MediaObjectDecoder (MediaObject *initSeg, MediaObject *mediaSeg, IMediaObjectDecoderObserver *observer, bool nodecoding);
virtual ~MediaObjectDecoder ();
bool Start ();
void Stop ();
void WaitForDelete ();
virtual int Read (uint8_t *buf, int buf_size);
virtual void OnVideoDataAvailable (const uint8_t **data, sampleplayer::decoder::videoFrameProperties* props);
virtual void OnAudioDataAvailable (const uint8_t **data, sampleplayer::decoder::audioFrameProperties* props);
virtual bool IsAudio ();
private:
THREAD_HANDLE threadHandle;
IMediaObjectDecoderObserver *observer;
sampleplayer::decoder::LibavDecoder *decoder;
MediaObject *initSegment;
MediaObject *mediaSegment;
bool run;
bool decoderInitialized;
size_t initSegmentOffset;
bool noDecoding;
static void* Decode (void *data);
static void* No_Decode (void *data);
void Notify ();
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_INPUT_MEDIAOBJECTDECODER_H_ */
| 2,785 | 42.53125 | 151 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/DASHReceiver.cpp | /*
* DASHReceiver.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 "DASHReceiver.h"
#include <stdio.h>
#include <boost/bind.hpp>
#include <iostream>
using namespace libdash::framework::input;
using namespace libdash::framework::buffer;
using namespace libdash::framework::mpd;
using namespace dash::mpd;
using duration_in_seconds = std::chrono::duration<double, std::ratio<1, 1> >;
DASHReceiver::DASHReceiver (IMPD *mpd, IDASHReceiverObserver *obs, MediaObjectBuffer *buffer, uint32_t bufferSize, bool ndnEnabled, double ndnAlpha, bool chunkGranularityEnabled, int sample) :
mpd (mpd),
period (NULL),
adaptationSet (NULL),
representation (NULL),
adaptationSetStream (NULL),
representationStream (NULL),
segmentNumber (0),
observer (obs),
buffer (buffer),
bufferSize (bufferSize),
isBuffering (false),
withFeedBack (false),
isNDN (ndnEnabled),
ndnAlpha (ndnAlpha),
previousQuality (0),
isPaused (false),
threadComplete (false),
isScheduledPaced (false),
targetDownload (0.0),
downloadingTime (0.0),
chunkGranularity (chunkGranularityEnabled),
samplesize (sample)
{
this->period = this->mpd->GetPeriods().at(0);
this->adaptationSet = this->period->GetAdaptationSets().at(0);
this->representation = this->adaptationSet->GetRepresentation().at(0);
this->adaptationSetStream = new AdaptationSetStream(mpd, period, adaptationSet);
this->representationStream = adaptationSetStream->GetRepresentationStream(this->representation);
this->segmentOffset = CalculateSegmentOffset();
this->conn = NULL;
this->initConn = NULL;
if(isNDN)
{
#ifdef NDNICPDOWNLOAD
this->chunktimeObs = new ChunktimeObserver(this->samplesize);
this->chunktimeObs->addThroughputSignal(boost::bind(&DASHReceiver::NotifybpsChunk, this, _1)); //pass the function to register as a Slot at ChunktimeObserver-Signal
this->chunktimeObs->addContextSignal(boost::bind(&DASHReceiver::NotifyContextChunk, this, _1, _2));
this->conn = new NDNConnection(this->ndnAlpha, this->chunktimeObs);
this->initConn = new NDNConnection(this->ndnAlpha, this->chunktimeObs);
#else
this->conn = new NDNConnectionConsumerApi(this->ndnAlpha);
this->initConn = new NDNConnectionConsumerApi(this->ndnAlpha);
#endif
}
InitializeCriticalSection(&this->monitorMutex);
InitializeCriticalSection(&this->monitorPausedMutex);
InitializeConditionVariable(&this->paused);
}
DASHReceiver::~DASHReceiver ()
{
delete this->adaptationSetStream;
DeleteCriticalSection(&this->monitorMutex);
DeleteCriticalSection(&this->monitorPausedMutex);
DeleteConditionVariable(&this->paused);
}
void DASHReceiver::SetAdaptationLogic(adaptation::IAdaptationLogic *_adaptationLogic)
{
this->adaptationLogic = _adaptationLogic;
this->withFeedBack = this->adaptationLogic->IsRateBased();
}
bool DASHReceiver::Start ()
{
if(this->isBuffering)
return false;
this->isBuffering = true;
this->bufferingThread = CreateThreadPortable (DoBuffering, this);
if(this->bufferingThread == NULL)
{
this->isBuffering = false;
return false;
}
return true;
}
void DASHReceiver::Stop ()
{
if(!this->isBuffering)
return;
this->isBuffering = false;
this->buffer->SetEOS(true);
if(this->bufferingThread != NULL)
{
JoinThread(this->bufferingThread);
DestroyThreadPortable(this->bufferingThread);
}
}
MediaObject* DASHReceiver::GetNextSegment ()
{
ISegment *seg = NULL;
EnterCriticalSection(&this->monitorPausedMutex);
while(this->isPaused)
SleepConditionVariableCS(&this->paused, &this->monitorPausedMutex, INFINITE);
if(this->segmentNumber >= this->representationStream->GetSize())
{
LeaveCriticalSection(&this->monitorPausedMutex);
return NULL;
}
seg = this->representationStream->GetMediaSegment(this->segmentNumber + this->segmentOffset);
if (seg != NULL)
{
std::vector<IRepresentation *> rep = this->adaptationSet->GetRepresentation();
int quality = 0;
while(quality != rep.size() - 1)
{
if(rep.at(quality) == this->representation)
break;
quality++;
}
Debug("DASH receiver: Next segment is: %s / %s\n",((dash::network::IChunk*)seg)->Host().c_str(),((dash::network::IChunk*)seg)->Path().c_str());
int realBPS = rep.at(quality)->GetSpecificSegmentSize(std::to_string(segmentNumber+1));
L("DASH_Receiver:\t%s\t%d\t%u\tRealBPS: %u\n", ((dash::network::IChunk*)seg)->Path().c_str() ,quality, rep.at(quality)->GetBandwidth(), realBPS);
if(quality != previousQuality)
{
L("DASH_Receiver:\tQUALITY_SWITCH\t%s\t%d\t%d\n", (quality > previousQuality) ?"UP" : "DOWN", previousQuality, quality);
previousQuality = quality;
}
//TODO: Somewhere after this point there is an delay
MediaObject *media = new MediaObject(seg, this->representation,this->withFeedBack);
this->segmentNumber++;
this->adaptationLogic->SegmentPositionUpdate(rep.at(quality)->GetBandwidth());
LeaveCriticalSection(&this->monitorPausedMutex);
return media;
}
LeaveCriticalSection(&this->monitorPausedMutex);
return NULL;
}
MediaObject* DASHReceiver::GetSegment (uint32_t segNum)
{
ISegment *seg = NULL;
if(segNum >= this->representationStream->GetSize())
return NULL;
seg = this->representationStream->GetMediaSegment(segNum + segmentOffset);
if (seg != NULL)
{
MediaObject *media = new MediaObject(seg, this->representation);
return media;
}
return NULL;
}
MediaObject* DASHReceiver::GetInitSegment ()
{
ISegment *seg = NULL;
seg = this->representationStream->GetInitializationSegment();
if (seg != NULL)
{
MediaObject *media = new MediaObject(seg, this->representation);
return media;
}
return NULL;
}
MediaObject* DASHReceiver::FindInitSegment (dash::mpd::IRepresentation *representation)
{
if (!this->InitSegmentExists(representation))
return NULL;
return this->initSegments[representation];
}
uint32_t DASHReceiver::GetPosition ()
{
return this->segmentNumber;
}
void DASHReceiver::SetPosition (uint32_t segmentNumber)
{
// some logic here
this->segmentNumber = segmentNumber;
}
void DASHReceiver::SetPositionInMsecs (uint32_t milliSecs)
{
// some logic here
this->positionInMsecs = milliSecs;
}
void DASHReceiver::SetRepresentation (IPeriod *period, IAdaptationSet *adaptationSet, IRepresentation *representation)
{
EnterCriticalSection(&this->monitorMutex);
bool periodChanged = false;
if (this->representation == representation)
{
LeaveCriticalSection(&this->monitorMutex);
return;
}
this->representation = representation;
if (this->adaptationSet != adaptationSet)
{
this->adaptationSet = adaptationSet;
if (this->period != period)
{
this->period = period;
periodChanged = true;
}
delete this->adaptationSetStream;
this->adaptationSetStream = NULL;
this->adaptationSetStream = new AdaptationSetStream(this->mpd, this->period, this->adaptationSet);
}
this->representationStream = this->adaptationSetStream->GetRepresentationStream(this->representation);
this->DownloadInitSegment(this->representation);
if (periodChanged)
{
this->segmentNumber = 0;
this->CalculateSegmentOffset();
}
LeaveCriticalSection(&this->monitorMutex);
}
libdash::framework::adaptation::IAdaptationLogic* DASHReceiver::GetAdaptationLogic ()
{
return this->adaptationLogic;
}
dash::mpd::IRepresentation* DASHReceiver::GetRepresentation ()
{
return this->representation;
}
uint32_t DASHReceiver::CalculateSegmentOffset ()
{
if (mpd->GetType() == "static")
return 0;
uint32_t firstSegNum = this->representationStream->GetFirstSegmentNumber();
uint32_t currSegNum = this->representationStream->GetCurrentSegmentNumber();
uint32_t startSegNum = currSegNum - 2*bufferSize;
return (startSegNum > firstSegNum) ? startSegNum : firstSegNum;
}
void DASHReceiver::NotifySegmentDownloaded (double bufferFillPct, int segNum, int quality)
{
this->observer->OnSegmentDownloaded();
std::vector<int> rttVec = this->rttMap[quality];
std::vector<int> numHopsVec = this->numHopsMap[quality];
this->adaptationLogic->OnSegmentDownloaded(bufferFillPct, segNum, quality, rttVec, numHopsVec);
this->rttMap[quality].clear();
this->numHopsMap[quality].clear();
}
void DASHReceiver::NotifyBitrateChange(dash::mpd::IRepresentation *representation)
{
if(this->representation != representation)
{
this->representation = representation;
this->SetRepresentation(this->period,this->adaptationSet,this->representation);
}
}
void DASHReceiver::DownloadInitSegment (IRepresentation* rep)
{
if (this->InitSegmentExists(rep))
return;
MediaObject *initSeg = NULL;
initSeg = this->GetInitSegment();
if (initSeg)
{
initSeg->StartDownload(this->initConn);
this->initSegments[rep] = initSeg;
initSeg->WaitFinished(true);
}
}
bool DASHReceiver::InitSegmentExists (IRepresentation* rep)
{
if (this->initSegments.find(rep) != this->initSegments.end())
return true;
return false;
}
void DASHReceiver::Notifybps (uint64_t bps)
{
if(this)
{
if(this->adaptationLogic)
{
if(this->withFeedBack)
{
this->adaptationLogic->BitrateUpdate(bps);
}
}
}
}
void DASHReceiver::NotifybpsSegment (uint64_t bps) //segment-based feedback enabled
{
if(!chunkGranularity)
this->Notifybps(bps);
}
void DASHReceiver::NotifybpsChunk (uint64_t bps) //chunk-based feedback enabled
{
if(chunkGranularity)
this->Notifybps(bps);
}
void DASHReceiver::NotifyContextChunk (uint64_t rtt, uint64_t numHops)
{
int rttSeconds = (int)(rtt / (uint64_t)1000); // actually milliseconds?
std::vector<IRepresentation *> rep = this->adaptationSet->GetRepresentation();
int quality = 0;
while(quality != rep.size() - 1)
{
if(rep.at(quality) == this->representation)
break;
quality++;
}
this->rttMap[quality].push_back(rttSeconds);
this->numHopsMap[quality].push_back((int)numHops);
}
void DASHReceiver::NotifyDlTime (double time)
{
if(this)
{
if(this->adaptationLogic)
{
if(this->withFeedBack)
{
//std::cout << "DASHReceiver::NotifyDlTime call " << time << "seconds \n";
this->adaptationLogic->DLTimeUpdate(time);
}
}
}
}
void DASHReceiver::NotifyCheckedAdaptationLogic()
{
this->adaptationLogic->CheckedByDASHReceiver();
}
//Is only called when this->adaptationLogic->IsBufferBased
void DASHReceiver::OnSegmentBufferStateChanged(uint32_t fillstateInPercent)
{
this->adaptationLogic->BufferUpdate(fillstateInPercent);
}
void DASHReceiver::OnEOS(bool value)
{
this->adaptationLogic->OnEOS(value);
}
/* Thread that does the buffering of segments */
void* DASHReceiver::DoBuffering (void *receiver)
{
DASHReceiver *dashReceiver = (DASHReceiver *) receiver;
dashReceiver->DownloadInitSegment(dashReceiver->GetRepresentation());
MediaObject *media = dashReceiver->GetNextSegment();
dashReceiver->NotifyCheckedAdaptationLogic();
media->SetDASHReceiver(dashReceiver);
std::chrono::time_point<std::chrono::system_clock> m_start_time = std::chrono::system_clock::now();
while(media != NULL && dashReceiver->isBuffering)
{
if(dashReceiver->isScheduledPaced)
{
double delay = std::chrono::duration_cast<duration_in_seconds>(std::chrono::system_clock::now() - m_start_time).count();
L("-DASH-Reciever: Waiting for next Download in DoBufferung %f, targetdownload: %f, delay: %f\n", dashReceiver->targetDownload - delay, dashReceiver->targetDownload, delay);
//Only wait when buffer if more than 80 percent full
if(delay < dashReceiver->targetDownload && ((double) dashReceiver->buffer->Length()/(double) dashReceiver->buffer->Capacity()) > 0.9)
{
sleep(dashReceiver->targetDownload - delay);
}
}
m_start_time = std::chrono::system_clock::now();
media->StartDownload(dashReceiver->conn);
media->WaitFinished(false);
if (!dashReceiver->buffer->PushBack(media))
{
dashReceiver->threadComplete = true;
return NULL;
}
// Get the quality so we can notify the adaptation logic
std::vector<IRepresentation *> rep = dashReceiver->adaptationSet->GetRepresentation();
int quality = 0;
while(quality != rep.size() - 1)
{
if(rep.at(quality) == dashReceiver->representation)
break;
quality++;
}
double bufferFillPct = (double) dashReceiver->buffer->Length()/(double) dashReceiver->buffer->Capacity();
dashReceiver->NotifySegmentDownloaded(bufferFillPct, dashReceiver->segmentNumber, quality);
media = dashReceiver->GetNextSegment();
dashReceiver->NotifyCheckedAdaptationLogic();
if(media)
media->SetDASHReceiver(dashReceiver);
}
dashReceiver->buffer->SetEOS(true);
dashReceiver->threadComplete = true;
return NULL;
}
void DASHReceiver::ShouldAbort ()
{
Debug("DASH RECEIVER SEGMENT --\n");
this->segmentNumber--;
Debug("DASH RECEIVER ABORT REQUEST\n");
this->buffer->ShouldAbort();
}
void DASHReceiver::Seeking (int offset)
{
EnterCriticalSection(&this->monitorPausedMutex);
this->isPaused = true;
this->ShouldAbort();
this->buffer->Clear();
this->segmentNumber = this->segmentNumber + offset;
if((int)this->segmentNumber < 0)
this->segmentNumber = 0;
this->isPaused = false;
WakeAllConditionVariable(&this->paused);
LeaveCriticalSection(&this->monitorPausedMutex);
}
void DASHReceiver::FastForward ()
{
//Seeking 30s in the future (15 segments = 2 x 15 seconds)
this->Seeking(15);
}
void DASHReceiver::FastRewind ()
{
this->Seeking(-15);
if(this->threadComplete)
{
this->buffer->SetEOS(false);
this->isBuffering = true;
this->bufferingThread = CreateThreadPortable (DoBuffering, this);
this->threadComplete = false;
}
}
void DASHReceiver::SetTargetDownloadingTime (double target)
{
this->isScheduledPaced = true;
this->targetDownload = target;
}
| 15,595 | 31.356846 | 201 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/NDNConnection.h | /*
* NDNConnection.h
*****************************************************************************
* Header file for NDNx input module for libdash
*
* Author: Qian Li <[email protected]>
* Jacques Samain <[email protected]>
*
* Copyright (C) 2016 IRT SystemX
*
* Based on NDNx input module for VLC by Jordan Augé
* Portions Copyright (C) 2015 Cisco Systems
* Based on CCNx input module for libdash by
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
* Based on the NDNx input module by UCLA
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*****************************************************************************/
#ifndef NDNCONNECTION_H_
#define NDNCONNECTION_H_
#include "../libdash/source/portable/Networking.h"
#include "INDNConnection.h"
#include "../../debug.h"
#include "log/log.h"
#include <string>
#include <stdint.h>
#include <iostream>
#include <sstream>
#include <chrono>
#include <inttypes.h>
#include <stdlib.h>
#include <stdarg.h>
#include <algorithm>
#include<ndn-icp-download.hpp>
#include <ndn-cxx/face.hpp>
#include <ndn-cxx/security/key-chain.hpp>
#include <ndn-cxx/util/command-interest-generator.hpp>
#include <inttypes.h>
#include <time.h>
#include <limits.h>
#include <errno.h>
#include <boost/exception/diagnostic_information.hpp>
//logging purpose
#include <chrono>
#include <stdarg.h>
#define DEFAULT_LIFETIME 250
#define RETRY_TIMEOUT 25
//typedef struct {
// volatile uint64_t i_pos;
// volatile int eof;
//} ndn_cxx_libdash_data_t;
typedef struct {
uint8_t data[10000];
uint64_t start_offset;
uint64_t size;
} buffer_t;
namespace libdash {
namespace framework {
namespace input {
class NDNConnection : public INDNConnection, public ndn::NdnIcpDownloadObserver {
public:
NDNConnection(double alpha);
NDNConnection(double alpha, ChunktimeObserver* c_obs);
~NDNConnection();
virtual void Init(dash::network::IChunk *chunk);
void InitForMPD(const std::string& url);
virtual int Read(uint8_t *data, size_t len, dash::network::IChunk *chunk);
virtual int ReadStopAndWait(uint8_t *data, size_t len, dash::network::IChunk *chunk);
virtual int ReadBetter(uint8_t *data, size_t len, dash::network::IChunk *chunk);
virtual int ReadFull(uint8_t *data, size_t len, dash::network::IChunk *chunk);
int Read(uint8_t *data, size_t len);
virtual int Peek(uint8_t *data, size_t len, dash::network::IChunk *chunk);
virtual double GetAverageDownloadingSpeed();
virtual double GetDownloadingTime();
virtual void doFetch();
virtual void onData(const ndn::Interest &interest, const ndn::Data &data);
virtual void onTimeout(const ndn::Interest &interest);
/*
* IDASHMetrics
* Can't be deleted...
*/
const std::vector<dash::metrics::ITCPConnection *> &GetTCPConnectionList() const;
const std::vector<dash::metrics::IHTTPTransaction *> &GetHTTPTransactionList() const;
/*
* NdnIcpDownloadObserver
*/
virtual void notifyStats(double WinSize, double RTT);
virtual void notifyChunkStats(std::string chunkName, double chunkThroughput); //for measurements on chunk-level
private:
uint64_t i_chunksize;
int i_lifetime;
int i_missed_co;
/**< number of content objects we missed in NDNBlock */
buffer_t m_buffer;
std::string m_name;
ndn::Name m_recv_name;
ndn::Face m_face;
int m_first;
bool m_isFinished;
uint64_t m_nextSeg;
double ndnAlpha;
bool ndnRateBased;
bool allow_stale;
int sysTimeout;
unsigned InitialMaxwindow;
unsigned int timer;
double drop_factor;
double p_min;
double beta;
unsigned int gamma;
unsigned int samples;
unsigned int nchunks; // XXX chunks=-1 means: download the whole file!
bool output;
bool report_path;
ndn::NdnIcpDownload *ndnicpdownload;
bool res;
std::vector<char> mdata;
char* deezData;
int datSize;
int dataPos;
int firstChunk;
double speed; // in bps
double dnltime; //in secs
uint64_t sizeDownloaded;
std::chrono::time_point<std::chrono::system_clock> m_start_time;
std::vector<dash::metrics::ITCPConnection *> tcpConnections;
std::vector<dash::metrics::IHTTPTransaction *> httpTransactions;
uint64_t cumulativeBytesReceived;
double dnltime_chunk;
double speed_chunk;
std::chrono::time_point<std::chrono::system_clock> m_last_fetch_chunk;
};
}
}
}
#endif /* NDNCONNECTION_H_ */
| 5,780 | 31.116667 | 127 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/NDNConnection.cpp | /*
* NDNConnection.cpp
*****************************************************************************
* NDNx input module for libdash
*
* Author: Qian Li <[email protected]>
* Jacques Samain <[email protected]>
*
* Copyright (C) 2016 IRT SystemX, Cisco
*
* Based on NDNx input module for VLC by Jordan Augé
* Portions Copyright (C) 2015 Cisco Systems
* Based on CCNx input module for libdash by
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
* Based on the NDNx input module by UCLA
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Email: [email protected]
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*****************************************************************************/
#ifdef NDNICPDOWNLOAD
#include "NDNConnection.h"
#include <iostream>
#define BOOST_THREAD_PROVIDES_FUTURE
#include <boost/thread.hpp>
#include <boost/thread/future.hpp>
#include <iostream>
#include <boost/bind.hpp>
/*****************************************************************************
* Module descriptor
*****************************************************************************/
using namespace libdash::framework::input;
using namespace dash;
using namespace dash::network;
using namespace dash::metrics;
using std::bind;
using std::placeholders::_1;
using std::placeholders::_2;
using duration_in_seconds = std::chrono::duration<double, std::ratio<1, 1> >;
NDNConnection::NDNConnection(double alpha, ChunktimeObserver* c_obs) :
m_recv_name(std::string()),
m_first(1),
m_isFinished(false),
cumulativeBytesReceived(0),
ndnAlpha(alpha)
{
i_chunksize = -1;
i_missed_co = 0;
i_lifetime = DEFAULT_LIFETIME;
allow_stale = false;
InitialMaxwindow = RECEPTION_BUFFER - 1; // Constants declared inside ndn-icp-download.hpp
double InitialWindow = 50;
timer = DEFAULT_INTEREST_TIMEOUT;
drop_factor = 0.96;
p_min = P_MIN;
beta = 0.97; //Packet loss occurs burst so e.g. 250*0,95^10 was 0.05 decrease factor
gamma = 2.5; //growth factor, was 1 increase to 5
samples = SAMPLES;
output = false;
report_path = false;
this->firstChunk = -1;
output = false;
report_path = false;
this->ndnicpdownload = new ndn::NdnIcpDownload(this->InitialMaxwindow,InitialWindow, this->gamma, this->beta, this->allow_stale, 1000);
this->ndnicpdownload->setAlpha(ndnAlpha);
ndnicpdownload->addObserver(this); //ALWAYS OBSERVE
if(c_obs != NULL)
ndnicpdownload->addObserver(c_obs);
std::shared_ptr<ndn::DataPath> initPath = std::make_shared<ndn::DataPath>(drop_factor, p_min, timer, samples);
initPath->setAlpha(ndnAlpha);
ndnicpdownload->insertToPathTable(DEFAULT_PATH_ID, initPath);
ndnicpdownload->setCurrentPath(initPath);
ndnicpdownload->setStartTimeToNow();
ndnicpdownload->setLastTimeOutToNow();
ndnicpdownload->setUnversioned(true);
if (output)
ndnicpdownload->enableOutput();
if (report_path)
ndnicpdownload->enablePathReport();
Debug("NDN class created\n");
}
NDNConnection::~NDNConnection() {
delete ndnicpdownload;
}
void NDNConnection::Init(IChunk *chunk) {
Debug("NDN Connection: STARTING\n");
m_first = 1;
m_buffer.size = 0;
sizeDownloaded = 0;
m_name = "ndn:/" + chunk->Host() + chunk->Path();
m_nextSeg = 0;
m_isFinished = false;
res = false;
dataPos = 0;
datSize = 0;
deezData = NULL;
Debug("NDN_Connection:\tINTIATED_to_name %s\n", m_name.c_str());
L("NDN_Connection:\tSTARTING DOWNLOAD %s\n", m_name.c_str());
}
void NDNConnection::InitForMPD(const std::string& url)
{
m_first = 1;
m_buffer.size = 0;
sizeDownloaded = 0;
if(url.find("//") != std::string::npos)
{
int pos = url.find("//");
char* myName = (char*)malloc(strlen(url.c_str()) - 1);
strncpy(myName, url.c_str(), pos + 1);
strncpy(myName + pos + 1, url.c_str() + pos + 2, strlen(url.c_str()) - pos - 2);
m_name = std::string(myName);
}
else
{
m_name = url;
}
m_nextSeg = 0;
m_isFinished = false;
res = false;
dataPos = 0;
datSize = 0;
deezData = NULL;
Debug("NDN_Connection:\tINTIATED_for_mpd %s\n", m_name.c_str());
L("NDN_Connection:\tSTARTING DOWNLOAD %s\n", m_name.c_str());
}
int NDNConnection::Peek(uint8_t *data, size_t len, IChunk *chunk) {
return -1;
}
void NDNConnection::doFetch() {
ndn::Name name(m_name);
if (m_first == 0)
{
name.append(m_recv_name[-2]).appendSegment(m_nextSeg);
}
ndn::Interest interest(name, ndn::time::milliseconds(i_lifetime));
Debug("fetching %s\n", m_name.c_str());
if (m_first == 1)
{
m_start_time = std::chrono::system_clock::now();
m_last_fetch_chunk = std::chrono::system_clock::now();
interest.setMustBeFresh(true);
#ifdef FRESH
} else {
interest.setMustBeFresh(true);
#endif // FRESH
}
Debug("NDN_Init_CHUNK:\n" );
L("NDN_Init_CHUNK:\n" );
m_face.expressInterest(interest, bind(&NDNConnection::onData, this, _1, _2),
bind(&NDNConnection::onTimeout, this, _1));
}
/*****************************************************************************
* CALLBACKS
*****************************************************************************/
void NDNConnection::onData(const ndn::Interest &interest, const ndn::Data &data) {
m_nextSeg++;
if (m_isFinished)
{
return;
}
if (m_first == 1) {
m_recv_name = data.getName();
i_chunksize = data.getContent().value_size();
m_first = 0;
}
if (true) {
dnltime_chunk = std::chrono::duration_cast<duration_in_seconds>(std::chrono::system_clock::now() - m_last_fetch_chunk).count();
speed_chunk = (double) (i_chunksize * 8/ dnltime_chunk);
L("NDNConnection::onData\n");
Debug("NDN_Connection_SEGMENT:\tonData %s, Average_DL: %f\n", m_name.c_str(), speed_chunk);
L("NDN_Connection_SEGMENT:\tonData %s, Average_DL: %f\n", m_name.c_str(), speed_chunk);
m_last_fetch_chunk = std::chrono::system_clock::now();
}
const ndn::Block &content = data.getContent();
memcpy(m_buffer.data, reinterpret_cast<const char *>(content.value()), content.value_size());
m_buffer.size = content.value_size();
m_buffer.start_offset = 0;
sizeDownloaded += m_buffer.size;
const ndn::name::Component& finalBlockId = data.getMetaInfo().getFinalBlockId();
if (finalBlockId == data.getName()[-1])
{
//Stopping ReadStopAndWait when last segment was fetched in this method
m_isFinished = true;
}
}
void NDNConnection::onTimeout(const ndn::Interest &interest) {
//TODO What do we do on timeouts?
/* m_buffer.size = 0;
m_buffer.start_offset = 0;
if (!m_first && interest.getName()[-1].toSegment() == m_cid_timing_out) {
m_timeout_counter = (m_timeout_counter + 1) % (i_retrytimeout + 2);
if (m_timeout_counter > NDN_MAX_NDN_GET_TRYS) {
b_last = true;
}
}
else {
m_cid_timing_out = m_first ? 0 : interest.getName()[-1].toSegment();
m_timeout_counter = 1;
if (m_timeout_counter > NDN_MAX_NDN_GET_TRYS) {
Debug("Abort, abort\n\n");
b_last = true;
}
}
*/
}
int NDNConnection::ReadStopAndWait(uint8_t *data, size_t len, IChunk *chunk) {
while (true) {
if (m_isFinished)
{
this->dnltime = std::chrono::duration_cast<duration_in_seconds>(std::chrono::system_clock::now() - m_start_time).count();
speed = (double) (sizeDownloaded * 8/ this->dnltime);
cumulativeBytesReceived += sizeDownloaded;
L("NDN_Connection:\tFINISHED DOWNLOADING %s, Average_DL: %f, size: %lu, cumulative: %lu\n", m_name.c_str(), speed, sizeDownloaded, cumulativeBytesReceived);
return 0;
}
doFetch();
try {
m_face.processEvents();
} catch (...) {
std::cerr << "Unexpected exception during the fetching, diagnostic informations:\n" <<
boost::current_exception_diagnostic_information();
return 0;
}
if (m_buffer.size <= 0) {
i_missed_co++;
//i_missed_co is the number of timeouts we have during the DL of one chunk
continue;
}
memcpy(data, m_buffer.data, m_buffer.size);
if (m_buffer.size > 0) {
return m_buffer.size;
}
}
}
int NDNConnection::ReadBetter(uint8_t *data, size_t len, IChunk *chunk) {
if(this->firstChunk == -1) //this means that we start the DL, thus the timer is launched.
m_start_time = std::chrono::system_clock::now();
if(res)
{
this->dnltime = std::chrono::duration_cast<duration_in_seconds>(std::chrono::system_clock::now() - m_start_time).count();
speed = (double) (sizeDownloaded * 8 / this->dnltime);
cumulativeBytesReceived += sizeDownloaded;
L("NDN_Connection:\tFINISHED DOWNLOADING %s Average_DL: %f size: %lu cumulative: %lu \n", m_name.c_str(), speed, sizeDownloaded, cumulativeBytesReceived);
return 0;
}
this->mdata.clear();
nchunks = len / 1000; //TODO how to know in advance the chunksize, ie: 1000?
this->res = this->ndnicpdownload->download(this->m_name, &(this->mdata), this->firstChunk, nchunks);
int size = this->mdata.size();
int i = 0;
for(std::vector<char>::const_iterator it = this->mdata.begin(); it != this->mdata.end(); it++)
{
data[i] = *it;
i++;
}
if(this->firstChunk == -1)
this->firstChunk = 0;
this->firstChunk += nchunks;
sizeDownloaded += size;
return size;
}
int NDNConnection::ReadFull(uint8_t *data, size_t len, IChunk *chunk) {
if(!res)
{
L("NDNConnection::ReadFull-Init\n");
m_start_time = std::chrono::system_clock::now();
}
if(res)
{
if(this->dataPos == this->datSize)
{
this->dnltime = std::chrono::duration_cast<duration_in_seconds>(std::chrono::system_clock::now() - m_start_time).count();
if(!this->ndnRateBased)
speed = (double) (sizeDownloaded * 8 / this->dnltime);
cumulativeBytesReceived += sizeDownloaded;
L("NDN_Connection:\tFINISHED DOWNLOADING %s Average_DL: %f size: %lu cumulative: %lu Throughput: %f\n", m_name.c_str(), speed, sizeDownloaded, cumulativeBytesReceived, (double) (sizeDownloaded * 8 / this->dnltime));
free(this->deezData);
this->deezData = NULL;
return 0;
}
if((this->datSize - this->dataPos) > (int)len)
{
memcpy(data, this->deezData + this->dataPos, len);
this->dataPos += len;
sizeDownloaded += len;
return len;
}
else
{
assert(this->datSize - this->dataPos > 0);
memcpy(data, this->deezData + this->dataPos, this->datSize - this->dataPos);
int temp = this->datSize - this->dataPos;
this->dataPos += this->datSize - this->dataPos;
sizeDownloaded += temp;
return temp;
}
}
this->mdata.clear();
L("NDN_Connection:\tSTARTINF ICP DOWNLOAD\n");
boost::future<bool> f = boost::async(boost::bind(&ndn::NdnIcpDownload::download, this->ndnicpdownload, this->m_name, &(this->mdata), this->firstChunk, -1));
this->res = f.get();
this->datSize = this->mdata.size();
this->deezData = (char *)malloc(this->datSize);
int i = 0;
std::copy(this->mdata.begin(), this->mdata.end(), this->deezData);
/* for(std::vector<char>::const_iterator it = this->mdata.begin(); it != this->mdata.end(); it++)
{
deezData[i] = *it;
i++;
}
*/
if(this->datSize > (int)len)
{
memcpy(data, this->deezData, len);
this->dataPos += len;
sizeDownloaded += len;
return len;
}
else
{
memcpy(data, this->deezData, this->datSize);
this->dataPos += this->datSize;
sizeDownloaded += this->datSize;
return this->datSize;
}
}
int NDNConnection::Read(uint8_t *data, size_t len, IChunk *chunk) {
//return ReadStopAndWait(data, len, chunk);
//return ReadBetter(data, len, chunk);
return ReadFull(data, len, chunk);
}
int NDNConnection::Read(uint8_t *data, size_t len) { //method to read the mpd file
if(!res)
m_start_time = std::chrono::system_clock::now();
if(res)
{
if(this->dataPos == this->datSize)
{
this->dnltime = std::chrono::duration_cast<duration_in_seconds>(std::chrono::system_clock::now() - m_start_time).count();
speed = (double) (sizeDownloaded * 8 / this->dnltime);
cumulativeBytesReceived += sizeDownloaded;
L("NDN_Connection:\tFINISHED DOWNLOADING %s, Average_DL: %f, size: %lu, cumulative: %lu\n", m_name.c_str(), speed, sizeDownloaded, cumulativeBytesReceived);
return 0;
}
if((this->datSize - this->dataPos) > len)
{
memcpy(data, this->deezData + this->dataPos, len);
this->dataPos += len;
sizeDownloaded += len;
return len;
}
else
{
memcpy(data, this->deezData + this->dataPos, this->datSize - this->dataPos);
int temp = this->datSize - this->dataPos;
this->dataPos += this->datSize - this->dataPos;
sizeDownloaded += temp;
return temp;
}
}
this->mdata.clear();
this->res = this->ndnicpdownload->download(this->m_name, &(this->mdata), this->firstChunk, -1);
this->datSize = this->mdata.size();
this->deezData = (char *)malloc(this->datSize);
int i = 0;
for(std::vector<char>::const_iterator it = this->mdata.begin(); it != this->mdata.end(); it++)
{
deezData[i] = *it;
i++;
}
if(this->datSize > len)
{
memcpy(data, this->deezData, len);
this->dataPos += len;
sizeDownloaded += len;
return len;
}
else
{
memcpy(data, this->deezData, this->datSize);
this->dataPos += this->datSize;
sizeDownloaded += this->datSize;
return this->datSize;
}
}
double NDNConnection::GetAverageDownloadingSpeed()
{
Debug("NDNConnection: DL speed is %f\n", this->speed);
return this->speed;
}
double NDNConnection::GetDownloadingTime()
{
L("NDNConnection: DL time is %f\n", this->dnltime);
return this->dnltime;
}
const std::vector<ITCPConnection *> &NDNConnection::GetTCPConnectionList() const {
return tcpConnections;
}
const std::vector<IHTTPTransaction *> &NDNConnection::GetHTTPTransactionList() const {
return httpTransactions;
}
void NDNConnection::notifyStats(double winSize, double RTT)
{
this->speed = (winSize); // * 1000000 * 1400 * 8;
L("NDNConnection:\tNotificationICPDL\t%f\t%f\t%f\n", winSize, RTT, speed);
}
void NDNConnection::notifyChunkStats(std::string chunkName, double chunkThroughput)
{
L("NDNConnection:\tChunk-Download\t Chunk-Name: %s\t single Chunk-Throughput: %f\n", chunkName.c_str(), chunkThroughput);
}
#endif
| 14,712 | 29.026531 | 218 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/NDNConnectionConsumerApi.h | /*
* NDNConnectionConsumerApi.h
*
****************************************
*
* Copyright (c) Cisco Systems 2016
* Author: Jacques Samain <[email protected]>
*
* NDN Connection class based on the Consumer/Producer API.
*
****************************************
*/
#ifndef QTSAMPLEPLAYER_LIBDASHFRAMEWORK_INPUT_NDNCONNECTIONCONSUMERAPI_H_
#define QTSAMPLEPLAYER_LIBDASHFRAMEWORK_INPUT_NDNCONNECTIONCONSUMERAPI_H_
#include "../libdash/source/portable/Networking.h"
#include "INDNConnection.h"
#include "../../debug.h"
#include "log/log.h"
#include <sys/types.h>
#include <string>
#include <stdint.h>
#include <iostream>
#include <sstream>
#include <chrono>
#include <inttypes.h>
#include <stdlib.h>
#include <stdarg.h>
#include <algorithm>
#include <ndn-cxx/security/validator.hpp>
#include <ndn-cxx/security/key-chain.hpp>
#include "Consumer-Producer-API/consumer-context.hpp"
#include "Consumer-Producer-API/manifest.hpp"
#include "Consumer-Producer-API/download-observer.hpp"
#include <future>
#include <inttypes.h>
#include <time.h>
#include <limits.h>
#include <errno.h>
#include "../libdashframework/Portable/MultiThreading.h"
#include <boost/exception/diagnostic_information.hpp>
//logging purpose
#include <chrono>
#include <stdarg.h>
namespace libdash {
namespace framework {
namespace input {
class NDNConnectionConsumerApi : public INDNConnection, public ndn::NdnObserver {
public:
NDNConnectionConsumerApi(double alpha);
virtual ~NDNConnectionConsumerApi();
virtual void Init(dash::network::IChunk *chunk);
void InitForMPD(const std::string& url);
virtual int Read(uint8_t *data, size_t len, dash::network::IChunk *chunk);
int Read(uint8_t *data, size_t len);
virtual int Peek(uint8_t *data, size_t len, dash::network::IChunk *chunk);
virtual double GetAverageDownloadingSpeed();
virtual double GetDownloadingTime();
void processPayload(ndn::Consumer& , const uint8_t*, size_t);
bool onPacket(ndn::Consumer& , const ndn::Data&);
// virtual void onData(const ndn::Interest &interest, const ndn::Data &data);
// virtual void onTimeout(const ndn::Interest &interest);
/*
* IDASHMetrics
* Can't be deleted...
*/
const std::vector<dash::metrics::ITCPConnection *> &GetTCPConnectionList() const;
const std::vector<dash::metrics::IHTTPTransaction *> &GetHTTPTransactionList() const;
/*
* NdnObserver
*/
virtual void notifyStats(double throughput);
virtual void notifyChunkStats(std::string chunkName, double chunkThroughput); //for measurement on chunk-level
private:
uint64_t i_chunksize;
int i_lifetime;
int i_missed_co;
/**< number of content objects we missed in NDNBlock */
std::string m_name;
ndn::Name m_recv_name;
ndn::Face m_face;
int m_first;
bool m_isFinished;
uint64_t m_nextSeg;
double ndnAlpha;
bool ndnRateBased;
bool allow_stale;
int sysTimeout;
unsigned InitialMaxwindow;
unsigned int timer;
double drop_factor;
double p_min;
double beta;
unsigned int gamma;
unsigned int samples;
unsigned int nchunks; // XXX chunks=-1 means: download the whole file!
bool output;
bool report_path;
ndn::Consumer* myConsumer;
bool res;
std::vector<char> mdata;
char* deezData;
int datSize;
int dataPos;
int firstChunk;
double speed; // in bps
double dnltime; //in seconds
uint64_t sizeDownloaded;
std::chrono::time_point<std::chrono::system_clock> m_start_time;
std::vector<dash::metrics::ITCPConnection *> tcpConnections;
std::vector<dash::metrics::IHTTPTransaction *> httpTransactions;
uint64_t cumulativeBytesReceived;
mutable CRITICAL_SECTION monitorMutex;
mutable CONDITION_VARIABLE contentRetrieved;
};
} /* namespace input */
} /* namespace framework */
} /* namespace libdash */
#endif /* QTSAMPLEPLAYER_LIBDASHFRAMEWORK_INPUT_NDNCONNECTIONCONSUMERAPI_H_ */
| 4,732 | 30.138158 | 126 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/NDNConnectionConsumerApi.cpp | /*
* NDNConnectionConsumerApi.h
*
****************************************
*
* Copyright (c) Cisco Systems 2016
* Author: Jacques Samain <[email protected]>
*
* NDN Connection class based on the Consumer/Producer API.
*
****************************************
*/
#ifndef NDNICPDOWNLOAD
#include "NDNConnectionConsumerApi.h"
#define DEFAULT_LIFETIME 250
#define RETRY_TIMEOUTS 5
using namespace dash;
using namespace dash::network;
using namespace dash::metrics;
using namespace ndn;
using std::bind;
using std::placeholders::_1;
using std::placeholders::_2;
using std::placeholders::_3;
using duration_in_seconds = std::chrono::duration<double, std::ratio<1, 1> >;
namespace libdash {
namespace framework {
namespace input {
NDNConnectionConsumerApi::NDNConnectionConsumerApi(double alpha) :
m_recv_name(std::string()),
m_first(1),
m_isFinished(false),
sizeDownloaded (0),
cumulativeBytesReceived(0),
ndnAlpha(alpha)
{
drop_factor = 0.95;
beta = 0.05;
gamma = 1;
this->speed = 0.0;
this->dnltime = 0.0;
this->deezData = NULL;
this->datSize = 0;
this->dataPos = 0;
InitializeConditionVariable (&this->contentRetrieved);
InitializeCriticalSection (&this->monitorMutex);
this->myConsumer = new Consumer(Name(""), RAAQMDR);
this->myConsumer->setContextOption(INTEREST_LIFETIME, DEFAULT_LIFETIME);
this->myConsumer->setContextOption(INTEREST_RETX, RETRY_TIMEOUTS);
this->myConsumer->setContextOption(BETA_VALUE, beta);
this->myConsumer->setContextOption(GAMMA_VALUE, (int)gamma);
this->myConsumer->setContextOption(DROP_FACTOR, drop_factor);
this->myConsumer->setContextOption(RATE_ESTIMATION_ALPHA, this->ndnAlpha);
this->myConsumer->setContextOption(RATE_ESTIMATION_OBSERVER, this);
this->myConsumer->setContextOption(CONTENT_RETRIEVED, (ConsumerContentCallback) bind(&NDNConnectionConsumerApi::processPayload, this, _1, _2, _3));
this->myConsumer->setContextOption(DATA_TO_VERIFY, (ConsumerDataVerificationCallback)bind(&NDNConnectionConsumerApi::onPacket, this, _1, _2));
#ifdef NO_GUI
if(this->ndnAlpha != 20)
this->ndnRateBased = true;
#else
this->ndnRateBased = true;
#endif
Debug("NDN class created\n");
}
NDNConnectionConsumerApi::~NDNConnectionConsumerApi() {
delete this->myConsumer;
if(this->deezData)
{
free(this->deezData);
this->deezData = NULL;
}
DeleteConditionVariable (&this->contentRetrieved);
DeleteCriticalSection (&this->monitorMutex);
}
void NDNConnectionConsumerApi::Init(IChunk *chunk) {
Debug("NDN Connection: STARTING\n");
m_first = 1;
sizeDownloaded = 0;
m_name = "ndn:/" + chunk->Host() + chunk->Path();
m_isFinished = false;
res = false;
dataPos = 0;
datSize = 0;
if(this->deezData)
{
free(this->deezData);
deezData = NULL;
}
Debug("API_NDN_Connection:\tINTIATED_to_name %s\n", m_name.c_str());
L("API_NDN_Connection:\tSTARTING DOWNLOAD %s\n", m_name.c_str());
}
void NDNConnectionConsumerApi::InitForMPD(const std::string& url)
{
m_first = 1;
sizeDownloaded = 0;
if(url.find("//") != std::string::npos)
{
int pos = url.find("//");
char* myName = (char*)malloc(strlen(url.c_str()) - 1);
strncpy(myName, url.c_str(), pos + 1);
strncpy(myName + pos + 1, url.c_str() + pos + 2, strlen(url.c_str()) - pos - 2);
m_name = std::string(myName);
}
else
{
m_name = url;
}
m_isFinished = false;
res = false;
dataPos = 0;
datSize = 0;
if(this->deezData)
{
free(this->deezData);
deezData = NULL;
}
Debug("API_NDN_Connection:\tINTIATED_for_mpd %s\n", m_name.c_str());
L("API_NDN_Connection:\tSTARTING DOWNLOAD %s\n", m_name.c_str());
}
int NDNConnectionConsumerApi::Read(uint8_t* data, size_t len, IChunk *chunk)
{
return this->Read(data, len);
}
int NDNConnectionConsumerApi::Read(uint8_t *data, size_t len)
{
if(!res)
m_start_time = std::chrono::system_clock::now();
if(res)
{
if(this->dataPos == this->datSize)
{
this->dnltime = std::chrono::duration_cast<duration_in_seconds>(std::chrono::system_clock::now() - m_start_time).count();
if(speed == 0 || !this->ndnRateBased)
speed = (double) (sizeDownloaded * 8 / this->dnltime);
cumulativeBytesReceived += sizeDownloaded;
L("API_NDN_Connection:\tFINISHED DOWNLOADING %s Average_DL: %f size: %lu cumulative: %lu Throughput: %f\n", m_name.c_str(), speed, sizeDownloaded, cumulativeBytesReceived, (double) (sizeDownloaded * 8 / this->dnltime));
free(this->deezData);
this->deezData = NULL;
return 0;
}
if((this->datSize - this->dataPos) > (int)len)
{
memcpy(data, this->deezData + this->dataPos, len);
this->dataPos += len;
sizeDownloaded += len;
return len;
}
else
{
assert(this->datSize - this->dataPos > 0);
memcpy(data, this->deezData + this->dataPos, this->datSize - this->dataPos);
int temp = this->datSize - this->dataPos;
this->dataPos += this->datSize - this->dataPos;
sizeDownloaded += temp;
return temp;
}
}
this->myConsumer->consume(Name(m_name));
EnterCriticalSection(&this->monitorMutex);
while(this->m_isFinished == false)
SleepConditionVariableCS(&this->contentRetrieved, &this->monitorMutex, INFINITE);
assert(this->datSize != 0);
this->res = true;
LeaveCriticalSection(&this->monitorMutex);
if(this->datSize > (int)len)
{
memcpy(data, this->deezData, len);
this->dataPos += len;
sizeDownloaded += len;
return len;
}
else
{
memcpy(data, this->deezData, this->datSize);
this->dataPos += this->datSize;
sizeDownloaded += this->datSize;
return this->datSize;
}
}
int NDNConnectionConsumerApi::Peek(uint8_t *data, size_t len, IChunk *chunk) {
return -1;
}
bool NDNConnectionConsumerApi::onPacket(Consumer& c, const Data& data)
{
return true;
}
void NDNConnectionConsumerApi::processPayload(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
EnterCriticalSection(&this->monitorMutex);
this->deezData = (char *)malloc(bufferSize*sizeof(uint8_t));
memcpy(this->deezData, buffer, bufferSize*sizeof(uint8_t));
this->m_isFinished = true;
this->datSize = (int) bufferSize;
WakeAllConditionVariable(&this->contentRetrieved);
LeaveCriticalSection(&this->monitorMutex);
}
double NDNConnectionConsumerApi::GetAverageDownloadingSpeed()
{
Debug("NDNConnection: DL speed is %f\n", this->speed);
return this->speed;
}
double NDNConnectionConsumerApi::GetDownloadingTime()
{
Debug("NDNConnection: DL time is %f\n", this->dnltime);
return this->dnltime;
}
const std::vector<ITCPConnection *> &NDNConnectionConsumerApi::GetTCPConnectionList() const {
return tcpConnections;
}
const std::vector<IHTTPTransaction *> &NDNConnectionConsumerApi::GetHTTPTransactionList() const {
return httpTransactions;
}
void NDNConnectionConsumerApi::notifyStats(double winSize)
{
this->speed = (winSize); // * 1000000 * 1400 * 8;
L("API_NDNConnection:\tNotificationICPDL\t%f\t%f\n", winSize, speed);
}
void NDNConnectionConsumerApi::notifyChunkStats(std::string chunkName, double chunkThroughput) //for measurement on chunk-level
{
L("API_NDNConnection:\tChunk-Information(API)\t%s\t%f\n", chunkName.c_str(), chunkThroughput);
}
} /* namespace input */
} /* namespace framework */
} /* namespace libdash */
#endif //NDEF NDNICPDOWNLOAD
| 7,692 | 27.812734 | 224 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/MediaObject.cpp | /*
* MediaObject.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 "MediaObject.h"
#include <inttypes.h>
#include<stdio.h>
using namespace libdash::framework::input;
using namespace dash::mpd;
using namespace dash::network;
using namespace dash::metrics;
MediaObject::MediaObject (ISegment *segment, IRepresentation *rep, bool withFeedBack) :
segment (segment),
rep (rep),
withFeedBack (withFeedBack)
{
InitializeConditionVariable (&this->stateChanged);
InitializeCriticalSection (&this->stateLock);
}
MediaObject::~MediaObject ()
{
if(this->state == IN_PROGRESS)
{
this->segment->AbortDownload();
this->OnDownloadStateChanged(ABORTED);
}
this->segment->DetachDownloadObserver(this);
this->WaitFinished();
DeleteConditionVariable (&this->stateChanged);
DeleteCriticalSection (&this->stateLock);
delete this->segment;
this->segment = NULL;
}
void MediaObject::SetFeedBack(bool flag)
{
this->withFeedBack = flag;
}
bool MediaObject::StartDownload ()
{
this->segment->AttachDownloadObserver(this);
return this->segment->StartDownload();
}
bool MediaObject::StartDownload (INDNConnection* conn)
{
//L("Media_object:\tSTARTING DOWNLOAD %s\n", ((IChunk*)this->segment)->Path().c_str());
if(conn == NULL)
return this->StartDownload();
conn->Init(this->segment);
this->segment->AttachDownloadObserver(this);
return this->segment->StartDownload(conn);
}
const char* MediaObject::GetPath ()
{
return ((IChunk*)this->segment)->Path().c_str();
}
void MediaObject::AbortDownload ()
{
this->segment->AbortDownload();
// L("Media_object:\tABORTED DOWNLOAD %s\n", ((IChunk*)this->segment)->Path().c_str());
this->OnDownloadStateChanged(ABORTED);
}
void MediaObject::WaitFinished (bool isInit)
{
EnterCriticalSection(&this->stateLock);
while(this->state != COMPLETED && this->state != ABORTED){
SleepConditionVariableCS(&this->stateChanged, &this->stateLock, INFINITE);
}
LeaveCriticalSection(&this->stateLock);
if(this->state != ABORTED)
{
if(this->withFeedBack && !isInit)
{
this->dashReceiver->NotifybpsSegment(this->bps); //done by ChunktimeObserver "after every sample" instead of "after every segment"
this->dashReceiver->NotifyDlTime(this->dnltime); //DL time needed to
}
// L("Media_object:\tFINISHED DOWNLOAD %s\n", ((IChunk*)this->segment)->Path().c_str());
}
}
int MediaObject::Read (uint8_t *data, size_t len)
{
return this->segment->Read(data, len);
}
int MediaObject::Peek (uint8_t *data, size_t len)
{
return this->segment->Peek(data, len);
}
int MediaObject::Peek (uint8_t *data, size_t len, size_t offset)
{
return this->segment->Peek(data, len, offset);
}
IRepresentation* MediaObject::GetRepresentation ()
{
return this->rep;
}
void MediaObject::OnDownloadStateChanged (DownloadState state)
{
EnterCriticalSection(&this->stateLock);
this->state = state;
WakeAllConditionVariable(&this->stateChanged);
LeaveCriticalSection(&this->stateLock);
}
void MediaObject::OnDownloadRateChanged (uint64_t bitsPerSecond)
{
this->bps = bitsPerSecond;
}
void MediaObject::OnDownloadTimeChanged (double dnltime)
{
this->dnltime = dnltime;
}
void MediaObject::SetDASHReceiver(input::DASHReceiver *_dashReceiver)
{
this->dashReceiver = _dashReceiver;
}
void MediaObject::SetAdaptationLogic(adaptation::IAdaptationLogic *_adaptationLogic)
{
this->adaptationLogic = _adaptationLogic;
}
const std::vector<ITCPConnection *>& MediaObject::GetTCPConnectionList () const
{
return this->segment->GetTCPConnectionList();
}
const std::vector<IHTTPTransaction *>& MediaObject::GetHTTPTransactionList () const
{
return this->segment->GetHTTPTransactionList();
}
| 4,457 | 29.534247 | 136 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/INDNConnection.h | /*
* INDNConnection.h
*
* Author:Jack Samain <[email protected]>
*
*/
#ifndef QTSAMPLEPLAYER_LIBDASHFRAMEWORK_INPUT_INDNCONNECTION_H_
#define QTSAMPLEPLAYER_LIBDASHFRAMEWORK_INPUT_INDNCONNECTION_H_
#include "IConnection.h"
#include "IChunk.h"
namespace libdash {
namespace framework {
namespace input {
class INDNConnection : public dash::network::IConnection {
public:
virtual ~INDNConnection(){};
virtual int Read(uint8_t* data, size_t len) = 0;
virtual void Init(dash::network::IChunk *chunk) = 0;
virtual void InitForMPD(const std::string&) = 0;
};
}
}
}
#endif // QTSAMPLEPLAYER_LIBDASHFRAMEWORK_INPUT_INDNCONNECTION_H_
| 672 | 18.228571 | 65 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/MediaObjectDecoder.cpp | /*
* MediaObjectDecoder.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 "MediaObjectDecoder.h"
using namespace sampleplayer::decoder;
using namespace libdash::framework::input;
using namespace dash::mpd;
MediaObjectDecoder::MediaObjectDecoder (MediaObject* initSegment, MediaObject* mediaSegment, IMediaObjectDecoderObserver *observer, bool nodecoding) :
observer (observer),
initSegment (initSegment),
mediaSegment (mediaSegment),
decoderInitialized (false),
initSegmentOffset (0),
threadHandle (NULL),
noDecoding (nodecoding)
{
if(!noDecoding)
{
this->decoder = new LibavDecoder(this);
this->decoder->AttachVideoObserver(this);
this->decoder->AttachAudioObserver(this);
}
}
MediaObjectDecoder::~MediaObjectDecoder()
{
this->WaitForDelete();
if(!noDecoding)
delete this->decoder;
delete this->mediaSegment;
}
bool MediaObjectDecoder::Start ()
{
if(!noDecoding)
{
if(!decoder->Init())
return false;
this->decoderInitialized = true;
this->run = true;
this->threadHandle = CreateThreadPortable (Decode, this);
if(this->threadHandle == NULL)
{
this->run = false;
return false;
}
return true;
}
else
{
this->run = true;
this->threadHandle = CreateThreadPortable (No_Decode, this);
if(this->threadHandle == NULL)
{
this->run = false;
return false;
}
return true;
}
}
void MediaObjectDecoder::Stop ()
{
if (!this->run)
return;
this->run = false;
if (this->threadHandle != NULL)
{
JoinThread(this->threadHandle);
DestroyThreadPortable(this->threadHandle);
}
}
void MediaObjectDecoder::WaitForDelete ()
{
if (this->threadHandle != NULL)
{
JoinThread(this->threadHandle);
DestroyThreadPortable(this->threadHandle);
}
}
void MediaObjectDecoder::OnVideoDataAvailable (const uint8_t **data, videoFrameProperties* props)
{
this->observer->OnVideoFrameDecoded(data, props);
}
void MediaObjectDecoder::OnAudioDataAvailable (const uint8_t **data, audioFrameProperties* props)
{
this->observer->OnAudioSampleDecoded(data, props);
}
void* MediaObjectDecoder::No_Decode (void *data)
{
MediaObjectDecoder *mediaObjectDecoder = (MediaObjectDecoder *) data;
sleep(2);
if (mediaObjectDecoder->run)
{
mediaObjectDecoder->Notify();
return NULL;
}
}
void* MediaObjectDecoder::Decode (void *data)
{
MediaObjectDecoder *mediaObjectDecoder = (MediaObjectDecoder *) data;
while (mediaObjectDecoder->run && mediaObjectDecoder->decoder->Decode());
if (mediaObjectDecoder->run)
{
mediaObjectDecoder->decoder->Flush();
mediaObjectDecoder->decoder->Stop();
mediaObjectDecoder->Notify();
return NULL;
}
mediaObjectDecoder->decoder->Stop();
return NULL;
}
int MediaObjectDecoder::Read (uint8_t *buf, int buf_size)
{
int ret = 0;
if (!this->decoderInitialized && this->initSegment)
{
ret = this->initSegment->Peek(buf, buf_size, this->initSegmentOffset);
this->initSegmentOffset += (size_t) ret;
}
if (ret == 0)
ret = this->mediaSegment->Read(buf, buf_size);
return ret;
}
bool MediaObjectDecoder::IsAudio ()
{
return this->decoder->IsAudio();
}
void MediaObjectDecoder::Notify ()
{
this->observer->OnDecodingFinished();
}
| 3,985 | 24.716129 | 151 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/DASHManager.cpp |
/*
* DASHManager.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 <immintrin.h>
#include <tmmintrin.h>
#include "DASHManager.h"
using namespace libdash::framework::input;
using namespace libdash::framework::buffer;
using namespace sampleplayer::decoder;
using namespace dash;
using namespace dash::network;
using namespace dash::mpd;
//To circumvent the stupid refactoring in libavcodec...
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)
#define av_frame_alloc avcodec_alloc_frame
#define av_frame_free avcodec_free_frame
#endif
DASHManager::DASHManager (sampleplayer::managers::StreamType type, uint32_t maxCapacity, IDASHManagerObserver* stream, IMPD* mpd, bool ndnEnabled, double ndnAlpha, bool nodecoding, bool chunkGranularityEnabled, int sample) :
readSegmentCount (0),
receiver (NULL),
mediaObjectDecoder (NULL),
multimediaStream (stream),
isRunning (false),
isNDN (ndnEnabled),
ndnAlpha (ndnAlpha),
noDecoding (nodecoding),
chunkGranularity (chunkGranularityEnabled),
samplesize (sample)
{
this->buffer = new MediaObjectBuffer(type, maxCapacity);
this->buffer->AttachObserver(this);
this->receiver = new DASHReceiver(mpd, this, this->buffer, maxCapacity, this->IsNDN(), this->ndnAlpha, this->chunkGranularity, this->samplesize);
}
DASHManager::~DASHManager ()
{
this->Stop();
delete this->receiver;
delete this->buffer;
this->receiver = NULL;
this->buffer = NULL;
}
bool DASHManager::IsNDN ()
{
return this->isNDN;
}
void DASHManager::ShouldAbort ()
{
Debug("DASH MANAGER: ABORT REQUEST\n");
this->receiver->ShouldAbort();
}
bool DASHManager::Start ()
{
this->receiver->SetAdaptationLogic(this->adaptationLogic);
if (!this->receiver->Start())
return false;
if (!this->CreateAVDecoder())
return false;
this->isRunning = true;
return true;
}
void DASHManager::Stop ()
{
if (!this->isRunning)
return;
this->isRunning = false;
this->receiver->Stop();
this->mediaObjectDecoder->Stop();
this->buffer->Clear();
}
uint32_t DASHManager::GetPosition ()
{
return this->receiver->GetPosition();
}
void DASHManager::SetPosition (uint32_t segmentNumber)
{
this->receiver->SetPosition(segmentNumber);
}
void DASHManager::SetPositionInMsec (uint32_t milliSecs)
{
this->receiver->SetPositionInMsecs(milliSecs);
}
void DASHManager::SetAdaptationLogic (libdash::framework::adaptation::IAdaptationLogic *_adaptationLogic)
{
this->adaptationLogic = _adaptationLogic;
}
void DASHManager::Clear ()
{
this->buffer->Clear();
}
/*void DASHManager::ClearTail ()
{
this->buffer->ClearTail();
}
*/
void DASHManager::SetRepresentation (IPeriod *period, IAdaptationSet *adaptationSet, IRepresentation *representation)
{
this->receiver->SetRepresentation(period, adaptationSet, representation);
//this->buffer->ClearTail();
}
void DASHManager::EnqueueRepresentation (IPeriod *period, IAdaptationSet *adaptationSet, IRepresentation *representation)
{
this->receiver->SetRepresentation(period, adaptationSet, representation);
}
void DASHManager::OnVideoFrameDecoded (const uint8_t **data, videoFrameProperties* props)
{
/* TODO: some error handling here */
if (data == NULL || props->fireError)
{
Debug("data is %sNULL and %serror was fired\n", (data==NULL)? "" : "not ", (props->fireError)?"":"no ");
return;
}
int w = props->width;
int h = props->height;
//AVFrame *rgbframe = avcodec_alloc_frame();
AVFrame *rgbframe = av_frame_alloc();
int numBytes = avpicture_get_size(AV_PIX_FMT_RGB24, w, h);
uint8_t *buffer = (uint8_t*)av_malloc(numBytes);
avpicture_fill((AVPicture*)rgbframe, buffer, AV_PIX_FMT_RGB24, w, h);
SwsContext *imgConvertCtx = sws_getContext(props->width, props->height, (AVPixelFormat)props->pxlFmt, w, h, AV_PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL);
sws_scale(imgConvertCtx, data, props->linesize, 0, h, rgbframe->data, rgbframe->linesize);
uint8_t *src = (uint8_t *)rgbframe->data[0];
QImage *image = new QImage(w, h, QImage::Format_RGB32);
//TRYING to tackle efficiency issue by multithreading the rendering
///*
int numberOfThreads = 3;
Container* m_Containers[numberOfThreads];
THREAD_HANDLE m_threads[numberOfThreads];
for(int i=0; i < numberOfThreads; i++)
{
m_Containers[i] = (Container *)malloc(sizeof(struct Container));
m_Containers[i]->number = i;
m_Containers[i]->total = numberOfThreads;
m_Containers[i]->height = h;
m_Containers[i]->width = w;
m_Containers[i]->src = src + i * (h/numberOfThreads - 1) *rgbframe->linesize[0];
m_Containers[i]->image = image;
m_Containers[i]->linesize = rgbframe->linesize[0];
m_threads[i] = CreateThreadPortable(AV2QImage, m_Containers[i]);
}
for(int i = 0; i < numberOfThreads; i++)
{
JoinThread(m_threads[i]);
}
for(int i=0; i < numberOfThreads; i++)
free(m_Containers[i]);
//*/
/* for (size_t y = 0; y < h; y++)
{
QRgb *scanLine = (QRgb *)image->scanLine(y);
for(size_t x = 0; x < w; x ++)
{
scanLine[x] = qRgb(src[3*x],src[3*x + 1],src[3*x + 2]);
}
src += rgbframe->linesize[0];
}*/
this->multimediaStream->AddFrame(image);
//delete image;
//image = NULL;
av_free(rgbframe);
av_free(buffer);
sws_freeContext(imgConvertCtx);
imgConvertCtx = NULL;
}
/* in and out must be 16-byte aligned */
void DASHManager::rgb_to_bgrx_sse(unsigned w, const void *in, void *out)
{
const __m128i *in_vec = in;
__m128i *out_vec = out;
w /= 16;
while (w-- > 0) {
/* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
* in_vec[0] Ra Ga Ba Rb Gb Bb Rc Gc Bc Rd Gd Bd Re Ge Be Rf
* in_vec[1] Gf Bf Rg Gg Bg Rh Gh Bh Ri Gi Bi Rj Gj Bj Rk Gk
* in_vec[2] Bk Rl Gl Bl Rm Gm Bm Rn Gn Bn Ro Go Bo Rp Gp Bp
*/
__m128i in1, in2, in3;
__m128i out;
in1 = in_vec[0];
out = _mm_shuffle_epi8(in1,
_mm_set_epi8(0xff, 9, 10, 11, 0xff, 6, 7, 8, 0xff, 3, 4, 5, 0xff, 0, 1, 2));
out = _mm_or_si128(out,
_mm_set_epi8(0xff, 0, 0, 0, 0xff, 0, 0, 0, 0xff, 0, 0, 0, 0xff, 0, 0, 0));
out_vec[0] = out;
in2 = in_vec[1];
in1 = _mm_and_si128(in1,
_mm_set_epi8(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0));
out = _mm_and_si128(in2,
_mm_set_epi8(0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff));
out = _mm_or_si128(out, in1);
out = _mm_shuffle_epi8(out,
_mm_set_epi8(0xff, 5, 6, 7, 0xff, 2, 3, 4, 0xff, 15, 0, 1, 0xff, 12, 13, 14));
out = _mm_or_si128(out,
_mm_set_epi8(0xff, 0, 0, 0, 0xff, 0, 0, 0, 0xff, 0, 0, 0, 0xff, 0, 0, 0));
out_vec[1] = out;
in3 = in_vec[2];
in_vec += 3;
in2 = _mm_and_si128(in2,
_mm_set_epi8(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0));
out = _mm_and_si128(in3,
_mm_set_epi8(0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff));
out = _mm_or_si128(out, in2);
out = _mm_shuffle_epi8(out,
_mm_set_epi8(0xff, 1, 2, 3, 0xff, 14, 15, 0, 0xff, 11, 12, 13, 0xff, 8, 9, 10));
out = _mm_or_si128(out,
_mm_set_epi8(0xff, 0, 0, 0, 0xff, 0, 0, 0, 0xff, 0, 0, 0, 0xff, 0, 0, 0));
out_vec[2] = out;
out = _mm_shuffle_epi8(in3,
_mm_set_epi8(0xff, 13, 14, 15, 0xff, 10, 11, 12, 0xff, 7, 8, 9, 0xff, 4, 5, 6));
out = _mm_or_si128(out,
_mm_set_epi8(0xff, 0, 0, 0, 0xff, 0, 0, 0, 0xff, 0, 0, 0, 0xff, 0, 0, 0));
out_vec[3] = out;
out_vec += 4;
}
}
void* DASHManager::AV2QImage (void* data)
{
Container *m_container = (Container *) data;
for(size_t y = (m_container->height / m_container->total)*m_container->number; y < ((m_container->number == m_container->total - 1) ? m_container->height : (m_container->height / m_container->total) * (m_container->number + 1) ); y++)
{
QRgb *scanLine = (QRgb *)m_container->image->scanLine(y);
rgb_to_bgrx_sse(m_container->width, m_container->src, (void *) scanLine);
/*for(size_t x = 0; x < m_container->width; x ++)
{
scanLine[x] = qRgb(m_container->src[3*x],m_container->src[3*x + 1],m_container->src[3*x + 2]);
}*/
m_container->src += m_container->linesize;
}
}
void DASHManager::OnAudioSampleDecoded (const uint8_t **data, audioFrameProperties* props)
{
/* TODO: some error handling here */
if (data == NULL || props->fireError)
return;
QAudioFormat *format = new QAudioFormat();
format->setSampleRate(props->sampleRate);
format->setChannelCount(props->channels);
format->setSampleSize(props->samples);
format->setCodec("audio/pcm");
format->setByteOrder(QAudioFormat::LittleEndian);
format->setSampleType(QAudioFormat::Float);
Debug("chunksize: %d, sampleRate: %d, samples: %d\n",props->chunkSize, props->sampleRate, props->samples);
AudioChunk *samples = new AudioChunk(format, (char*)data[0], props->linesize);
this->multimediaStream->AddSamples(samples);
}
void DASHManager::OnBufferStateChanged (uint32_t fillstateInPercent)
{
this->multimediaStream->OnSegmentBufferStateChanged(fillstateInPercent);
if(this->adaptationLogic->IsBufferBased())
this->receiver->OnSegmentBufferStateChanged(fillstateInPercent);
}
void DASHManager::OnEOS (bool value)
{
if(this->adaptationLogic->IsBufferBased())
this->receiver->OnEOS(value);
}
void DASHManager::OnSegmentDownloaded ()
{
this->readSegmentCount++;
// notify observers
}
void DASHManager::OnDecodingFinished ()
{
if (this->isRunning)
this->CreateAVDecoder();
}
bool DASHManager::CreateAVDecoder ()
{
MediaObject *mediaObject = this->buffer->GetFront();
// initSegForMediaObject may be NULL => BaseUrls
if (!mediaObject)
{
//No media Object here means that the stream is finished ? Feels like it is but need to check TODO
this->multimediaStream->SetEOS(true);
return false;
}
MediaObject *initSegForMediaObject = this->receiver->FindInitSegment(mediaObject->GetRepresentation());
if(this->mediaObjectDecoder)
{
delete this->mediaObjectDecoder;
}
this->mediaObjectDecoder = new MediaObjectDecoder(initSegForMediaObject, mediaObject, this, this->noDecoding);
return this->mediaObjectDecoder->Start();
}
void DASHManager::FastForward ()
{
this->receiver->FastForward();
}
void DASHManager::FastRewind ()
{
this->receiver->FastRewind();
}
void DASHManager::SetTargetDownloadingTime (double target)
{
this->receiver->SetTargetDownloadingTime(target);
}
| 11,148 | 31.037356 | 235 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/DASHManager.h | /*
* DASHManager.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_INPUT_DASHMANAGER_H_
#define LIBDASH_FRAMEWORK_INPUT_DASHMANAGER_H_
#include "../Buffer/MediaObjectBuffer.h"
#include "DASHReceiver.h"
#include "../../Decoder/IVideoObserver.h"
#include "IDASHReceiverObserver.h"
#include "IMediaObjectDecoderObserver.h"
#include "MediaObjectDecoder.h"
#include "libdash.h"
#include "IMPD.h"
#include <QtMultimedia/qaudioformat.h>
#include "IDASHManagerObserver.h"
#include "../Buffer/AudioChunk.h"
#include "../Buffer/IMediaObjectBufferObserver.h"
namespace libdash
{
namespace framework
{
namespace input
{
struct Container
{
int height;
int width;
int total;
int number;
QImage* image;
uint8_t* src;
int linesize;
};
class DASHManager : public IDASHReceiverObserver, public IMediaObjectDecoderObserver, public buffer::IMediaObjectBufferObserver
{
public:
DASHManager (sampleplayer::managers::StreamType type, uint32_t maxCapacity, IDASHManagerObserver *multimediaStream, dash::mpd::IMPD *mpd, bool ndnEnabled, double ndnAlpha, bool nodecoding, bool chunkGranularityEnabled, int sample);
virtual ~DASHManager ();
static void rgb_to_bgrx_sse(unsigned w, const void *in, void *out);
bool Start ();
void Stop ();
uint32_t GetPosition ();
void SetPosition (uint32_t segmentNumber); // to implement
void SetPositionInMsec (uint32_t millisec);
void Clear ();
void ClearTail ();
void SetRepresentation (dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, dash::mpd::IRepresentation *representation);
void EnqueueRepresentation (dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, dash::mpd::IRepresentation *representation);
void OnSegmentDownloaded ();
void OnDecodingFinished ();
void OnVideoFrameDecoded (const uint8_t **data, sampleplayer::decoder::videoFrameProperties* props);
void OnAudioSampleDecoded (const uint8_t **data, sampleplayer::decoder::audioFrameProperties* props);
void OnBufferStateChanged (uint32_t fillstateInPercent);
void OnEOS (bool value);
void SetAdaptationLogic (libdash::framework::adaptation::IAdaptationLogic *_adaptationLogic);
bool IsNDN ();
void ShouldAbort ();
void FastForward ();
void FastRewind ();
void SetTargetDownloadingTime(double);
private:
bool CreateAVDecoder ();
static void* AV2QImage (void* data);
buffer::MediaObjectBuffer *buffer;
MediaObjectDecoder *mediaObjectDecoder;
DASHReceiver *receiver;
uint32_t readSegmentCount;
IDASHManagerObserver *multimediaStream;
bool isRunning;
bool isNDN;
double ndnAlpha;
bool noDecoding;
bool chunkGranularity;
int samplesize;
libdash::framework::adaptation::IAdaptationLogic *adaptationLogic;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_INPUT_DASHMANAGER_H_ */
| 4,356 | 41.715686 | 263 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/DASHReceiver.h | /*
* DASHReceiver.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_INPUT_DASHRECEIVER_H_
#define LIBDASH_FRAMEWORK_INPUT_DASHRECEIVER_H_
#include "libdash.h"
#include "IMPD.h"
#include "../Input/MediaObject.h"
#include "IDASHReceiverObserver.h"
#include "../Buffer/MediaObjectBuffer.h"
#include "../MPD/AdaptationSetStream.h"
#include "../MPD/IRepresentationStream.h"
#include "../Portable/MultiThreading.h"
#include <chrono>
#ifdef NDNICPDOWNLOAD
#include "NDNConnection.h"
#else
#include "NDNConnectionConsumerApi.h"
#endif
namespace libdash
{
namespace framework
{
namespace adaptation
{
class IAdaptationLogic;
}
namespace buffer
{
class MediaObjectBuffer;
}
namespace input
{
class MediaObject;
class DASHReceiver
{
public:
DASHReceiver (dash::mpd::IMPD *mpd, IDASHReceiverObserver *obs, buffer::MediaObjectBuffer *buffer, uint32_t bufferSize, bool ndnEnabled, double ndnAlpha, bool chunkGranularityEnabled, int sample);
virtual ~DASHReceiver ();
bool Start ();
void Stop ();
input::MediaObject* GetNextSegment ();
input::MediaObject* GetSegment (uint32_t segmentNumber);
input::MediaObject* GetInitSegment ();
input::MediaObject* FindInitSegment (dash::mpd::IRepresentation *representation);
uint32_t GetPosition ();
void SetPosition (uint32_t segmentNumber);
void SetPositionInMsecs (uint32_t milliSecs);
dash::mpd::IRepresentation* GetRepresentation ();
void SetRepresentation (dash::mpd::IPeriod *period,
dash::mpd::IAdaptationSet *adaptationSet,
dash::mpd::IRepresentation *representation);
void SetAdaptationLogic (adaptation::IAdaptationLogic *_adaptationLogic);
libdash::framework::adaptation::IAdaptationLogic* GetAdaptationLogic ();
void Notifybps (uint64_t bps);
void NotifybpsSegment (uint64_t bps);
void NotifybpsChunk (uint64_t bps);
void NotifyContextChunk (uint64_t rtt, uint64_t numHops);
void NotifyDlTime (double dnltime);
void NotifyBitrateChange (dash::mpd::IRepresentation *representation);
void OnSegmentBufferStateChanged(uint32_t fillstateInPercent);
bool IsNDN ();
void ShouldAbort ();
void Seeking (int);
void FastForward ();
void FastRewind ();
void OnEOS (bool value);
void SetTargetDownloadingTime(double);
void NotifyCheckedAdaptationLogic();
bool threadComplete;
private:
uint32_t CalculateSegmentOffset ();
void NotifySegmentDownloaded (double bufferFillPct, int segNum, int quality);
void DownloadInitSegment (dash::mpd::IRepresentation* rep);
bool InitSegmentExists (dash::mpd::IRepresentation* rep);
bool withFeedBack;
static void* DoBuffering (void *receiver);
std::map<dash::mpd::IRepresentation*, MediaObject*> initSegments;
buffer::MediaObjectBuffer *buffer;
IDASHReceiverObserver *observer;
dash::mpd::IMPD *mpd;
dash::mpd::IPeriod *period;
dash::mpd::IAdaptationSet *adaptationSet;
dash::mpd::IRepresentation *representation;
mpd::AdaptationSetStream *adaptationSetStream;
mpd::IRepresentationStream *representationStream;
uint32_t segmentNumber;
uint32_t positionInMsecs;
uint32_t segmentOffset;
uint32_t bufferSize;
mutable CRITICAL_SECTION monitorMutex;
mutable CRITICAL_SECTION monitorPausedMutex;
mutable CONDITION_VARIABLE paused;
bool isPaused;
bool isScheduledPaced;
double targetDownload;
double downloadingTime;
adaptation::IAdaptationLogic *adaptationLogic;
INDNConnection* conn;
INDNConnection* initConn;
THREAD_HANDLE bufferingThread;
bool isBuffering;
bool isNDN;
double ndnAlpha;
int previousQuality;
bool chunkGranularity;
int samplesize;
ChunktimeObserver* chunktimeObs;
std::map<int, std::vector<int>> rttMap;
std::map<int, std::vector<int>> numHopsMap;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_INPUT_DASHRECEIVER_H_ */
| 6,681 | 48.132353 | 227 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/MediaObject.h | /*
* MediaObject.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_INPUT_MEDIAOBJECT_H_
#define LIBDASH_FRAMEWORK_INPUT_MEDIAOBJECT_H_
#include "../Adaptation/IAdaptationLogic.h"
#include "IMPD.h"
#include "IDownloadObserver.h"
#include "IDASHMetrics.h"
#include "../Portable/MultiThreading.h"
#ifdef NDNICPDOWNLOAD
#include "NDNConnection.h"
#else
#include "NDNConnectionConsumerApi.h"
#endif
namespace libdash
{
namespace framework
{
namespace adaptation
{
class IAdaptationLogic;
}
namespace input
{
class DASHReceiver;
class MediaObject : public dash::network::IDownloadObserver, public dash::metrics::IDASHMetrics
{
public:
MediaObject (dash::mpd::ISegment *segment, dash::mpd::IRepresentation *rep, bool withFeedBack = false);
virtual ~MediaObject ();
bool StartDownload ();
bool StartDownload (INDNConnection* conn);
void AbortDownload ();
void WaitFinished (bool isInit=false);
int Read (uint8_t *data, size_t len);
int Peek (uint8_t *data, size_t len);
int Peek (uint8_t *data, size_t len, size_t offset);
dash::mpd::IRepresentation* GetRepresentation ();
const char* GetPath ();
void SetFeedBack (bool flag);
virtual void OnDownloadStateChanged (dash::network::DownloadState state);
virtual void OnDownloadRateChanged (uint64_t bytesDownloaded); //Here the bytesDownloaded is in fact the bitrate bps
virtual void OnDownloadTimeChanged (double dnltime);
/*
* IDASHMetrics
*/
const std::vector<dash::metrics::ITCPConnection *>& GetTCPConnectionList () const;
const std::vector<dash::metrics::IHTTPTransaction *>& GetHTTPTransactionList () const;
void SetAdaptationLogic(framework::adaptation::IAdaptationLogic *_adaptationLogic);
void SetDASHReceiver(input::DASHReceiver *_dashReceiver);
private:
dash::mpd::ISegment *segment;
dash::mpd::IRepresentation *rep;
dash::network::DownloadState state;
uint64_t bps;
double dnltime;
bool withFeedBack;
input::DASHReceiver *dashReceiver;
adaptation::IAdaptationLogic *adaptationLogic;
mutable CRITICAL_SECTION stateLock;
mutable CONDITION_VARIABLE stateChanged;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_INPUT_MEDIAOBJECT_H_ */
| 3,591 | 41.258824 | 144 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/IMediaObjectDecoderObserver.h | /*
* IMediaObjectDecoderObserver.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_INPUT_IMEDIAOBJECTDECODEROBSERVER_H_
#define LIBDASH_FRAMEWORK_INPUT_IMEDIAOBJECTDECODEROBSERVER_H_
#include "../../Decoder/IAudioObserver.h"
#include "../../Decoder/IVideoObserver.h"
namespace libdash
{
namespace framework
{
namespace input
{
class IMediaObjectDecoderObserver
{
public:
virtual ~IMediaObjectDecoderObserver () {}
virtual void OnDecodingFinished () = 0;
virtual void OnVideoFrameDecoded (const uint8_t **data, sampleplayer::decoder::videoFrameProperties* props) = 0;
virtual void OnAudioSampleDecoded (const uint8_t **data, sampleplayer::decoder::audioFrameProperties* props) = 0;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_INPUT_IMEDIAOBJECTDECODEROBSERVER_H_ */
| 1,419 | 37.378378 | 140 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/IDASHManagerObserver.h | /*
* IDASHManagerObserver.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_INPUT_IDASHMANAGEROBSERVER_H_
#define LIBDASH_FRAMEWORK_INPUT_IDASHMANAGEROBSERVER_H_
#include <QImage>
#include "../Buffer/AudioChunk.h"
#include "../Buffer/Buffer.h"
namespace libdash
{
namespace framework
{
namespace input
{
class IDASHManagerObserver
{
public:
virtual ~IDASHManagerObserver () {}
virtual void AddFrame (QImage *frame) = 0;
//virtual void AddFrame (ImageWrap *frame) = 0;
virtual void AddSamples (buffer::AudioChunk *samples) = 0;
virtual void SetEOS (bool value) = 0;
//virtual void AddSubtitle () = 0;
virtual void OnSegmentBufferStateChanged (uint32_t fillstateInPercent) = 0;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_INPUT_IDASHMANAGEROBSERVER_H_ */
| 1,441 | 33.333333 | 97 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Input/IDataReceiver.h | /*
* IDataReceiver.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_INPUT_IDATARECEIVER_H_
#define LIBDASH_FRAMEWORK_INPUT_IDATARECEIVER_H_
#include <stdint.h>
namespace libdash
{
namespace framework
{
namespace input
{
class IDataReceiver
{
public:
virtual ~IDataReceiver () {}
virtual int Read (uint8_t *buf, int buf_size ) = 0;
virtual bool IsAudio () = 0;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_INPUT_IDATARECEIVER_H_ */
| 974 | 26.857143 | 79 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/AdaptationSetStream.h | /*
* AdaptationSetStream.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_MPD_ADAPTATIONSETSTREAM_H_
#define LIBDASH_FRAMEWORK_MPD_ADAPTATIONSETSTREAM_H_
#include "IRepresentationStream.h"
#include "IRepresentation.h"
#include "IMPD.h"
#include "IPeriod.h"
#include "IAdaptationSet.h"
#include "RepresentationStreamFactory.h"
#include "BaseUrlResolver.h"
namespace libdash
{
namespace framework
{
namespace mpd
{
class AdaptationSetStream
{
public:
AdaptationSetStream (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet);
virtual ~AdaptationSetStream ();
IRepresentationStream* GetRepresentationStream (dash::mpd::IRepresentation *representation);
private:
RepresentationStreamType DetermineRepresentationStreamType (dash::mpd::IRepresentation *representation);
void Initialize ();
std::map<dash::mpd::IRepresentation *, IRepresentationStream *> representations;
dash::mpd::IMPD *mpd;
dash::mpd::IPeriod *period;
dash::mpd::IAdaptationSet *adaptationSet;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_MPD_ADAPTATIONSETSTREAM_H_ */
| 1,961 | 37.470588 | 145 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/TimeResolver.cpp | /*
* TimeResolver.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 "TimeResolver.h"
using namespace libdash::framework::mpd;
bool TimeResolver::CheckTimeInterval (std::string availabilityStartTime, std::string availabilityEndTime)
{
struct tm* startTime = TimeResolver::ResolveUTCDateTime(availabilityStartTime);
struct tm* currentTime = TimeResolver::GetCurrentUTCTime();
struct tm* endTime = TimeResolver::ResolveUTCDateTime(availabilityEndTime);
if (!startTime)
{
if (!endTime)
return true;
if (difftime(mktime(endTime),mktime(currentTime)) > 0)
return true;
}
else
{
if (difftime(mktime(currentTime),mktime(startTime)) > 0)
{
if (!endTime)
return true;
if (difftime(mktime(endTime),mktime(currentTime)) > 0)
return true;
}
}
return false;
}
uint32_t TimeResolver::GetCurrentTimeInSec ()
{
return mktime(TimeResolver::GetCurrentUTCTime());
}
uint32_t TimeResolver::GetUTCDateTimeInSec (const std::string& datetime)
{
return mktime(TimeResolver::ResolveUTCDateTime(datetime));
}
double TimeResolver::GetDurationInSec (const std::string& duration)
{
/* no check for duration with yyyy,dd,mm */
if (duration == "" || duration.substr(0, 2) != "PT")
return 0;
size_t startPos = 2;
size_t endPos = std::string::npos;
uint32_t hours = 0;
uint32_t mins = 0;
double secs = 0;
char designators[] = { 'H', 'M', 'S' };
endPos = duration.find(designators[0], startPos);
if (endPos != std::string::npos)
{
hours = strtol(duration.substr(startPos, endPos - startPos).c_str(), NULL, 10);
startPos = endPos + 1;
}
endPos = duration.find(designators[1], startPos);
if (endPos != std::string::npos)
{
mins = strtol(duration.substr(startPos, endPos - startPos).c_str(), NULL, 10);
startPos = endPos + 1;
}
endPos = duration.find(designators[2], startPos);
if (endPos != std::string::npos)
secs = strtod(duration.substr(startPos, endPos - startPos).c_str(), NULL);
return hours*3600 + mins*60 + secs;
}
struct tm* TimeResolver::ResolveUTCDateTime (const std::string& dateTimeString)
{
if (dateTimeString == "")
return NULL;
time_t rawtime;
struct tm* timeInfo;
time ( &rawtime );
timeInfo = gmtime ( &rawtime );
std::string timeString = dateTimeString.substr();
timeString = timeString.substr(0, timeString.size()-1);
std::vector<std::string> dateTime = SplitToStr(timeString, 'T');
std::vector<int> dateChunks = SplitToI(dateTime.at(0), '-');
std::vector<int> timeChunks = SplitToI(dateTime.at(1), ':');
timeInfo->tm_year = dateChunks.at(0) - 1900;
timeInfo->tm_mon = dateChunks.at(1) - 1;
timeInfo->tm_mday = dateChunks.at(2);
timeInfo->tm_hour = timeChunks.at(0);
timeInfo->tm_min = timeChunks.at(1);
timeInfo->tm_sec = timeChunks.at(2);
return timeInfo;
}
struct tm* TimeResolver::GetCurrentUTCTime ()
{
time_t rawTime;
time(&rawTime);
return gmtime(&rawTime);
}
std::vector<int> TimeResolver::SplitToI (const std::string &s, char delim)
{
std::stringstream ss(s);
std::string item;
std::vector<int> integers;
while(std::getline(ss, item, delim))
integers.push_back((int)strtol(item.c_str(), NULL, 10));
return integers;
}
std::vector<std::string> TimeResolver::SplitToStr (const std::string &s, char delim)
{
std::stringstream ss(s);
std::string item;
std::vector<std::string> strings;
while(std::getline(ss, item, delim))
strings.push_back(item);
return strings;
}
| 4,380 | 29.423611 | 130 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/TimeResolver.h | /*
* TimeResolver.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_MPD_TIMERESOLVER_H_
#define LIBDASH_FRAMEWORK_MPD_TIMERESOLVER_H_
#include <time.h>
#include "config.h"
namespace libdash
{
namespace framework
{
namespace mpd
{
class TimeResolver
{
public:
static bool CheckTimeInterval (std::string availabilityStartTime, std::string availabilityEndTime);
static uint32_t GetCurrentTimeInSec ();
static uint32_t GetUTCDateTimeInSec (const std::string& datetime);
static double GetDurationInSec (const std::string& duration);
private:
static struct tm* ResolveUTCDateTime (const std::string& timeString);
static struct tm* GetCurrentUTCTime ();
static std::vector<int> SplitToI (const std::string &s, char delim);
static std::vector<std::string> SplitToStr (const std::string &s, char delim);
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_MPD_TIMERESOLVER_H_ */
| 1,601 | 35.409091 | 129 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/SingleMediaSegmentStream.h | /*
* SingleMediaSegmentStream.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_MPD_SINGLEMEDIASEGMENTSTREAM_H_
#define LIBDASH_FRAMEWORK_MPD_SINGLEMEDIASEGMENTSTREAM_H_
#include "IMPD.h"
#include "AbstractRepresentationStream.h"
#include "ISegment.h"
namespace libdash
{
namespace framework
{
namespace mpd
{
class SingleMediaSegmentStream: public AbstractRepresentationStream
{
public:
SingleMediaSegmentStream (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, dash::mpd::IRepresentation *representation);
virtual ~SingleMediaSegmentStream ();
virtual dash::mpd::ISegment* GetInitializationSegment ();
virtual dash::mpd::ISegment* GetIndexSegment (size_t segmentNumber);
virtual dash::mpd::ISegment* GetMediaSegment (size_t segmentNumber);
virtual dash::mpd::ISegment* GetBitstreamSwitchingSegment ();
virtual RepresentationStreamType GetStreamType ();
virtual uint32_t GetFirstSegmentNumber ();
virtual uint32_t GetCurrentSegmentNumber ();
virtual uint32_t GetLastSegmentNumber ();
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_MPD_SINGLEMEDIASEGMENTSTREAM_H_ */ | 1,972 | 41.891304 | 192 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/BaseUrlResolver.h | /*
* BaseUrlResolver.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_MPD_BASEURLRESOLVER_H_
#define LIBDASH_FRAMEWORK_MPD_BASEURLRESOLVER_H_
#include "IMPD.h"
namespace libdash
{
namespace framework
{
namespace mpd
{
class BaseUrlResolver
{
public:
static std::vector<dash::mpd::IBaseUrl *> ResolveBaseUrl (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet,
size_t mpdBaseUrl, size_t periodBaseUrl, size_t adaptationSetBaseUrl);
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_MPD_BASEURLRESOLVER_H_ */
| 1,122 | 32.029412 | 173 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/AbstractRepresentationStream.h | /*
* AbstractRepresentationStream.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_MPD_ABSTRACTREPRESENTATIONSTREAM_H_
#define LIBDASH_FRAMEWORK_MPD_ABSTRACTREPRESENTATIONSTREAM_H_
#include "IRepresentationStream.h"
#include "IBaseUrl.h"
#include "IRepresentation.h"
#include "IAdaptationSet.h"
#include "IMPD.h"
#include "IPeriod.h"
#include "BaseUrlResolver.h"
#include "TimeResolver.h"
namespace libdash
{
namespace framework
{
namespace mpd
{
class AbstractRepresentationStream : public IRepresentationStream
{
public:
AbstractRepresentationStream (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet,
dash::mpd::IRepresentation *representation);
virtual ~AbstractRepresentationStream ();
virtual dash::mpd::ISegment* GetInitializationSegment () = 0;
virtual dash::mpd::ISegment* GetIndexSegment (size_t segmentNumber) = 0;
virtual dash::mpd::ISegment* GetMediaSegment (size_t segmentNumber) = 0;
virtual dash::mpd::ISegment* GetBitstreamSwitchingSegment () = 0;
virtual RepresentationStreamType GetStreamType () = 0;
virtual uint32_t GetSize ();
virtual uint32_t GetFirstSegmentNumber ();
virtual uint32_t GetCurrentSegmentNumber ();
virtual uint32_t GetLastSegmentNumber ();
virtual uint32_t GetAverageSegmentDuration ();
protected:
virtual void SetBaseUrls (const std::vector<dash::mpd::IBaseUrl *> baseurls);
std::vector<dash::mpd::IBaseUrl *> baseUrls;
dash::mpd::IMPD *mpd;
dash::mpd::IPeriod *period;
dash::mpd::IAdaptationSet *adaptationSet;
dash::mpd::IRepresentation *representation;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_ADAPTATION_ABSTRACTADAPTATIONLOGIC_H_ */
| 2,896 | 45.725806 | 152 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/SingleMediaSegmentStream.cpp | /*
* SingleMediaSegmentStream.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 "SingleMediaSegmentStream.h"
using namespace dash::mpd;
using namespace libdash::framework::mpd;
SingleMediaSegmentStream::SingleMediaSegmentStream (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, IRepresentation *representation) :
AbstractRepresentationStream (mpd, period, adaptationSet, representation)
{
this->baseUrls = BaseUrlResolver::ResolveBaseUrl(mpd, period, adaptationSet, 0, 0, 0);
}
SingleMediaSegmentStream::~SingleMediaSegmentStream ()
{
}
ISegment* SingleMediaSegmentStream::GetInitializationSegment ()
{
if (this->representation->GetSegmentBase())
{
/* TODO: check whether @sourceURL and/or @range is available in SegmentBase.Initialization, see Table 13 */
if (this->representation->GetSegmentBase()->GetInitialization())
return this->representation->GetSegmentBase()->GetInitialization()->ToSegment(baseUrls);
}
return NULL;
}
ISegment* SingleMediaSegmentStream::GetIndexSegment (size_t segmentNumber)
{
/* segmentNumber is not used in this case */
if (this->representation->GetSegmentBase())
{
if (this->representation->GetSegmentBase()->GetRepresentationIndex())
return this->representation->GetSegmentBase()->GetRepresentationIndex()->ToSegment(baseUrls);
}
return NULL;
}
ISegment* SingleMediaSegmentStream::GetMediaSegment (size_t segmentNumber)
{
/* segmentNumber equals the desired BaseUrl */
if (this->representation->GetBaseURLs().size() > segmentNumber)
return this->representation->GetBaseURLs().at(segmentNumber)->ToMediaSegment(baseUrls);
return this->representation->GetBaseURLs().at(0)->ToMediaSegment(baseUrls);
}
ISegment* SingleMediaSegmentStream::GetBitstreamSwitchingSegment ()
{
/* not possible */
return NULL;
}
RepresentationStreamType SingleMediaSegmentStream::GetStreamType ()
{
return SingleMediaSegment;
}
uint32_t SingleMediaSegmentStream::GetFirstSegmentNumber ()
{
return 0;
}
uint32_t SingleMediaSegmentStream::GetCurrentSegmentNumber ()
{
return 0;
}
uint32_t SingleMediaSegmentStream::GetLastSegmentNumber ()
{
return 0;
} | 2,827 | 36.210526 | 150 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/AdaptationSetStream.cpp |
/*
* AbstractRepresentationStream.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 "AdaptationSetStream.h"
using namespace libdash::framework::mpd;
using namespace dash::mpd;
AdaptationSetStream::AdaptationSetStream (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet) :
mpd (mpd),
period (period),
adaptationSet (adaptationSet)
{
Initialize();
}
AdaptationSetStream::~AdaptationSetStream()
{
std::map<IRepresentation *, IRepresentationStream *>::iterator iter;
for (iter = representations.begin(); iter != representations.end(); ++iter)
{
delete(iter->second);
}
}
IRepresentationStream* AdaptationSetStream::GetRepresentationStream (IRepresentation *representation)
{
return this->representations.find(representation)->second;
}
RepresentationStreamType AdaptationSetStream::DetermineRepresentationStreamType (IRepresentation *representation)
{
/* check on Representation Level */
if (representation->GetSegmentList())
return libdash::framework::mpd::SegmentList;
if (representation->GetSegmentTemplate())
return libdash::framework::mpd::SegmentTemplate;
if (representation->GetSegmentBase() || representation->GetBaseURLs().size() > 0)
return libdash::framework::mpd::SingleMediaSegment;
/* check on AdaptationSet Level */
if (this->adaptationSet->GetSegmentList())
return libdash::framework::mpd::SegmentList;
if (this->adaptationSet->GetSegmentTemplate())
return libdash::framework::mpd::SegmentTemplate;
if (this->adaptationSet->GetSegmentBase())
return libdash::framework::mpd::SingleMediaSegment;
/* check on Period Level */
if (this->period->GetSegmentList())
return libdash::framework::mpd::SegmentList;
if (this->period->GetSegmentTemplate())
return libdash::framework::mpd::SegmentTemplate;
if (this->period->GetSegmentBase())
return libdash::framework::mpd::SingleMediaSegment;
return libdash::framework::mpd::UNDEFINED;
}
void AdaptationSetStream::Initialize()
{
for (size_t i = 0; i < adaptationSet->GetRepresentation().size(); i++)
{
IRepresentation *representation = adaptationSet->GetRepresentation().at(i);
RepresentationStreamType type = DetermineRepresentationStreamType(representation);
representations[representation] = RepresentationStreamFactory::Create(type, mpd, period, adaptationSet, representation);
}
}
| 2,965 | 36.075 | 128 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/SegmentTemplateStream.cpp | /*
* SegmentTemplateStream.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 "SegmentTemplateStream.h"
using namespace dash::mpd;
using namespace libdash::framework::mpd;
SegmentTemplateStream::SegmentTemplateStream (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, IRepresentation *representation) :
AbstractRepresentationStream (mpd, period, adaptationSet, representation)
{
this->baseUrls = BaseUrlResolver::ResolveBaseUrl(mpd, period, adaptationSet, 0, 0, 0);
this->segmentTemplate = FindSegmentTemplate();
CalculateSegmentStartTimes();
}
SegmentTemplateStream::~SegmentTemplateStream ()
{
}
ISegment* SegmentTemplateStream::GetInitializationSegment ()
{
if (this->segmentTemplate->GetInitialization())
return this->segmentTemplate->GetInitialization()->ToSegment(baseUrls);
return this->segmentTemplate->ToInitializationSegment(baseUrls, representation->GetId(), representation->GetBandwidth());
}
ISegment* SegmentTemplateStream::GetIndexSegment (size_t segmentNumber)
{
/* time-based template */
if (this->segmentTemplate->GetSegmentTimeline())
{
if (this->segmentStartTimes.size() > segmentNumber)
return this->segmentTemplate->GetIndexSegmentFromTime(baseUrls, representation->GetId(), representation->GetBandwidth(), this->segmentStartTimes.at(segmentNumber));
return NULL;
}
/* number-based template */
return this->segmentTemplate->GetIndexSegmentFromNumber(baseUrls, representation->GetId(), representation->GetBandwidth(),
this->segmentTemplate->GetStartNumber() + segmentNumber);
}
ISegment* SegmentTemplateStream::GetMediaSegment (size_t segmentNumber)
{
/* time-based template */
if (this->segmentTemplate->GetSegmentTimeline())
{
if (this->segmentStartTimes.size() > segmentNumber)
return this->segmentTemplate->GetMediaSegmentFromTime(baseUrls, representation->GetId(), representation->GetBandwidth(), this->segmentStartTimes.at(segmentNumber));
return NULL;
}
/* number-based template */
return this->segmentTemplate->GetMediaSegmentFromNumber(baseUrls, representation->GetId(), representation->GetBandwidth(),
this->segmentTemplate->GetStartNumber() + segmentNumber);
}
ISegment* SegmentTemplateStream::GetBitstreamSwitchingSegment ()
{
if (this->segmentTemplate->GetBitstreamSwitching())
return this->segmentTemplate->GetBitstreamSwitching()->ToSegment(baseUrls);
return this->segmentTemplate->ToBitstreamSwitchingSegment(baseUrls, representation->GetId(), representation->GetBandwidth());
}
RepresentationStreamType SegmentTemplateStream::GetStreamType ()
{
return SegmentList;
}
uint32_t SegmentTemplateStream::GetSize ()
{
if (!this->segmentStartTimes.empty())
return this->segmentStartTimes.size();
uint32_t numberOfSegments = 0;
double mediaPresentationDuration = 0;
if (this->mpd->GetType() == "static")
{
mediaPresentationDuration = TimeResolver::GetDurationInSec(this->mpd->GetMediaPresentationDuration());
numberOfSegments = (uint32_t) ceil(mediaPresentationDuration / (this->segmentTemplate->GetDuration() / this->segmentTemplate->GetTimescale()));
}
else
{
numberOfSegments = UINT32_MAX - 1;
}
return numberOfSegments;
}
uint32_t SegmentTemplateStream::GetAverageSegmentDuration ()
{
/* TODO calculate average segment durations for SegmentTimeline */
return this->segmentTemplate->GetDuration();
}
ISegmentTemplate* SegmentTemplateStream::FindSegmentTemplate ()
{
if (this->representation->GetSegmentTemplate())
return this->representation->GetSegmentTemplate();
if (this->adaptationSet->GetSegmentTemplate())
return this->adaptationSet->GetSegmentTemplate();
if (this->period->GetSegmentTemplate())
return this->period->GetSegmentTemplate();
return NULL;
}
void SegmentTemplateStream::CalculateSegmentStartTimes ()
{
if (!this->segmentTemplate->GetSegmentTimeline())
return;
size_t numOfTimelines = 0;
uint32_t segStartTime = 0;
uint32_t segDuration = 0;
size_t repeatCount = 0;
numOfTimelines = this->segmentTemplate->GetSegmentTimeline()->GetTimelines().size();
for (size_t i = 0; i < numOfTimelines; i++)
{
repeatCount = this->segmentTemplate->GetSegmentTimeline()->GetTimelines().at(i)->GetRepeatCount();
segStartTime = this->segmentTemplate->GetSegmentTimeline()->GetTimelines().at(i)->GetStartTime();
segDuration = this->segmentTemplate->GetSegmentTimeline()->GetTimelines().at(i)->GetDuration();
if (repeatCount > 0)
{
for (size_t j = 0; j <= repeatCount; j++)
{
if (segStartTime > 0)
{
this->segmentStartTimes.push_back(segStartTime + segDuration * j);
}
else
{
/* TODO: implement if SegmentTemplate.SegmentTimeline.S@t is not specified */
}
}
}
else
{
this->segmentStartTimes.push_back(segStartTime);
}
}
}
| 5,976 | 38.065359 | 176 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/RepresentationStreamFactory.cpp | /*
* RepresentationStreamFactory.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 "RepresentationStreamFactory.h"
using namespace libdash::framework::mpd;
using namespace dash::mpd;
IRepresentationStream* RepresentationStreamFactory::Create(RepresentationStreamType type, IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, IRepresentation *representation)
{
switch(type)
{
case SingleMediaSegment: return new SingleMediaSegmentStream(mpd, period, adaptationSet, representation);
case SegmentList: return new SegmentListStream (mpd, period, adaptationSet, representation);
case SegmentTemplate: return new SegmentTemplateStream (mpd, period, adaptationSet, representation);
default: return NULL;
}
}
| 1,166 | 40.678571 | 182 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/AdaptationSetHelper.cpp | /*
* AbstractSetHelper.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 "AdaptationSetHelper.h"
using namespace libdash::framework::mpd;
using namespace dash::mpd;
std::vector<IAdaptationSet *> AdaptationSetHelper::GetAudioAdaptationSets (dash::mpd::IPeriod *period)
{
std::vector<IAdaptationSet *> audioAdaptationSets;
std::vector<IAdaptationSet *> adaptationSets = period->GetAdaptationSets();
for (size_t i = 0; i < adaptationSets.size(); i++)
if (AdaptationSetHelper::IsAudioAdaptationSet(adaptationSets.at(i)))
audioAdaptationSets.push_back(adaptationSets.at(i));
return audioAdaptationSets;
}
std::vector<IAdaptationSet *> AdaptationSetHelper::GetVideoAdaptationSets (dash::mpd::IPeriod *period)
{
std::vector<IAdaptationSet *> videoAdaptationSets;
std::vector<IAdaptationSet *> adaptationSets = period->GetAdaptationSets();
for (size_t i = 0; i < adaptationSets.size(); i++)
if (AdaptationSetHelper::IsVideoAdaptationSet(adaptationSets.at(i)))
videoAdaptationSets.push_back(adaptationSets.at(i));
return videoAdaptationSets;
}
bool AdaptationSetHelper::IsAudioAdaptationSet (dash::mpd::IAdaptationSet *adaptationSet)
{
return IsContainedInMimeType(adaptationSet, "audio");
}
bool AdaptationSetHelper::IsVideoAdaptationSet (dash::mpd::IAdaptationSet *adaptationSet)
{
return IsContainedInMimeType(adaptationSet, "video");
}
bool AdaptationSetHelper::IsContainedInMimeType (dash::mpd::IAdaptationSet *adaptationSet, std::string value)
{
if (adaptationSet->GetMimeType() != "")
if (adaptationSet->GetMimeType().find(value) != std::string::npos)
return true;
for (size_t i = 0; i < adaptationSet->GetRepresentation().size(); i++)
if (adaptationSet->GetRepresentation().at(i)->GetMimeType() != "")
if (adaptationSet->GetRepresentation().at(i)->GetMimeType().find(value) != std::string::npos)
return true;
return false;
}
| 2,446 | 39.783333 | 137 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/AdaptationSetHelper.h | /*
* AbstractSetHelper.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_MPD_ADAPTATIONSETHELPER_H_
#define LIBDASH_FRAMEWORK_MPD_ADAPTATIONSETHELPER_H_
#include "IMPD.h"
namespace libdash
{
namespace framework
{
namespace mpd
{
class AdaptationSetHelper
{
public:
static std::vector<dash::mpd::IAdaptationSet *> GetAudioAdaptationSets (dash::mpd::IPeriod *period);
static std::vector<dash::mpd::IAdaptationSet *> GetVideoAdaptationSets (dash::mpd::IPeriod *period);
static bool IsAudioAdaptationSet (dash::mpd::IAdaptationSet *adaptationSet);
static bool IsVideoAdaptationSet (dash::mpd::IAdaptationSet *adaptationSet);
static bool IsContainedInMimeType (dash::mpd::IAdaptationSet *adaptationSet, std::string value);
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_MPD_ADAPTATIONSETHELPER_H_ */
| 1,484 | 40.25 | 154 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/SegmentTemplateStream.h | /*
* SegmentTemplateStream.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_MPD_SEGMENTTEMPLATESTREAM_H_
#define LIBDASH_FRAMEWORK_MPD_SEGMENTTEMPLATESTREAM_H_
#include <math.h>
#include "IMPD.h"
#include "AbstractRepresentationStream.h"
#include "ISegment.h"
#include "ISegmentTemplate.h"
namespace libdash
{
namespace framework
{
namespace mpd
{
class SegmentTemplateStream: public AbstractRepresentationStream
{
public:
SegmentTemplateStream (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, dash::mpd::IRepresentation *representation);
virtual ~SegmentTemplateStream ();
virtual dash::mpd::ISegment* GetInitializationSegment ();
virtual dash::mpd::ISegment* GetIndexSegment (size_t segmentNumber);
virtual dash::mpd::ISegment* GetMediaSegment (size_t segmentNumber);
virtual dash::mpd::ISegment* GetBitstreamSwitchingSegment ();
virtual RepresentationStreamType GetStreamType ();
virtual uint32_t GetSize ();
virtual uint32_t GetAverageSegmentDuration ();
private:
dash::mpd::ISegmentTemplate* FindSegmentTemplate ();
void CalculateSegmentStartTimes ();
dash::mpd::ISegmentTemplate *segmentTemplate;
std::vector<uint32_t> segmentStartTimes;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_MPD_SEGMENTTEMPLATESTREAM_H_ */
| 2,252 | 39.963636 | 189 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/BaseUrlResolver.cpp | /*
* BaseUrlResolver.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 "BaseUrlResolver.h"
using namespace dash::mpd;
using namespace libdash::framework::mpd;
std::vector<dash::mpd::IBaseUrl *> BaseUrlResolver::ResolveBaseUrl(IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet,
size_t mpdBaseUrl, size_t periodBaseUrl, size_t adaptationSetBaseUrl)
{
std::vector<dash::mpd::IBaseUrl *> urls;
if (mpd->GetBaseUrls().size() > 0)
{
if (mpd->GetBaseUrls().size() > mpdBaseUrl)
urls.push_back(mpd->GetBaseUrls().at(mpdBaseUrl));
else
urls.push_back(mpd->GetBaseUrls().at(0));
}
if (period->GetBaseURLs().size() > 0)
{
if (period->GetBaseURLs().size() > periodBaseUrl)
urls.push_back(period->GetBaseURLs().at(periodBaseUrl));
else
urls.push_back(period->GetBaseURLs().at(0));
}
if (adaptationSet->GetBaseURLs().size() > 0)
{
if (adaptationSet->GetBaseURLs().size() > adaptationSetBaseUrl)
urls.push_back(adaptationSet->GetBaseURLs().at(adaptationSetBaseUrl));
else
urls.push_back(adaptationSet->GetBaseURLs().at(0));
}
if (urls.size() > 0)
{
if (urls.at(0)->GetUrl().substr(0,7) != "http://" && urls.at(0)->GetUrl().substr(0,8) != "https://")
{
urls.push_back(mpd->GetMPDPathBaseUrl());
size_t lastPos = urls.size() - 1;
IBaseUrl *absoluteUrl = urls.at(lastPos);
for (size_t i = lastPos; i > 0; i--)
{
urls[i] = urls[i-1];
}
urls[0] = absoluteUrl;
}
}
else
{
urls.push_back(mpd->GetMPDPathBaseUrl());
}
return urls;
}
| 2,187 | 32.661538 | 136 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/SegmentListStream.cpp | /*
* SegmentListStream.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 "SegmentListStream.h"
using namespace dash::mpd;
using namespace libdash::framework::mpd;
SegmentListStream::SegmentListStream (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, IRepresentation *representation) :
AbstractRepresentationStream (mpd, period, adaptationSet, representation)
{
this->baseUrls = BaseUrlResolver::ResolveBaseUrl(mpd, period, adaptationSet, 0, 0, 0);
this->segmentList = FindSegmentList();
}
SegmentListStream::~SegmentListStream ()
{
}
ISegment* SegmentListStream::GetInitializationSegment ()
{
if (this->segmentList->GetInitialization())
return this->segmentList->GetInitialization()->ToSegment(this->baseUrls);
return NULL;
}
ISegment* SegmentListStream::GetIndexSegment (size_t segmentNumber)
{
if (this->segmentList->GetSegmentURLs().size() > segmentNumber)
return this->segmentList->GetSegmentURLs().at(segmentNumber)->ToIndexSegment(this->baseUrls);
return NULL;
}
ISegment* SegmentListStream::GetMediaSegment (size_t segmentNumber)
{
if (this->segmentList->GetSegmentURLs().size() > segmentNumber)
return this->segmentList->GetSegmentURLs().at(segmentNumber)->ToMediaSegment(this->baseUrls);
return NULL;
}
ISegment* SegmentListStream::GetBitstreamSwitchingSegment ()
{
if (this->segmentList->GetBitstreamSwitching())
return this->segmentList->GetBitstreamSwitching()->ToSegment(baseUrls);
return NULL;
}
RepresentationStreamType SegmentListStream::GetStreamType ()
{
return SegmentList;
}
uint32_t SegmentListStream::GetSize ()
{
return this->segmentList->GetSegmentURLs().size();
}
ISegmentList* SegmentListStream::FindSegmentList ()
{
if (this->representation->GetSegmentList())
return this->representation->GetSegmentList();
if (this->adaptationSet->GetSegmentList())
return this->adaptationSet->GetSegmentList();
if (this->period->GetSegmentList())
return this->period->GetSegmentList();
return NULL;
}
uint32_t SegmentListStream::GetAverageSegmentDuration ()
{
/* TODO calculate average segment durations for SegmentTimeline */
return this->segmentList->GetDuration();
}
| 2,862 | 34.7875 | 142 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/SegmentListStream.h | /*
* SegmentListStream.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_MPD_SEGMENTLISTSTREAM_H_
#define LIBDASH_FRAMEWORK_MPD_SEGMENTLISTSTREAM_H_
#include "IMPD.h"
#include "AbstractRepresentationStream.h"
#include "ISegment.h"
#include "ISegmentList.h"
namespace libdash
{
namespace framework
{
namespace mpd
{
class SegmentListStream: public AbstractRepresentationStream
{
public:
SegmentListStream (dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period, dash::mpd::IAdaptationSet *adaptationSet, dash::mpd::IRepresentation *representation);
virtual ~SegmentListStream ();
virtual dash::mpd::ISegment* GetInitializationSegment ();
virtual dash::mpd::ISegment* GetIndexSegment (size_t segmentNumber);
virtual dash::mpd::ISegment* GetMediaSegment (size_t segmentNumber);
virtual dash::mpd::ISegment* GetBitstreamSwitchingSegment ();
virtual RepresentationStreamType GetStreamType ();
virtual uint32_t GetSize ();
virtual uint32_t GetAverageSegmentDuration ();
private:
dash::mpd::ISegmentList* FindSegmentList ();
dash::mpd::ISegmentList *segmentList;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_MPD_SEGMENTLISTSTREAM_H_ */
| 2,046 | 39.137255 | 185 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/IRepresentationStream.h | /*
* IRepresentationStream.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_MPD_IREPRESENTATIONSTREAM_H_
#define LIBDASH_FRAMEWORK_MPD_IREPRESENTATIONSTREAM_H_
#include "ISegment.h"
namespace libdash
{
namespace framework
{
namespace mpd
{
enum RepresentationStreamType
{
SingleMediaSegment,
SegmentList,
SegmentTemplate,
UNDEFINED
};
class IRepresentationStream
{
public:
virtual ~IRepresentationStream () {}
virtual dash::mpd::ISegment* GetInitializationSegment () = 0;
virtual dash::mpd::ISegment* GetIndexSegment (size_t segmentNumber) = 0;
virtual dash::mpd::ISegment* GetMediaSegment (size_t segmentNumber) = 0;
virtual dash::mpd::ISegment* GetBitstreamSwitchingSegment () = 0;
virtual RepresentationStreamType GetStreamType () = 0;
virtual uint32_t GetSize () = 0;
virtual uint32_t GetFirstSegmentNumber () = 0;
virtual uint32_t GetCurrentSegmentNumber () = 0;
virtual uint32_t GetLastSegmentNumber () = 0;
virtual uint32_t GetAverageSegmentDuration () = 0;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_MPD_IREPRESENTATIONSTREAM_H_ */
| 2,083 | 39.862745 | 115 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/AbstractRepresentationStream.cpp | /*
* AbstractRepresentationStream.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 "AbstractRepresentationStream.h"
using namespace libdash::framework::mpd;
using namespace dash::mpd;
AbstractRepresentationStream::AbstractRepresentationStream (IMPD *mpd, IPeriod *period, IAdaptationSet *adaptationSet, IRepresentation *representation) :
mpd (mpd),
period (period),
adaptationSet (adaptationSet),
representation (representation)
{
}
AbstractRepresentationStream::~AbstractRepresentationStream ()
{
}
void AbstractRepresentationStream::SetBaseUrls (const std::vector<dash::mpd::IBaseUrl *> baseurls)
{
this->baseUrls.clear();
for (size_t i = 0; i < baseurls.size(); i++)
this->baseUrls.push_back(baseurls.at(i));
}
uint32_t AbstractRepresentationStream::GetSize ()
{
return UINT32_MAX - 1;
}
uint32_t AbstractRepresentationStream::GetFirstSegmentNumber ()
{
if (this->mpd->GetType() == "dynamic")
{
uint32_t currTime = TimeResolver::GetCurrentTimeInSec();
uint32_t availStT = TimeResolver::GetUTCDateTimeInSec(this->mpd->GetAvailabilityStarttime());
uint32_t duration = this->GetAverageSegmentDuration();
uint32_t timeshift = TimeResolver::GetDurationInSec(this->mpd->GetTimeShiftBufferDepth());
return (currTime - duration - availStT - timeshift ) / duration;
}
return 0;
}
uint32_t AbstractRepresentationStream::GetCurrentSegmentNumber ()
{
if (this->mpd->GetType() == "dynamic")
{
uint32_t currTime = TimeResolver::GetCurrentTimeInSec();
uint32_t duration = this->GetAverageSegmentDuration();
uint32_t availStT = TimeResolver::GetUTCDateTimeInSec(this->mpd->GetAvailabilityStarttime());
return (currTime - duration - availStT) / duration;
}
return 0;
}
uint32_t AbstractRepresentationStream::GetLastSegmentNumber ()
{
if (this->mpd->GetType() == "dynamic")
{
uint32_t currTime = TimeResolver::GetCurrentTimeInSec();
uint32_t duration = this->GetAverageSegmentDuration();
uint32_t availStT = TimeResolver::GetUTCDateTimeInSec(this->mpd->GetAvailabilityStarttime());
uint32_t checkTime = mpd->GetFetchTime() +
TimeResolver::GetDurationInSec(this->mpd->GetMinimumUpdatePeriod());
return ( ((checkTime > currTime) ? currTime : checkTime) - duration - availStT) / duration;
}
return 0;
}
uint32_t AbstractRepresentationStream::GetAverageSegmentDuration ()
{
return 1;
}
| 3,147 | 36.035294 | 154 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/MPD/RepresentationStreamFactory.h | /*
* RepresentationStreamFactory.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_MPD_RERPRESENTATIONSTREAMFACTORY_H_
#define LIBDASH_FRAMEWORK_MPD_RERPRESENTATIONSTREAMFACTORY_H_
#include "IRepresentationStream.h"
#include "SingleMediaSegmentStream.h"
#include "SegmentListStream.h"
#include "SegmentTemplateStream.h"
#include "IRepresentation.h"
namespace libdash
{
namespace framework
{
namespace mpd
{
class RepresentationStreamFactory
{
public:
static IRepresentationStream* Create(libdash::framework::mpd::RepresentationStreamType type, dash::mpd::IMPD *mpd, dash::mpd::IPeriod *period,
dash::mpd::IAdaptationSet *adaptationSet, dash::mpd::IRepresentation *representation);
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_MPD_RERPRESENTATIONSTREAMFACTORY_H_ */
| 1,317 | 32.794872 | 162 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Buffer/AudioChunk.cpp | /*
* AudioChunk.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 "AudioChunk.h"
using namespace libdash::framework::buffer;
AudioChunk::AudioChunk (QAudioFormat *format, char* data, qint64 dataLength) :
chunkLength (dataLength),
format (format)
{
this->data = (char*) malloc(this->chunkLength);
memcpy(this->data, data, this->chunkLength);
}
AudioChunk::~AudioChunk ()
{
delete this->format;
free(this->data);
}
char* AudioChunk::Data ()
{
return this->data;
}
qint64 AudioChunk::Length ()
{
return this->chunkLength;
}
QAudioFormat* AudioChunk::Format ()
{
return this->format;
}
| 1,045 | 24.512195 | 79 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Buffer/Buffer.h | /*
* Buffer.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_BUFFER_BUFFER_H_
#define LIBDASH_FRAMEWORK_BUFFER_BUFFER_H_
#include "../Portable/MultiThreading.h"
#include "IBufferObserver.h"
#include <deque>
#include <vector>
namespace libdash
{
namespace framework
{
/*struct ImageWrap
{
QImage *image;
uint8_t *data;
};
*/
namespace buffer
{
template <class T>
class Buffer
{
public:
Buffer (uint32_t maxcapacity, BufferType type);
virtual ~Buffer ();
bool PushBack (T *element);
T* Front ();
T* GetFront ();
void PopFront ();
void ClearTail ();
void Clear ();
void SetEOS (bool value);
uint32_t Length ();
uint32_t Capacity ();
void AttachObserver (IBufferObserver *observer);
void Notify ();
private:
std::deque<T*> objects;
std::vector<IBufferObserver *> observer;
bool eos;
uint32_t maxcapacity;
mutable CRITICAL_SECTION monitorMutex;
mutable CONDITION_VARIABLE full;
mutable CONDITION_VARIABLE empty;
BufferType type;
};
}
}
}
using namespace libdash::framework::buffer;
template <class T>
Buffer<T>::Buffer (uint32_t maxcapacity, BufferType type) :
type (type),
eos (false),
maxcapacity (maxcapacity)
{
InitializeConditionVariable (&this->full);
InitializeConditionVariable (&this->empty);
InitializeCriticalSection (&this->monitorMutex);
}
template <class T>
Buffer<T>::~Buffer ()
{
this->Clear();
DeleteConditionVariable (&this->full);
DeleteConditionVariable (&this->empty);
DeleteCriticalSection (&this->monitorMutex);
}
template <class T>
bool Buffer<T>::PushBack (T *object)
{
EnterCriticalSection(&this->monitorMutex);
while(this->objects.size() >= this->maxcapacity && !this->eos)
SleepConditionVariableCS(&this->empty, &this->monitorMutex, INFINITE);
if(this->objects.size() >= this->maxcapacity)
{
LeaveCriticalSection(&this->monitorMutex);
return false;
}
this->objects.push_back(object);
WakeAllConditionVariable(&this->full);
LeaveCriticalSection(&this->monitorMutex);
this->Notify();
return true;
}
template <class T>
T* Buffer<T>::Front ()
{
EnterCriticalSection(&this->monitorMutex);
while(this->objects.size() == 0 && !this->eos)
SleepConditionVariableCS(&this->full, &this->monitorMutex, INFINITE);
if(this->objects.size() == 0)
{
LeaveCriticalSection(&this->monitorMutex);
return NULL;
}
T *object = this->objects.front();
LeaveCriticalSection(&this->monitorMutex);
return object;
}
template <class T>
T* Buffer<T>::GetFront ()
{
EnterCriticalSection(&this->monitorMutex);
while(this->objects.size() == 0 && !this->eos)
SleepConditionVariableCS(&this->full, &this->monitorMutex, INFINITE);
if(this->objects.size() == 0)
{
LeaveCriticalSection(&this->monitorMutex);
return NULL;
}
T *object = this->objects.front();
this->objects.pop_front();
this->objects.shrink_to_fit();
WakeAllConditionVariable(&this->empty);
LeaveCriticalSection(&this->monitorMutex);
this->Notify();
return object;
}
template <class T>
uint32_t Buffer<T>::Length ()
{
EnterCriticalSection(&this->monitorMutex);
uint32_t ret = this->objects.size();
LeaveCriticalSection(&this->monitorMutex);
return ret;
}
template <class T>
void Buffer<T>::PopFront ()
{
EnterCriticalSection(&this->monitorMutex);
this->objects.pop_front();
this->objects.shrink_to_fit();
WakeAllConditionVariable(&this->empty);
LeaveCriticalSection(&this->monitorMutex);
this->Notify();
}
template <class T>
void Buffer<T>::SetEOS (bool value)
{
EnterCriticalSection(&this->monitorMutex);
this->eos = value;
WakeAllConditionVariable(&this->empty);
WakeAllConditionVariable(&this->full);
LeaveCriticalSection(&this->monitorMutex);
}
template <class T>
void Buffer<T>::AttachObserver (IBufferObserver *observer)
{
this->observer.push_back(observer);
}
template <class T>
void Buffer<T>::Notify ()
{
for(size_t i = 0; i < this->observer.size(); i++)
this->observer.at(i)->OnBufferStateChanged(this->type, (uint32_t)((double)this->objects.size()/(double)this->maxcapacity*100.0));
}
template <class T>
void Buffer<T>::ClearTail ()
{
EnterCriticalSection(&this->monitorMutex);
int size = this->objects.size() - 1;
if (size < 1)
{
LeaveCriticalSection(&this->monitorMutex);
return;
}
T* object = this->objects.front();
this->objects.pop_front();
for(int i=0; i < size; i++)
{
delete this->objects.front();
this->objects.pop_front();
}
this->objects.shrink_to_fit();
this->objects.push_back(object);
WakeAllConditionVariable(&this->empty);
WakeAllConditionVariable(&this->full);
LeaveCriticalSection(&this->monitorMutex);
this->Notify();
}
template <class T>
void Buffer<T>::Clear ()
{
EnterCriticalSection(&this->monitorMutex);
for(int i = 0; i < this->objects.size(); i++)
delete this->objects[i];
this->objects.clear();
this->objects.shrink_to_fit();
WakeAllConditionVariable(&this->empty);
WakeAllConditionVariable(&this->full);
LeaveCriticalSection(&this->monitorMutex);
this->Notify();
}
template <class T>
uint32_t Buffer<T>::Capacity ()
{
return this->maxcapacity;
}
#endif /* LIBDASH_FRAMEWORK_BUFFER_BUFFER_H_ */
| 6,776 | 26.54878 | 137 | h |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Buffer/MediaObjectBuffer.cpp | /*
* MediaObjectBuffer.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 "MediaObjectBuffer.h"
using namespace libdash::framework::buffer;
using namespace libdash::framework::input;
using namespace dash::mpd;
using namespace dash::network;
MediaObjectBuffer::MediaObjectBuffer (sampleplayer::managers::StreamType type, uint32_t maxcapacity) :
type (type),
eos (false),
maxcapacity (maxcapacity)
{
InitializeConditionVariable (&this->full);
InitializeConditionVariable (&this->empty);
InitializeCriticalSection (&this->monitorMutex);
}
MediaObjectBuffer::~MediaObjectBuffer ()
{
this->Clear();
DeleteConditionVariable (&this->full);
DeleteConditionVariable (&this->empty);
DeleteCriticalSection (&this->monitorMutex);
}
bool MediaObjectBuffer::PushBack (MediaObject *media)
{
Debug("Media Object Buffer: Pushing back\n");
EnterCriticalSection(&this->monitorMutex);
while(this->mediaobjects.size() >= this->maxcapacity && !this->eos)
SleepConditionVariableCS(&this->empty, &this->monitorMutex, INFINITE);
Debug("Media Object Buffer: Pushed back\n");
if(this->mediaobjects.size() >= this->maxcapacity)
{
LeaveCriticalSection(&this->monitorMutex);
return false;
}
this->mediaobjects.push_back(media);
WakeAllConditionVariable(&this->full);
LeaveCriticalSection(&this->monitorMutex);
this->Notify(MediaObjectBuffer::PushingBack, media);
return true;
}
MediaObject* MediaObjectBuffer::Front ()
{
EnterCriticalSection(&this->monitorMutex);
while(this->mediaobjects.size() == 0 && !this->eos)
SleepConditionVariableCS(&this->full, &this->monitorMutex, INFINITE);
if(this->mediaobjects.size() == 0)
{
LeaveCriticalSection(&this->monitorMutex);
return NULL;
}
MediaObject *object = this->mediaobjects.front();
LeaveCriticalSection(&this->monitorMutex);
return object;
}
MediaObject* MediaObjectBuffer::GetFront ()
{
Debug("Media Object Buffer: Asking for Front\n");
L("Media_object_buffer:\t%s\t%s\t%f\n", (this->type == sampleplayer::managers::StreamType::AUDIO)? "Audio": "Video", "Asking_Front" ,((double) this->mediaobjects.size()/(double) this->maxcapacity));
EnterCriticalSection(&this->monitorMutex);
bool isrebuf = false;
while(this->mediaobjects.size() == 0 && !this->eos)
{
L("Media_object_buffer:\tREBUFFERING_START\n");
isrebuf = true;
SleepConditionVariableCS(&this->full, &this->monitorMutex, INFINITE);
}
if(isrebuf)
L("Media_object_buffer:\tREBUFFERING_STOP\n");
Debug("Media Object Buffer: Got Front\n");
if(this->mediaobjects.size() == 0)
{
LeaveCriticalSection(&this->monitorMutex);
return NULL;
}
MediaObject *object = this->mediaobjects.front();
this->mediaobjects.pop_front();
WakeAllConditionVariable(&this->empty);
LeaveCriticalSection(&this->monitorMutex);
this->Notify(MediaObjectBuffer::GettingFront, object);
return object;
}
MediaObject* MediaObjectBuffer::ShouldAbort ()
{
MediaObject *mediaObject = NULL;
Debug("MEDIA OBJECT: SHOULD ABORT ENTERING LOCK\n");
EnterCriticalSection(&this->monitorMutex);
Debug("GOT THE LOCK\n");
if(this->mediaobjects.size() != 0)
{
mediaObject = this->mediaobjects.back();
this->mediaobjects.pop_back();
Debug("Aborting...\n");
mediaObject->AbortDownload();
WakeAllConditionVariable(&this->empty);
}
Debug("RELEASE THE LOCK\n");
LeaveCriticalSection(&this->monitorMutex);
//this->Notify();
Debug("RELEASED\n");
return mediaObject;
}
uint32_t MediaObjectBuffer::Length ()
{
EnterCriticalSection(&this->monitorMutex);
uint32_t ret = this->mediaobjects.size();
LeaveCriticalSection(&this->monitorMutex);
return ret;
}
/*void MediaObjectBuffer::PopFront ()
{
EnterCriticalSection(&this->monitorMutex);
this->mediaobjects.pop_front();
WakeAllConditionVariable(&this->empty);
LeaveCriticalSection(&this->monitorMutex);
this->Notify();
}
*/
void MediaObjectBuffer::SetEOS (bool value)
{
EnterCriticalSection(&this->monitorMutex);
for (size_t i = 0; i < this->mediaobjects.size(); i++)
this->mediaobjects.at(i)->AbortDownload();
this->eos = value;
WakeAllConditionVariable(&this->empty);
WakeAllConditionVariable(&this->full);
LeaveCriticalSection(&this->monitorMutex);
//As EOS means no more download, we can stop the adaptation logic
for(size_t i = 0; i < this->observer.size(); i++)
this->observer.at(i)->OnEOS(value);
}
void MediaObjectBuffer::AttachObserver (IMediaObjectBufferObserver *observer)
{
this->observer.push_back(observer);
}
void MediaObjectBuffer::Notify(enum NotificationType notifType, input::MediaObject* mediaObject)
{
L("Media_object_buffer:\t%s\t%s\t%s\t%f\n", (this->type == sampleplayer::managers::StreamType::AUDIO)? "Audio": "Video", (notifType == MediaObjectBuffer::GettingFront) ? "Got_Front" : (notifType == MediaObjectBuffer::PushingBack) ? "Pushed_Back" : "Cleared_Buffer" , (mediaObject != NULL) ? mediaObject->GetPath() : ".",((double) this->mediaobjects.size()/(double) this->maxcapacity));
for(size_t i = 0; i < this->observer.size(); i++)
this->observer.at(i)->OnBufferStateChanged((int)((double)this->mediaobjects.size()/(double)this->maxcapacity*100.0));
}
/*void MediaObjectBuffer::ClearTail ()
{
EnterCriticalSection(&this->monitorMutex);
int size = this->mediaobjects.size() - 1;
if (size < 1)
{
LeaveCriticalSection(&this->monitorMutex);
return;
}
MediaObject* object = this->mediaobjects.front();
this->mediaobjects.pop_front();
for(int i=0; i < size; i++)
{
delete this->mediaobjects.front();
this->mediaobjects.pop_front();
}
this->mediaobjects.push_back(object);
WakeAllConditionVariable(&this->empty);
WakeAllConditionVariable(&this->full);
LeaveCriticalSection(&this->monitorMutex);
this->Notify();
} */
void MediaObjectBuffer::Clear ()
{
EnterCriticalSection(&this->monitorMutex);
for(int i = 0; i < this->mediaobjects.size(); i++)
delete this->mediaobjects[i];
this->mediaobjects.clear();
WakeAllConditionVariable(&this->empty);
WakeAllConditionVariable(&this->full);
LeaveCriticalSection(&this->monitorMutex);
this->Notify(MediaObjectBuffer::ClearBuffer, NULL);
}
uint32_t MediaObjectBuffer::Capacity ()
{
return this->maxcapacity;
}
| 7,115 | 30.626667 | 386 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-dash/libdash/qtsampleplayer/libdashframework/Buffer/MediaObjectBuffer.h | /*
* MediaObjectBuffer.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_BUFFER_MEDIAOBJECTBUFFER_H_
#define LIBDASH_FRAMEWORK_BUFFER_MEDIAOBJECTBUFFER_H_
#include "../Input/MediaObject.h"
#include "../Portable/MultiThreading.h"
#include "IMediaObjectBufferObserver.h"
#include"../../Managers/IStreamObserver.h"
#include <deque>
namespace libdash
{
namespace framework
{
namespace input
{
class MediaObject;
}
namespace buffer
{
class MediaObjectBuffer
{
private:
enum NotificationType
{
GettingFront,
PushingBack,
ClearBuffer
};
public:
MediaObjectBuffer (sampleplayer::managers::StreamType type, uint32_t maxcapacity);
virtual ~MediaObjectBuffer ();
bool PushBack (input::MediaObject *media);
input::MediaObject* Front ();
input::MediaObject* GetFront ();
input::MediaObject* ShouldAbort ();
void PopFront ();
void ClearTail ();
void Clear ();
void SetEOS (bool value);
uint32_t Length ();
uint32_t Capacity ();
void AttachObserver (IMediaObjectBufferObserver *observer);
void Notify (enum NotificationType type, input::MediaObject* mediaObject);
uint32_t maxcapacity;
std::deque<input::MediaObject *> mediaobjects;
private:
std::vector<IMediaObjectBufferObserver *> observer;
bool eos;
sampleplayer::managers::StreamType type;
mutable CRITICAL_SECTION monitorMutex;
mutable CONDITION_VARIABLE full;
mutable CONDITION_VARIABLE empty;
};
}
}
}
#endif /* LIBDASH_FRAMEWORK_BUFFER_MEDIAOBJECTBUFFER_H_ */
| 2,883 | 36.947368 | 128 | h |
Subsets and Splits