|
|
#include "kernelModuleEmbedVideo.h"
#define LOG(X) kernelModule::m_pLog->Log("MOD_EVIDEO", this, X)
#ifdef DEBUG
#define LOG_ERROR(X) \
{ \ char _tBfrErrMSG2w34[2048]; \ sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \ kernelModule::m_pLog->Log("MOD_EVIDEO", this, _LOG_ERROR, _tBfrErrMSG2w34); \ }#else
#define LOG_ERROR(X) kernelModule::m_pLog->Log("MOD_EVIDEO", this, _LOG_ERROR, X);
#endif
#ifndef LRF_PROXY_ONLY
// #include "rgooseHardwareResourceNetworkProvider.h"
// #include "mojoKernel.h"
#include "../alg/generic/base64.h"
#include "../data/media/video/videoAVLIBSource.h"
#include "../data/media/video/videoLive555AVLibSource.h"
#include <arpa/inet.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <getopt.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <openssl/sha.h>
#include <paths.h>
#include <poll.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h> /* MIN() */
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
// #define DEBUG
// #undef DEBUG_EXTRA
// #define DEBUG_EXTRA
const char * m_pVideoScratchPath = VIDEO_SCRATCHPAD_PATH;
#ifndef STORAGE_DIR_MODE
#define STORAGE_DIR_MODE 0x1FF
#endif
#ifndef STORAGE_FILE_MODE
#define STORAGE_FILE_MODE 0x1B6
#endif
#define TLOG(X) basicLogCollection::getInstance()->Log("MOD_EVIDEO_T", CTX, X)
#ifdef DEBUG
#define TLOG_ERROR(X) \
{ \ char _tBfrErrMSG2w34[2048]; \ sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \ basicLogCollection::getInstance()->Log("MOD_EVIDEO_T", CTX, _LOG_ERROR, _tBfrErrMSG2w34); \ }#else
#define TLOG_ERROR(X) basicLogCollection::getInstance()->Log("MOD_EVIDEO_T", CTX, _LOG_ERROR, X);
#endif
enum{ WEBRTC_REQ_SIGNIN = 0, WEBRTC_REQ_WAIT = 1, WEBRTC_REQ_SIGNOUT = 2, WEBRTC_REQ_MESSAGE = 3};
//static const char * kRequestPaths[] = {"/stream", "/sign_in", "/wait", "/sign_out", "/message"};
// buffer_data bd[1]={0};
kernelModuleEmbedVideo::kernelModuleEmbedVideo(uint32_t moduleID) : kernelModule(moduleID, KERNEL_MODULE_EMBED_VIDEO), basicDualThread(){ m_pEventHeap = basicEventHeap::getInstance(); if (m_pDBC) { DBC_MODULE_EMBED_VIDEO_DATA * tDATA = m_pDBC->getEmbedVideoData(m_nDBAUXID); if (tDATA) { memcpy(&m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); free(tDATA); } else { LOG_ERROR("No DB Data Error!"); memset(&m_sEmbedVideoData, 0, sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); m_sEmbedVideoData.port = 8972; }; } else { LOG_ERROR("DB Error!"); }; m_bDetached = true; n_pNoSignalData = NULL; m_nNoSignalSize = 0;#ifdef HAVE_SMAL_PREVIEW_STREAMS
n_pNoSignalSmallData = NULL; m_nNoSignalSmallSize = 0;#endif
char tBuff[1024]; sprintf(m_pBaseSavePath, "%s/data/reports", getcwd(tBuff, 1024));#ifdef DEBUG
char tB[64]; sprintf(tB, "Web Streams Port: %d", m_sEmbedVideoData.port); LOG(tB); sprintf(tB, "Frame: [%dx%d]", m_sEmbedVideoData.width, m_sEmbedVideoData.height); LOG(tB); if (m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES) { LOG("Output Pictures"); } if ((m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO) == EVE_OUTPUT_VIDEO) { LOG("Output Video"); } if (m_sEmbedVideoData.show_ts) { LOG("Show TimeStamp"); } if (m_sEmbedVideoData.show_label) { LOG("Show Label"); } if (m_sEmbedVideoData.show_logo) { LOG("Show Logo"); }#endif
if (m_sEmbedVideoData.show_logo) { LOG(m_sEmbedVideoData.logo_md5); char tPath[MAX_PATH]; sprintf(tPath, "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5); if (! fileExist(tPath)) { LOG_ERROR("Logo File Missed!"); m_sEmbedVideoData.show_logo = false; }#ifdef DEBUG
else { LOG("Logo File is OK"); }#endif
; }; if (! fileExist(DB_SHMEM_POINT)) { mkdir(DB_SHMEM_POINT, 0775); // S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH );
chmod(DB_SHMEM_POINT, 0775); mkdir(m_pVideoScratchPath, 0775); chmod(m_pVideoScratchPath, 0775); } else { if (! fileExist((CSTR) m_pVideoScratchPath)) { mkdir(m_pVideoScratchPath, 0775); chmod(m_pVideoScratchPath, 0775); } else { // Clean Video Scratch
char tCMD[MAX_PATH]; sprintf(tCMD, "rm -r -f -d %s/* ", m_pVideoScratchPath); system(tCMD); }; };}
kernelModuleEmbedVideo::~kernelModuleEmbedVideo(){#ifdef DEBUG
LOG("Destructor");#endif
if (! m_bDetached) { stopService(true); }; // Sanity check
LOG("Sanity check in Destructor!");
waitThreadAEnd(true); if (m_vHandlersPool.size()) { // Kill-Wait Started Probes
#ifdef DEBUG
char tB[200]; sprintf(tB, "Have to Wait Client Handlers[%lu]!", m_vHandlersPool.size()); LOG(tB);
#endif
for (vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++) { pthread_cancel((*index)->m_hThreadHandle); } m_vHandlersPool.clear(); };#ifdef DEBUG
LOG("No More Clients Left");#endif
waitThreadBEnd(true); if (m_vViewHandlersPool.size()) { // Kill-Wait Started Viewers
#ifdef DEBUG
char tB[200]; sprintf(tB, "Have to Wait View Handlers[%lu]!", m_vViewHandlersPool.size()); LOG(tB);
#endif
for (vectorHANDLERS::iterator index = m_vViewHandlersPool.begin(); index < m_vViewHandlersPool.end(); index++) { pthread_cancel((*index)->m_hThreadHandle); } m_vViewHandlersPool.clear(); };#ifdef DEBUG_EXTRA
LOG("No More Viewers Left");#endif
#ifdef DEBUG_EXTRA
LOG("Deleting CAPS");#endif
if (m_mapCAPTURES.size()) { m_mapCAPTURES.clear(); }#ifdef DEBUG_EXTRA
LOG("Deleting MATS");#endif
if (m_mapMATS.size()) { m_mapMATS.clear(); }#ifdef DEBUG_EXTRA
LOG("Deleting No Signal");#endif
if (n_pNoSignalData) { free(n_pNoSignalData); }#ifdef HAVE_SMAL_PREVIEW_STREAMS
if (n_pNoSignalSmallData) { free(n_pNoSignalSmallData); }#endif
if (fileExist((CSTR) m_pVideoScratchPath)) { // Clean Video Scratch
char tCMD[MAX_PATH]; sprintf(tCMD, "rm -r -f -d %s/* ", m_pVideoScratchPath); system(tCMD); };#ifdef DEBUG_EXTRA
LOG("All Done!");#endif
}
static const char * ht_head = "HTTP/1.1 200 OK\r\n" "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n" "Pragma: no-cache\r\n" "Expires: 0\r\n" "MIME-version: 1.0\r\n" "Connection: close\r\n" //"Keep-Alive: timeout=5, max=1\r\n"
//"Connection: Keep-Alive\r\n"
//"Content-Type: video/mp4\r\n"
"Content-Transfer-Encoding: BINARY\r\n" //"Transfer-Encoding: chunked\r\n"
"Content-type: multipart/x-mixed-replace;boundary=MPFrame\r\n" "\r\n";static const char * ht_abort = "HTTP/1.1 404 OK\r\n" "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n" "Pragma: no-cache\r\n" "Expires: 0\r\n" "Connection: close\r\n\r\n";static const char * ht_no_signal = "HTTP/1.1 200 OK\r\n" "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n" "Pragma: no-cache\r\n" "Expires: 0\r\n" "MIME-version: 1.0\r\n" "Connection: close\r\n" "Content-Transfer-Encoding: BINARY\r\n" //"Content-type: multipart/x-mixed-replace;boundary=MPFrame\r\n\r\n"
"Content-Type: image/jpeg\r\nContent-length: %d\r\n\r\n";
void signal_pipe_handler(int SIG){ // Web Client Disconnected!
if ( SIG ) SIG = SIG;#ifdef DEBUG_EXTRA
basicLogCollection::getInstance()->Log("SIG_PIPE", NULL, _LOG_ERROR, "Sig Pipe Received Web Client Disconnected!");#endif
}
uint8_t kernelModuleEmbedVideo::getMediaMode(void){ return m_sEmbedVideoData.output_mode;}
void * kernelModuleEmbedVideo::webClientProc(void * ptr){
WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr; //kernelModuleEmbedVideo * MODULE = CTX->ModulePtr;
uint32_t msgSize; uint8_t tBuf[FILESTREAMBUFFERSZ]; //int retVal;
bool w = true;#ifdef DEBUG_EXTRA
TLOG("Start WebClient");#endif
pthread_setname_np(pthread_self(), "LiveVideoCL"); if (CTX) { char mesg[1024]; //size_t RecvSize;
struct pollfd pfd[1]; char cGetURI[1024]; //bool m_bDeflatePerMessage = false;
//bool m_pInit;
#ifdef DEBUG_EXTRA
pid_t pid = gettid(); char pidBuf[16]; sprintf(pidBuf, "pid:%d", pid); TLOG(pidBuf);#endif
signal(SIGPIPE, signal_pipe_handler);
pfd->fd = CTX->m_iSocketFID; pfd->events = POLLIN | POLLHUP;
while (CTX->bValid && w) { if (! CTX->initDone) { int RetVal; char * reqline[256]; RetVal = poll(pfd, 1, 1000); if (RetVal <= 0) { if (EINTR == errno) { continue; } TLOG_ERROR("Unrecoverable error"); w = false; continue; }; memset(mesg, 0, sizeof(mesg));
RetVal = recv(CTX->m_iSocketFID, mesg, sizeof(mesg), 0);
if (RetVal <= 0) { sprintf(mesg, "web recv() error: %s", strerror(errno)); TLOG_ERROR(mesg); w = false; continue; };#ifdef DEBUG_EXTRA
TLOG(mesg);#endif
uint32_t index = 0; reqline[index] = strtok(mesg, "\n"); if (strncmp(reqline[index], "GET", 3) == 0) { char * pPartURI; char * pPartPROTO; pPartURI = strstr(reqline[index], " "); if (pPartURI != NULL) { pPartURI++; pPartPROTO = strstr(pPartURI, " "); pPartPROTO++; int URILen = pPartPROTO - pPartURI; strncpy(cGetURI, pPartURI, URILen); cGetURI[URILen] = (char) 0; if (strncmp(pPartPROTO, "HTTP/1.0", 8) != 0 && strncmp(pPartPROTO, "HTTP/1.1", 8) != 0) { TLOG_ERROR("No HTTP version supplied in request!"); if (write(CTX->m_iSocketFID, "HTTP/1.1 400 Bad Request\r\n", 26) < 0) { sprintf(mesg, "Failed returning status 400 to client: %s", strerror(errno)); TLOG_ERROR(mesg); }; w = false; continue; }; };#ifdef DEBUG_EXTRA
TLOG("Req URI"); TLOG(cGetURI);#endif
}; // if( ( strncmp( cGetURI, "/stream", 7 ) == 0 ) || ( strncmp( cGetURI, "/video_feed", 11 ) == 0 ) ) {
if (strncmp(cGetURI, "/video_feed", 11) == 0) { uint32_t tStreamID = 0; CSTR tP;#ifdef HAVE_SMAL_PREVIEW_STREAMS
if ((tP = strstr(cGetURI, "/preview"))) { CTX->bPreviewMode = true; }#endif
if ((tP = strstr(cGetURI, "?"))) { CSTR tB; tP++; if ((tB = strstr(tP, "id="))) { tStreamID = atoi(tB + 3); }; }; if (tStreamID) {#ifdef DEBUG_EXTRA
char tB[64]; sprintf(tB, "StremID: %d", tStreamID); TLOG(tB);#endif
if (CTX->ModulePtr->registerForMediaStream(tStreamID, CTX)) { // Send Header
if (send(CTX->m_iSocketFID, ht_head, strlen(ht_head), 0) < 0) {#ifdef DEBUG_EXTRA
sprintf(mesg, "Failed sending file to client: %s", strerror(errno)); TLOG_ERROR(mesg);#endif
w = false; }; CTX->initDone = true; continue;#ifdef DEBUG_EXTRA
} else { TLOG("Stream id Not Online");#endif
};#ifdef DEBUG_EXTRA
} else { TLOG("No Stream ID");#endif
}; }; if (CTX->ModulePtr->n_pNoSignalData) { // Send Dummy Picture
#ifdef HAVE_SMAL_PREVIEW_STREAMS
if (CTX->bPreviewMode) { sprintf(mesg, ht_no_signal, CTX->ModulePtr->m_nNoSignalSmallSize); send(CTX->m_iSocketFID, mesg, strlen(mesg), 0); send(CTX->m_iSocketFID, CTX->ModulePtr->n_pNoSignalSmallData, CTX->ModulePtr->m_nNoSignalSmallSize, 0); send(CTX->m_iSocketFID, "\r\n\r\n", 4, 0); } else {#endif
sprintf(mesg, ht_no_signal, CTX->ModulePtr->m_nNoSignalSize); send(CTX->m_iSocketFID, mesg, strlen(mesg), 0); send(CTX->m_iSocketFID, CTX->ModulePtr->n_pNoSignalData, CTX->ModulePtr->m_nNoSignalSize, 0); send(CTX->m_iSocketFID, "\r\n\r\n", 4, 0);#ifdef HAVE_SMAL_PREVIEW_STREAMS
};#endif
#ifdef DEBUG_EXTRA
TLOG("VFEED Sent No Signal Image!");#endif
} else { // Send 404 Header
send(CTX->m_iSocketFID, ht_abort, strlen(ht_abort), 0);#ifdef DEBUG_EXTRA
TLOG("Aborted!");#endif
}; w = false; continue; } else { /*
retVal = read( CTX->m_iEncoderPipe[0], &msgSize, sizeof(uint32_t)); if( retVal == -1 ){ if( errno == EAGAIN || errno == EWOULDBLOCK ){ continue; }; TLOG_ERROR("Pipe Communication Error[1]!"); CTX->bValid = false; continue; }; if( msgSize < FILESTREAMBUFFERSZ ) { retVal = read( CTX->m_iEncoderPipe[0], tBuf, msgSize ); } else { TLOG_ERROR("Data too Big in Pipe Transfer!"); CTX->bValid = false; continue; }; if( retVal == -1 ){ //free( tBuf );
if( errno == EAGAIN || errno == EWOULDBLOCK ){ continue; }; TLOG_ERROR("Pipe Communication Error[2]!"); CTX->bValid = false; continue; }; */ /**************/ CTX->ModulePtr->m_mEncodedProtector.lock();#ifdef HAVE_SMAL_PREVIEW_STREAMS
if (CTX->bPreviewMode) { if (CTX->ModulePtr->m_mapPREVIEWS[CTX->mediaStreamId].size()) { msgSize = CTX->ModulePtr->m_mapPREVIEWS[CTX->mediaStreamId].size(); if (msgSize < FILESTREAMBUFFERSZ) { memcpy(tBuf, CTX->ModulePtr->m_mapPREVIEWS[CTX->mediaStreamId].data(), msgSize); CTX->ModulePtr->m_mEncodedProtector.unlock(); } else { CTX->ModulePtr->m_mEncodedProtector.unlock(); TLOG_ERROR("Data too Big in Pipe Transfer!"); w = false; continue; }; } else { CTX->ModulePtr->m_mEncodedProtector.unlock(); if (CTX->ModulePtr->n_pNoSignalSmallData) { msgSize = CTX->ModulePtr->m_nNoSignalSmallSize; memcpy(tBuf, CTX->ModulePtr->n_pNoSignalSmallData, msgSize); } else { TLOG_ERROR("Data too Big in Pipe Transfer!"); w = false; continue; }; }; } else {#endif
if (CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].size()) { msgSize = CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].size(); if (msgSize < FILESTREAMBUFFERSZ) { memcpy(tBuf, CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].data(), msgSize); CTX->ModulePtr->m_mEncodedProtector.unlock(); } else { CTX->ModulePtr->m_mEncodedProtector.unlock(); TLOG_ERROR("Data too Big in Pipe Transfer!"); w = false; continue; }; } else {
#ifdef DEBUG_EXTRA
TLOG("VFEED Sent No Signal Image!");#endif
CTX->ModulePtr->m_mEncodedProtector.unlock(); if (CTX->ModulePtr->n_pNoSignalData) { msgSize = CTX->ModulePtr->m_nNoSignalSize; memcpy(tBuf, CTX->ModulePtr->n_pNoSignalData, msgSize); } else { TLOG_ERROR("Data too Big in Pipe Transfer!"); w = false; continue; }; };#ifdef HAVE_SMAL_PREVIEW_STREAMS
};#endif
/*********/ sprintf(mesg, "--MPFrame\r\nContent-type: image/jpeg\r\nContent-length: %d\r\n\r\n", msgSize); if (send(CTX->m_iSocketFID, mesg, strlen(mesg), 0) < 0) {#ifdef DEBUG_EXTRA
sprintf(mesg, "[1]Failed sending file to client: %s", strerror(errno)); TLOG_ERROR(mesg);#endif
w = false; continue; }; if (send(CTX->m_iSocketFID, tBuf, msgSize, 0) < 0) {#ifdef DEBUG_EXTRA
sprintf(mesg, "[2]Failed sending file to client: %s", strerror(errno)); TLOG_ERROR(mesg);#endif
w = false; continue; }; if (send(CTX->m_iSocketFID, "\r\n\r\n", 4, 0) < 0) {#ifdef DEBUG_EXTRA
sprintf(mesg, "[3]Failed sending file to client: %s", strerror(errno)); TLOG_ERROR(mesg);#endif
w = false; continue; }; usleep(66666); }; }; }; close(CTX->m_iEncoderPipe[0]); shutdown(CTX->m_iSocketFID, SHUT_RDWR); SLEEP(3); close(CTX->m_iSocketFID); CTX->bValid = false;#ifdef DEBUG_EXTRA
TLOG("WEB Client Handler Ended!");#endif
pthread_exit(NULL); return NULL;}
void * kernelModuleEmbedVideo::viewClientProc(void * ptr){
WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr; //kernelModuleEmbedVideo * MODULE = CTX->ModulePtr;
//uint32_t tVideoID = 0;
long int tDTS = 0; uint32_t tETS = 0; uint32_t msgSize; uint8_t tBuf[FILESTREAMBUFFERSZ]; uint8_t rBuf[8192]; int rSIZE; int cSIZE; //int retVal;
bool w = true; char tBASE[11] = {0}; char tID[33] = {0}; char tFILE[PATH_MAX];
uint32_t cFRAME = 0; void * sPtr = NULL; void * ePtr = NULL; uint8_t baba[2] = {0xff, 0xd8}; uint8_t yaba[2] = {0xff, 0xd9}; FILE * tFID = NULL; TLOG("Start ViewClient"); pthread_setname_np(pthread_self(), "ReportVideoCL"); if (CTX) { char mesg[1024]; //size_t RecvSize;
struct pollfd pfd[1]; char cGetURI[1024]; //bool m_bDeflatePerMessage = false;
//bool m_pInit;
#ifdef DEBUG_EXTRA
pid_t pid = gettid(); char pidBuf[16]; sprintf(pidBuf, "pid:%d", pid); TLOG(pidBuf);#endif
signal(SIGPIPE, signal_pipe_handler);
pfd->fd = CTX->m_iSocketFID; pfd->events = POLLIN | POLLHUP;
while (CTX->bValid && w) { if (! CTX->initDone) { int RetVal; char * reqline[256]; RetVal = poll(pfd, 1, 1000); if (RetVal <= 0) { if (EINTR == errno) { continue; } TLOG_ERROR("Unrecoverable error"); w = false; continue; }; memset(mesg, 0, sizeof(mesg));
RetVal = recv(CTX->m_iSocketFID, mesg, sizeof(mesg), 0);
if (RetVal <= 0) { sprintf(mesg, "web recv() error: %s", strerror(errno)); TLOG_ERROR(mesg); w = false; continue; };#ifdef DEBUG_EXTRA
TLOG(mesg);#endif
uint32_t index = 0; reqline[index] = strtok(mesg, "\n"); if (strncmp(reqline[index], "GET", 3) == 0) { char * pPartURI; char * pPartPROTO; pPartURI = strstr(reqline[index], " "); if (pPartURI != NULL) { pPartURI++; pPartPROTO = strstr(pPartURI, " "); pPartPROTO++; int URILen = pPartPROTO - pPartURI; strncpy(cGetURI, pPartURI, URILen); cGetURI[URILen] = (char) 0; if (strncmp(pPartPROTO, "HTTP/1.0", 8) != 0 && strncmp(pPartPROTO, "HTTP/1.1", 8) != 0) { TLOG_ERROR("No HTTP version supplied in request!"); if (write(CTX->m_iSocketFID, "HTTP/1.1 400 Bad Request\r\n", 26) < 0) { sprintf(mesg, "Failed returning status 400 to client: %s", strerror(errno)); TLOG_ERROR(mesg); }; w = false; continue; }; };#ifdef DEBUG_EXTRA
TLOG("Req URI"); TLOG(cGetURI);#endif
};
if ((strncmp(cGetURI, "/stream", 7) == 0) || (strncmp(cGetURI, "/video_view", 11) == 0)) { CSTR tP; if ((tP = strstr(cGetURI, "?"))) { CSTR tB; tP++; if ((tB = strcasestr(tP, "id="))) { strncpy(tID, tB + 3, 32); tID[32] = (char) 0; }; if ((tB = strcasestr(tP, "ts="))) { tDTS = atol(tB + 3); // struct tm * ptm = gmtime ( &tDTS );
struct tm * ptm = localtime(&tDTS); if (ptm) { sprintf(tBASE, "%04d/%02d/%02d", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday); }; }; if ((tB = strcasestr(tP, "sf="))) { tETS = atoi(tB + 3); }; sprintf(tFILE, "./data/reports/%s/%s.mjpeg", tBASE, tID); };#ifdef DEBUG_EXTRA
char tB[64]; sprintf(tB, "Requested Video: %s", tFILE); TLOG(tB);#endif
if (fileExist(tFILE)) { tFID = fopen(tFILE, "r"); if (tFID) { // Send Header
if (send(CTX->m_iSocketFID, ht_head, strlen(ht_head), 0) < 0) {#ifdef DEBUG
sprintf(mesg, "Failed sending file to client: %s", strerror(errno)); TLOG_ERROR(mesg);#endif
w = false; }; CTX->initDone = true; continue;#ifdef DEBUG
} else { TLOG("Stream id Not Online");#endif
}; } else { TLOG_ERROR("VVIEW File Not Exists!"); }; };#ifdef DEBUG_EXTRA
TLOG("VVIEW Catched in DeadEnd!");#endif
if (1) { // Send Dummy Picture
sprintf(mesg, ht_no_signal, CTX->ModulePtr->m_nNoSignalSize); send(CTX->m_iSocketFID, mesg, strlen(mesg), 0); send(CTX->m_iSocketFID, CTX->ModulePtr->n_pNoSignalData, CTX->ModulePtr->m_nNoSignalSize, 0); send(CTX->m_iSocketFID, "\r\n\r\n", 4, 0);#ifdef DEBUG_EXTRA
TLOG("VVIEW Sent No Signal Image!");#endif
} else { // Send 404 Header
send(CTX->m_iSocketFID, ht_abort, strlen(ht_abort), 0);#ifdef DEBUG_EXTRA
TLOG("Aborted!");#endif
}; w = false; continue; } else { cSIZE = 0; while (! feof(tFID) && CTX->bValid && w) { rSIZE = fread(rBuf, 1, 8192, tFID); if (rSIZE > 0) { memcpy(tBuf + cSIZE, rBuf, rSIZE); cSIZE += rSIZE; if (sPtr == NULL) { sPtr = memmem(tBuf, cSIZE, baba, 2); } if (sPtr) { if (sPtr != tBuf) { cSIZE -= ((uint64_t) sPtr - (uint64_t) tBuf); memcpy(tBuf, sPtr, cSIZE); sPtr = tBuf; }; if (ePtr == NULL) { ePtr = memmem(sPtr, cSIZE, yaba, 2); } }; }; if (sPtr != NULL && ePtr != NULL) { if (feof(tFID)) { TLOG("LAST FRAME"); } cFRAME++; ePtr =(void *)(((uint64_t)ePtr) + 2); msgSize = ((uint64_t) ePtr - (uint64_t) sPtr); if (cFRAME > tETS || feof(tFID)) { // or last chanse to send data
if (feof(tFID)) { TLOG("SEND HEADER"); } sprintf(mesg, "--MPFrame\r\nContent-type: image/jpeg\r\nContent-length: %d\r\n\r\n", msgSize); if (send(CTX->m_iSocketFID, mesg, strlen(mesg), 0) < 0) {#ifdef DEBUG
sprintf(mesg, "[1]Failed sending file to client: %s", strerror(errno)); TLOG_ERROR(mesg);#endif
w = false; continue; }; if (feof(tFID)) { TLOG("SEND BODY"); } if (send(CTX->m_iSocketFID, tBuf, msgSize, 0) < 0) {#ifdef DEBUG
sprintf(mesg, "[2]Failed sending file to client: %s", strerror(errno)); TLOG_ERROR(mesg);#endif
w = false; continue; }; if (feof(tFID)) { TLOG("SEND TAIL"); } if (send(CTX->m_iSocketFID, "\r\n\r\n", 4, 0) < 0) {#ifdef DEBUG
sprintf(mesg, "[3]Failed sending file to client: %s", strerror(errno)); TLOG_ERROR(mesg);#endif
w = false; continue; }; SLEEP(66); }; if (! feof(tFID)) { cSIZE -= msgSize; memcpy(tBuf, ePtr, cSIZE); sPtr = ePtr = NULL; }#ifdef DEBUG
else { TLOG("File is Finished!"); }#endif
};#ifdef DEBUG
if (feof(tFID)) { TLOG("LAST FRAME SENT"); }#endif
};#ifdef DEBUG_EXTRA
TLOG("Close File");#endif
fclose(tFID); w = false; }; }; };#ifdef DEBUG_EXTRA
TLOG("Shut Down Socket");#endif
shutdown(CTX->m_iSocketFID, SHUT_RDWR);#ifdef DEBUG_EXTRA
TLOG("Close Socket");#endif
close(CTX->m_iSocketFID); CTX->bValid = false;#ifdef DEBUG_EXTRA
TLOG("View Client Handler Ended!");#endif
pthread_exit(NULL); TLOG("After Pthread Exit"); return NULL;}
// Start Thread To view Live Streams
void kernelModuleEmbedVideo::m_fThreadAProc(void){ if (! m_bEnabled) {#ifdef DEBUG_EXTRA
LOG("Module is Disabled!");#endif
return; };#ifdef DEBUG_EXTRA
LOG("[LIVE] Module Started!");#endif
pthread_setname_np(pthread_self(), "Live Video Stream"); struct pollfd pfd[1]; pfd->fd = m_nSocketDescriptor; pfd->events = POLLIN | POLLHUP; m_bThreadAStatus = TH_WORKING; while (m_bThreadAStatus < TH_ENDED) { if (! m_bEnabled) { m_bThreadAStatus = TH_ENDED; continue; }; int RetVal = poll(pfd, 1, 1000); if (RetVal < 0) { if (EINTR == errno) { continue; } LOG_ERROR("Unrecoverable error"); m_bThreadAStatus = TH_ENDED; continue; }; // Handle Connections
if (RetVal != 0) { if (pfd[0].revents & POLLIN) {#ifdef DEBUG_EXTRA
LOG("Handle New Client");#endif
int tSID = accept(pfd[0].fd, NULL, NULL); if (tSID < 0) { char tBuf[CTEXT]; sprintf(tBuf, "Accept() error: %s", strerror(errno)); LOG_ERROR(tBuf); } else {#ifdef DEBUG_EXTRA
LOG("Accept OK");#endif
WEB_CLIENT_CTX * tCTX = (WEB_CLIENT_CTX *) malloc(sizeof(WEB_CLIENT_CTX)); if (tCTX) {#ifdef DEBUG_EXTRA
LOG("CTX OK");#endif
WEB_HANDLER * tHANDLER = (WEB_HANDLER *) malloc(sizeof(WEB_HANDLER)); if (tHANDLER) {#ifdef DEBUG_EXTRA
LOG("HANDLER OK");#endif
memset(tCTX, 0, sizeof(WEB_CLIENT_CTX)); memset(tHANDLER, 0, sizeof(WEB_HANDLER)); tCTX->m_iSocketFID = tSID; tCTX->m_iEncoderPipe[0] = -1; tCTX->m_iEncoderPipe[1] = -1; tCTX->mediaStreamId = 0; tCTX->bValid = true; tCTX->ModulePtr = this;#ifdef DEBUG_EXTRA
LOG("Before Thread Create");#endif
int RetVal = pthread_create(&tHANDLER->m_hThreadHandle, NULL, webClientProc, (void *) tCTX); if (RetVal == -1) { free(tCTX); free(tHANDLER); LOG_ERROR("Thread Creation Faled."); shutdown(tSID, SHUT_RDWR); close(tSID); } else { tHANDLER->CTX = tCTX; m_mWebHandlersProtector.lock(); m_vHandlersPool.push_back(tHANDLER); m_mWebHandlersProtector.unlock();#ifdef DEBUG_EXTRA
LOG("Handler Pushed to a Pool");#endif
}; } else { // https://stackoverflow.com/questions/18545077/image-fullscreen-on-click
free(tCTX); LOG_ERROR("CL_HANDLER Mem Allocation Failure!"); shutdown(tSID, SHUT_RDWR); close(tSID); }; } else { LOG_ERROR("CL_CTX Mem Allocation Failure!"); shutdown(tSID, SHUT_RDWR); close(tSID); }; }; }; }; // Handle Dead Clients
m_mWebHandlersProtector.lock(); if (m_vHandlersPool.size()) { for (vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx != m_vHandlersPool.end();) { if (! ((*idx)->CTX->bValid)) {#ifdef DEBUG_EXTRA
LOG("Have Dead Client!");#endif
pthread_join((*idx)->m_hThreadHandle, NULL); // close( (*idx)->CTX->m_iEncoderPipe[0] );
close((*idx)->CTX->m_iEncoderPipe[1]); free((*idx)->CTX); free(*idx); m_vHandlersPool.erase(idx);#ifdef DEBUG_EXTRA
LOG("Web Handler Ripped!");#endif
} else { idx++; } }; }; m_mWebHandlersProtector.unlock(); // validate active streams ?
SLEEP(50); };}
void kernelModuleEmbedVideo::m_fThreadBProc(void){ if (! m_bEnabled) {#ifdef DEBUG_EXTRA
LOG("Module is Disabled!");#endif
return; };#ifdef DEBUG_EXTRA
LOG("[VIEW] Module Started!");#endif
struct pollfd pfd[1]; pfd->fd = m_nViewSocketDescriptor; pfd->events = POLLIN | POLLHUP; m_bThreadBStatus = TH_WORKING; pthread_setname_np(pthread_self(), "Report Video View"); while (m_bThreadBStatus < TH_ENDED) { if (! m_bEnabled) { m_bThreadBStatus = TH_ENDED; continue; }; int RetVal = poll(pfd, 1, 1000); if (RetVal < 0) { if (EINTR == errno) { continue; } LOG_ERROR("Unrecoverable error"); m_bThreadBStatus = TH_ENDED; continue; }; // Handle Connections
if (RetVal != 0) { if (pfd[0].revents & POLLIN) {#ifdef DEBUG_EXTRA
LOG("Handle New View");#endif
int tSID = accept(pfd[0].fd, NULL, NULL); if (tSID < 0) { char tBuf[CTEXT]; sprintf(tBuf, "Accept() error: %s", strerror(errno)); LOG_ERROR(tBuf); } else {#ifdef DEBUG_EXTRA
LOG("Accept OK");#endif
WEB_CLIENT_CTX * tCTX = (WEB_CLIENT_CTX *) malloc(sizeof(WEB_CLIENT_CTX)); if (tCTX) {#ifdef DEBUG_EXTRA
LOG("CTX OK");#endif
WEB_HANDLER * tHANDLER = (WEB_HANDLER *) malloc(sizeof(WEB_HANDLER)); if (tHANDLER) {#ifdef DEBUG_EXTRA
LOG("HANDLER OK");#endif
memset(tCTX, 0, sizeof(WEB_CLIENT_CTX)); memset(tHANDLER, 0, sizeof(WEB_HANDLER)); tCTX->m_iSocketFID = tSID; tCTX->m_iEncoderPipe[0] = -1; tCTX->m_iEncoderPipe[1] = -1; tCTX->mediaStreamId = 0; tCTX->bValid = true; tCTX->ModulePtr = this;#ifdef DEBUG_EXTRA
LOG("Before Thread Create");#endif
int RetVal = pthread_create(&tHANDLER->m_hThreadHandle, NULL, viewClientProc, (void *) tCTX); if (RetVal == -1) { free(tCTX); free(tHANDLER); LOG_ERROR("Thread Creation Faled."); shutdown(tSID, SHUT_RDWR); close(tSID); } else { tHANDLER->CTX = tCTX; m_mViewHandlersProtector.lock(); m_vViewHandlersPool.push_back(tHANDLER); m_mViewHandlersProtector.unlock();#ifdef DEBUG_EXTRA
LOG("Handler Pushed to a Pool");#endif
}; } else { // https://stackoverflow.com/questions/18545077/image-fullscreen-on-click
free(tCTX); LOG_ERROR("CL_HANDLER Mem Allocation Failure!"); shutdown(tSID, SHUT_RDWR); close(tSID); }; } else { LOG_ERROR("CL_CTX Mem Allocation Failure!"); shutdown(tSID, SHUT_RDWR); close(tSID); }; }; }; }; // Handle Dead Clients
m_mViewHandlersProtector.lock(); if (m_vViewHandlersPool.size()) { for (vectorHANDLERS::iterator idx = m_vViewHandlersPool.begin(); idx != m_vViewHandlersPool.end();) { if (! ((*idx)->CTX->bValid)) {#ifdef DEBUG_EXTRA
LOG("Have Dead Viewer!");#endif
pthread_join((*idx)->m_hThreadHandle, NULL); free((*idx)->CTX); free(*idx); m_vViewHandlersPool.erase(idx);#ifdef DEBUG_EXTRA
LOG("View Handler Ripped!");#endif
} else { idx++; } }; }; m_mViewHandlersProtector.unlock(); // validate active streams ?
SLEEP(50); };}
#define ENABLE_SOCKOPT(sd, level, opt) \
do \ { \ int val = 1; \ if (setsockopt(sd, level, opt, &val, sizeof(val)) < 0) \ warn("Failed enabling %s for web service", #opt); \ } \ while (0);
bool kernelModuleEmbedVideo::startService(){ m_bDetached = false; // Create NoSignal Image
cv::Mat tMat(m_sEmbedVideoData.height, m_sEmbedVideoData.width, CV_8UC3); cv::rectangle(tMat, cv::Point(0, 0), cv::Point(m_sEmbedVideoData.width, m_sEmbedVideoData.height), cv::Scalar(255, 0, 0), cv::FILLED); cv::putText(tMat, "NO SIGNAL", cv::Point(10, 30), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(0, 255, 255), 3); if (m_sEmbedVideoData.show_logo) { int a_x, a_y; if (m_sEmbedVideoData.logo_x < 0) { a_x = m_sEmbedVideoData.width + m_sEmbedVideoData.logo_x - m_sEmbedVideoData.logo_w; if (a_x < 0) { a_x = 0; } } else { a_x = m_sEmbedVideoData.logo_x; } if ((a_x + m_sEmbedVideoData.logo_w) > m_sEmbedVideoData.width) { a_x = m_sEmbedVideoData.width - m_sEmbedVideoData.logo_w; } if (m_sEmbedVideoData.logo_y < 0) { a_y = m_sEmbedVideoData.height + m_sEmbedVideoData.logo_y - m_sEmbedVideoData.logo_h; if (a_y < 0) { a_y = 0; } } else { a_y = m_sEmbedVideoData.logo_y; } if ((a_y + m_sEmbedVideoData.logo_h) > m_sEmbedVideoData.height) { a_y = m_sEmbedVideoData.height - m_sEmbedVideoData.logo_h; } if ((a_x > -1) && (a_y > -1)) { char tName[256]; m_sEmbedVideoData.logo_x = a_x; m_sEmbedVideoData.logo_y = a_y; sprintf(tName, "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5); cv::Mat T = cv::imread(tName, cv::IMREAD_UNCHANGED); if (T.cols > 0) { cv::Mat mask; vector<cv::Mat> layers;#ifdef DEBUG_EXTRA
LOG("Logo Loaded OK");#endif
cv::split(T, layers); // seperate channels
cv::Mat rgb[3] = {layers[0], layers[1], layers[2]}; mask = layers[3]; // png's alpha channel used as mask
cv::merge(rgb, 3, T); // put together the RGB channels, now transp insn't transparent
cv::resize(T, m_mLogoPic, cv::Size(m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h), cv::INTER_CUBIC); cv::resize(mask, m_mLogoMask, cv::Size(m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h), cv::INTER_CUBIC);
cv::Rect roi(cv::Point(m_sEmbedVideoData.logo_x, m_sEmbedVideoData.logo_y), cv::Size(m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h)); cv::Mat destinationROI = tMat(roi); m_mLogoPic.copyTo(destinationROI, m_mLogoMask); // m_sEmbedVideoData.show_logo = false;
} else {#ifdef DEBUG_EXTRA
LOG("Logo Disabled - No Picture is Loaded");#endif
m_sEmbedVideoData.show_logo = false; }; } else {#ifdef DEBUG_EXTRA
LOG("Logo Disabled - Wrong Coords");#endif
m_sEmbedVideoData.show_logo = false; };#ifdef DEBUG_EXTRA
LOG("Logo Draw OK");#endif
};
try { vector<int> compression_params; // compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
// compression_params.push_back(9);
compression_params.push_back(cv::IMWRITE_JPEG_QUALITY); compression_params.push_back(m_sEmbedVideoData.compression_quality); vector<uchar> buf; cv::imencode(".jpg", tMat, buf, compression_params); m_nNoSignalSize = buf.size(); n_pNoSignalData = (uint8_t *) malloc(m_nNoSignalSize); if (n_pNoSignalData) { memcpy(n_pNoSignalData, buf.data(), m_nNoSignalSize); } else { m_nNoSignalSize = 0; } buf.clear();#ifdef HAVE_SMAL_PREVIEW_STREAMS
// Make Small Preview Thumb
cv::Mat dst; cv::resize(tMat, dst, cv::Size(PREVIEW_SIZE_WIDTH, PREVIEW_SIZE_HEIGHT)); cv::imencode(".jpg", dst, buf, compression_params); m_nNoSignalSmallSize = buf.size(); n_pNoSignalSmallData = (uint8_t *) malloc(m_nNoSignalSmallSize); if (n_pNoSignalSmallData) { memcpy(n_pNoSignalSmallData, buf.data(), m_nNoSignalSmallSize); } else { m_nNoSignalSmallSize = 0; } buf.clear();#endif
} catch (cv::Exception & e) { LOG_ERROR(e.msg.c_str()); };
// Socket Live
struct sockaddr sa; struct sockaddr_in * sin; memset(&sa, 0, sizeof(struct sockaddr)); sa.sa_family = AF_INET; sin = (struct sockaddr_in *) &sa; sin->sin_addr.s_addr = htonl(INADDR_ANY); sin->sin_port = htons(m_sEmbedVideoData.port);
m_nSocketDescriptor = socket(sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0); if (m_nSocketDescriptor == -1) { LOG_ERROR("Failed creating ACC socket"); return false; }; ENABLE_SOCKOPT(m_nSocketDescriptor, SOL_SOCKET, SO_REUSEADDR);#ifdef SO_REUSEPORT
ENABLE_SOCKOPT(m_nSocketDescriptor, SOL_SOCKET, SO_REUSEPORT);#endif
if (bind(m_nSocketDescriptor, &sa, sizeof(sa)) < 0) { LOG_ERROR("Failed binding Socket"); close(m_nSocketDescriptor); return false;#ifdef DEBUG_EXTRA
} else { LOG("Bind Socessfull");#endif
}; if (listen(m_nSocketDescriptor, 10) != 0) { LOG_ERROR("Failed setting web listen backlog"); close(m_nSocketDescriptor); return false;#ifdef DEBUG_EXTRA
} else { LOG("Listen OK");#endif
};
// Socket Viewer
// struct sockaddr sa;
// struct sockaddr_in *sin;
memset(&sa, 0, sizeof(struct sockaddr)); sa.sa_family = AF_INET; sin = (struct sockaddr_in *) &sa; sin->sin_addr.s_addr = htonl(INADDR_ANY); sin->sin_port = htons(8974);
m_nViewSocketDescriptor = socket(sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0); if (m_nViewSocketDescriptor == -1) { LOG_ERROR("Failed creating ACC socket"); return false; }; ENABLE_SOCKOPT(m_nViewSocketDescriptor, SOL_SOCKET, SO_REUSEADDR);#ifdef SO_REUSEPORT
ENABLE_SOCKOPT(m_nViewSocketDescriptor, SOL_SOCKET, SO_REUSEPORT);#endif
if (bind(m_nViewSocketDescriptor, &sa, sizeof(sa)) < 0) { LOG_ERROR("Failed binding Socket"); close(m_nViewSocketDescriptor); return false;#ifdef DEBUG_EXTRA
} else { LOG("Bind Socessfull");#endif
}; if (listen(m_nViewSocketDescriptor, 10) != 0) { LOG_ERROR("Failed setting web listen backlog"); close(m_nViewSocketDescriptor); return false;#ifdef DEBUG_EXTRA
} else { LOG("Listen OK");#endif
};
#ifdef DEBUG_EXTRA
LOG("Start Thread");#endif
m_bEnabled = init(); return m_bEnabled;}
bool kernelModuleEmbedVideo::stopService(bool force){ m_bEnabled = false; // Stop Conveyor
m_bDetached = uninit();#ifdef DEBUG_EXTRA
LOG("StopService!");#endif
m_mStreamHandlersProtector.lock(); if (m_mapHANDLERS.size()) {#ifdef DEBUG
LOG("Deleting Stream Handlers!");#endif
for (mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++) {#ifdef DEBUG
LOG("Deleting Stream Handler");#endif
delete((*idx).second); } m_mapHANDLERS.clear(); }; m_mStreamHandlersProtector.unlock();
if (m_vHandlersPool.size()) { // Kill-Wait Started Probes
#ifdef DEBUG_EXTRA
char tB[200]; sprintf(tB, "Have to Wait Client Handlers[%d]!", m_vHandlersPool.size()); LOG(tB);
#endif
for (vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index != m_vHandlersPool.end(); index++) { if (force) {#ifdef DEBUG_EXTRA
LOG("Force Client Handler to Stop!");#endif
pthread_cancel((*index)->m_hThreadHandle); } else {#ifdef DEBUG_EXTRA
LOG("Waiting Client Handler to End!");#endif
pthread_join((*index)->m_hThreadHandle, NULL); } }; m_vHandlersPool.clear(); };#ifdef DEBUG_EXTRA
LOG("No More Client Handlers!");#endif
if (m_mapCAPTURES.size()) {#ifdef DEBUG_EXTRA
LOG("Some Caps!");#endif
for (mapSTREAMCAPS::iterator idx = m_mapCAPTURES.begin(); idx != m_mapCAPTURES.end(); idx++) { idx->second.clear(); } m_mapCAPTURES.clear();#ifdef DEBUG_EXTRA
LOG("No More Caps!");#endif
}; if (m_mapMATS.size()) {#ifdef DEBUG_EXTRA
LOG("Some Mats!");#endif
for (mapSTREAMMAPS::iterator idx = m_mapMATS.begin(); idx != m_mapMATS.end(); idx++) {#ifdef DEBUG_EXTRA
LOG("Release Mat!");#endif
idx->second.release(); };#ifdef DEBUG_EXTRA
LOG("Clear Map Mats!");#endif
m_mapMATS.clear();#ifdef DEBUG_EXTRA
LOG("No More Mats!");#endif
}; if (n_pNoSignalData) {#ifdef DEBUG_EXTRA
LOG("No Sig Data!");#endif
free(n_pNoSignalData); n_pNoSignalData = NULL; m_nNoSignalSize = 0;#ifdef DEBUG_EXTRA
LOG("No No Sig Data!");#endif
}; return m_bDetached;}
bool kernelModuleEmbedVideo::reloadSettings(){#ifdef DEBUG_EXTRA
LOG("Reload Service");#endif
if (m_pDBC) { DBC_MODULE_EMBED_VIDEO_DATA * tDATA = m_pDBC->getEmbedVideoData(m_nDBAUXID); if (tDATA) { if (stopService()) {#ifdef DEBUG_EXTRA
LOG("Stoped!");#endif
memcpy(&m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); free(tDATA);#ifdef DEBUG_EXTRA
LOG("Starting...");#endif
return startService(); } else { free(tDATA); }; }; }; return false;}
#include "deviceNodeCamera.h"
#include "deviceNodeFactory.h"
bool kernelModuleEmbedVideo::validate(){ bool RetVal = true; deviceNode ** tA = NULL; uint32_t tCNT = deviceNodeFactory::getInstance()->fetchNodes(ARGUS_ANALOG_STATIC_CAMERA, tA); if (! tCNT) { tCNT = deviceNodeFactory::getInstance()->fetchNodes(ARGUS_ANALOG_PTZ_CAMERA, tA); if (! tCNT) { tCNT = deviceNodeFactory::getInstance()->fetchNodes(ARGUS_IP_STATIC_CAMERA, tA); if (! tCNT) { tCNT = deviceNodeFactory::getInstance()->fetchNodes(ARGUS_IP_PTZ_CAMERA, tA); if (! tCNT) { tCNT = deviceNodeFactory::getInstance()->fetchNodes(ARGUS_IP_PRESET_CAMERA, tA); if (! tCNT) { tCNT = deviceNodeFactory::getInstance()->fetchNodes(ARGUS_ANALOG_PRESET_CAMERA, tA); }; }; }; }; }; if (tCNT) { for (uint32_t i = 0; i < tCNT; i++) { deviceNodeCamera * tCAM = (deviceNodeCamera *) tA[i]; if (! registerStream(tCAM->getCamStream(), tCAM->getFlipMode())) { RetVal = false; // tCAM->set
continue; }; }; free(tA); tA = NULL;#ifdef DEBUG_EXTRA
} else { LOG("No Camera Defined/Enabled In the system!");#endif
}; if (RetVal) { DBC_INT_LIST tInvalidList; m_mStreamHandlersProtector.lock(); for (mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++) { if ((*idx).second != NULL) { if (! (*idx).second->validate()) { tInvalidList.push_back((*idx).first); } } }; m_mStreamHandlersProtector.unlock(); if (tInvalidList.size()) { for (DBC_INT_LIST::iterator idx = tInvalidList.begin(); idx != tInvalidList.end(); idx++) { if (unregisterStream(*idx)) { registerStream(*idx); } }; tInvalidList.clear(); }; }; return RetVal;
if (m_pDBC) { DBC_MODULE_EMBED_VIDEO_DATA * tDATA = m_pDBC->getEmbedVideoData(m_nDBAUXID); if (tDATA) { if (memcmp(&m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA)) != 0) { free(tDATA);#ifdef DEBUG_EXTRA
LOG("Module Settings Changed!");#endif
return reloadSettings(); }; free(tDATA); } else { LOG_ERROR("No Fetched EVE Data"); RetVal = false; }; if (RetVal) { DBC_INT_LIST * tList = m_pDBC->listMediaStreams(0, LIST_VALID_RECORDS); if (tList != NULL) { for (DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++) {#ifdef DEBUG_EXTRA
LOG("REG STREAM");#endif
if (! registerStream(*idx)) { RetVal = false; continue; }; }; delete(tList);#ifdef DEBUG_EXTRA
} else { LOG("- No Valid Streams -");#endif
}; }; if (RetVal) { DBC_INT_LIST tInvalidList; m_mStreamHandlersProtector.lock(); for (mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++) { if ((*idx).second != NULL) { if (! (*idx).second->validate()) { tInvalidList.push_back((*idx).first); } } }; m_mStreamHandlersProtector.unlock(); if (tInvalidList.size()) { for (DBC_INT_LIST::iterator idx = tInvalidList.begin(); idx != tInvalidList.end(); idx++) { if (unregisterStream(*idx)) { registerStream(*idx); } }; tInvalidList.clear(); }; }; } else { LOG_ERROR("DB Error!"); RetVal = false; }; return RetVal;}
bool kernelModuleEmbedVideo::registerForMediaStream(uint32_t id, WEB_CLIENT_CTX *& CTX){ if (CTX) { if (id) { // Check if its Valid!
DBC_MEDIA_STREAM_DATA * tSD = m_pDBC->getMediaStreamData(id); if (tSD) { // if( !tSD->valid ) {
// free( tSD );
// return false;
// };
free(tSD); // if( pipe( CTX->m_iEncoderPipe ) == -1 ){
// CTX->bValid = false;
// return false;
// };
CTX->mediaStreamId = id; return true; }; }; } else { LOG_ERROR("Client Context error!"); } return false;}
bool kernelModuleEmbedVideo::dispatchEvent(EVENT_CONTAINER * Evt){ if (Evt) { switch (Evt->m_eClass) { case EVT_CLASS_IMAGE: case EVT_CLASS_VIDEO: { switch (Evt->m_eType) { case EVT_CAPTURE_START: {#ifdef DEBUG
LOG("Capture Event");#endif
if (Evt->m_ref_id && Evt->m_db_id) { uint32_t tPicID = saveStreamPicture(Evt->m_ref_id); if (tPicID) { //
// m_pDBC->addPictureEvent( Evt->m_db_id, tPicID );
} else {#ifdef DEBUG
LOG_ERROR("No Picture is Saved!");#endif
}; } else {#ifdef DEBUG
LOG_ERROR("No Stream ID or Event ID in Event Data!");#endif
}; break; }; default: break; }; break; }; case EVT_CLASS_CAMERA_CTRL: { switch (Evt->m_eType) { case EVT_CAMERA_MOVE_TO: {#ifdef DEBUG_EXTRA
LOG("Cam OnMove After Event -> Register SourceID");#endif
uint32_t sid = m_pDBC->getNodeAuxParam(Evt->m_nSourceNodeID); if (sid) {#ifdef DEBUG_EXTRA
LOG("Source ID found!");#endif
m_mStreamHandlersProtector.lock();#ifdef DEBUG_EXTRA
LOG("Mutex Locked!");#endif
mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find(sid); if (hnd != m_mapHANDLERS.end())#ifdef DEBUG_EXTRA
{ LOG("Handler found!");#endif
(*hnd).second->triggerCamMove();#ifdef DEBUG_EXTRA
LOG("Triggered!"); } else { LOG("No Stream Found!"); }#endif
m_mStreamHandlersProtector.unlock();#ifdef DEBUG_EXTRA
LOG("Mutex Unlocked!");#endif
} else { LOG("No Stream ID Found!"); } break; }; case EVT_CAMERA_ON_POSITION: {#ifdef DEBUG_EXTRA
LOG("Cam On Position After Event -> Capture Picture");#endif
DBC_SNAPSHOT_DATA * tData = (DBC_SNAPSHOT_DATA *) Evt->m_pEvtData; if (tData) { if (! saveStreamPicture(tData)) { LOG_ERROR("Save Error!"); } tData->assoc_event_ids.clear(); //free(tData);
delete( tData ); Evt->m_pEvtData = NULL;#ifdef DEBUG_EXTRA
LOG("Event Data Saved!");#endif
} else { LOG_ERROR("No Evt Data!"); } break; }; default: break; }; break; }; default: break; }; return true; }; return false;}
// https://www.ps2-home.com/forum/viewtopic.php?t=98
// https://www.mikekohn.net/software/playstation2.php
bool kernelModuleEmbedVideo::saveStreamPicture(DBC_SNAPSHOT_DATA * ptr){ if (ptr == NULL) { return false; } if ((m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES) == EVE_OUTPUT_PICTURES) {#ifdef DEBUG_EXTRA
LOG("Saving Picture!");#endif
// saveStreamPicture( ptr->stream_id );
//*
if (ptr->assoc_event_ids.size()) { if (m_mapCAPTURES.find(ptr->stream_id) != m_mapCAPTURES.end()) { m_mPictureProtector.lock(); ptr->data = (uint8_t *) malloc(m_mapCAPTURES[ptr->stream_id].size()); if (ptr->data) { ptr->data_size = m_mapCAPTURES[ptr->stream_id].size(); memcpy(ptr->data, m_mapCAPTURES[ptr->stream_id].data(), ptr->data_size); m_mPictureProtector.unlock(); CSTR MD5 = MD5Binary(ptr->data, ptr->data_size); if (MD5) { strncpy(ptr->md5, MD5, 32); free(MD5); if (! m_pDBC->addPicture(ptr, "jpg")) { LOG_ERROR("Database Error to consume capture!"); } } else { LOG_ERROR("no MD5 Hash!"); } free(ptr->data); } else { m_mPictureProtector.unlock(); LOG_ERROR("No memory to allocate!"); };#ifdef DEBUG_EXTRA
} else { LOG("No apropriate Stream Found!");#endif
}; }; //*/
#ifdef DEBUG_EXTRA
} else { LOG("No Pic Mode!");#endif
} if ((m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO) == EVE_OUTPUT_VIDEO) {#ifdef DEBUG
LOG("Saving Video!");#endif
if (ptr->assoc_event_ids.size()) { m_mStreamHandlersProtector.lock(); mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find(ptr->stream_id); if (hnd != m_mapHANDLERS.end()) { uint32_t db_id; uint32_t cfrm; for (DBC_INT_LIST::iterator idx = ptr->assoc_event_ids.begin(); idx < ptr->assoc_event_ids.end(); idx++) { (*hnd).second->triggerEvent(*idx, db_id, cfrm); }#ifdef DEBUG
} else { LOG("No Stream Found!");#endif
}; m_mStreamHandlersProtector.unlock();#ifdef DEBUG_EXTRA
} else { LOG("No Assoc EVTIDS!");#endif
};#ifdef DEBUG
} else { LOG("No Video Mode!");#endif
}; return true;}
bool kernelModuleEmbedVideo::saveStreamPicture(uint32_t id){ if (! id) { return false; } if (m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES) { if (m_mapCAPTURES.find(id) != m_mapCAPTURES.end()) { //FILE * tFD;
m_mPictureProtector.lock(); size_t tBufferSize = m_mapCAPTURES[id].size(); uint8_t * tBuffer = (uint8_t *) malloc(tBufferSize); if (tBuffer) { memcpy(tBuffer, m_mapCAPTURES[id].data(), tBufferSize); m_mPictureProtector.unlock(); CSTR MD5 = MD5Binary(tBuffer, tBufferSize); if (MD5) { char tFileName[MAX_PATH]; if (generateSavePicPath(MD5, tFileName)) { FILE * fd = fopen(tFileName, "wb+"); if (fd) { fwrite(tBuffer, 1, tBufferSize, fd); fclose(fd); ch_chown(tFileName, "nobody", "nogroup"); // retVal = m_pDBC->addPicture( id, MD5, "jpg" );
} else { LOG_ERROR("Can not open picture file!"); } } else { LOG_ERROR("Can not generate file name!"); } free(MD5); } else { LOG_ERROR("no MD5 Hash!"); } free(tBuffer); } else { m_mPictureProtector.unlock(); LOG_ERROR("no memory to allocate!"); }; }; } return true;}
int kernelModuleEmbedVideo::getWidh(void){ if (m_sEmbedVideoData.width) { return m_sEmbedVideoData.width; } return -1;}
int kernelModuleEmbedVideo::getHeight(void){ if (m_sEmbedVideoData.height) { return m_sEmbedVideoData.height; } return -1;}
bool kernelModuleEmbedVideo::generateSavePicPath(CSTR MD5, CSTR Output){ if (MD5 == NULL) { return false; } if (Output == NULL) { return false; } if (! fileExist(m_pBaseSavePath)) { LOG_ERROR("No Base Picture Save Path Defined!"); return false; }; if (strlen(MD5) < 4) { return false; } char test[5000]; sprintf(test, "%s/%c%c", m_pBaseSavePath, MD5[0], MD5[1]); if (! fileExist(test)) {#ifdef __linux__
mkdir(test, STORAGE_DIR_MODE);#else
_mkdir(test);#endif
ch_chown(test, "nobody", "nogroup"); }; sprintf(test, "%s/%c%c/%c%c", m_pBaseSavePath, MD5[0], MD5[1], MD5[2], MD5[3]); if (! fileExist(test)) {#ifdef __linux__
mkdir(test, STORAGE_DIR_MODE);#else
_mkdir(test);#endif
ch_chown(test, "nobody", "nogroup"); }; sprintf(Output, "%s/%c%c/%c%c/%s.jpg", m_pBaseSavePath, MD5[0], MD5[1], MD5[2], MD5[3], MD5); return true;}
bool kernelModuleEmbedVideo::registerStream(uint32_t streamID, uint8_t flip_mode){ // return true;
try { m_mStreamHandlersProtector.lock(); streamHandler * tData = m_mapHANDLERS.at(streamID); // If SH allready exists
if (tData != NULL) { m_mStreamHandlersProtector.unlock(); return true; }; // Create New One
if ((m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO) != EVE_OUTPUT_VIDEO) { tData = new streamHandler(this, MS_MODE_DECODE_FRAMES, flip_mode); } else { tData = new streamHandler(this, MS_MODE_ENCODE_FRAMES, flip_mode); }; if (tData != NULL) { if (tData->create(m_pDBC, streamID)) { m_mapHANDLERS[streamID] = tData; m_mStreamHandlersProtector.unlock(); return true; } else { LOG_ERROR("Error Creating new Stream Handler[t]!"); delete(tData); m_mapHANDLERS[streamID] = NULL; }; } else { LOG_ERROR("Error Constructing new Stream Handler[t]!"); }; m_mStreamHandlersProtector.unlock(); } catch (const std::out_of_range & oor) { streamHandler * tSH = NULL; // Create New One
if ((m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO) != EVE_OUTPUT_VIDEO) { tSH = new streamHandler(this, MS_MODE_DECODE_FRAMES, flip_mode); } else { tSH = new streamHandler(this, MS_MODE_ENCODE_FRAMES, flip_mode); }; if (tSH != NULL) { if (tSH->create(m_pDBC, streamID)) { m_mapHANDLERS[streamID] = tSH; m_mStreamHandlersProtector.unlock(); return true; } else { LOG_ERROR("Error Creating new Stream Handler[c]!"); delete(tSH); m_mapHANDLERS[streamID] = NULL; }; } else { LOG_ERROR("Error Constructing new Stream Handler[c]!"); }; m_mStreamHandlersProtector.unlock(); }; return false;}
bool kernelModuleEmbedVideo::unregisterStream(uint32_t streamID){ try { m_mStreamHandlersProtector.lock(); streamHandler * tData = m_mapHANDLERS.at(streamID); if (tData != NULL) { delete(tData); // ToDo: Remove Stream Mats and Clients Connected to a Stream ( or Push them No Signal Image )
m_mapHANDLERS[streamID] = NULL; m_mStreamHandlersProtector.unlock(); return true; }; m_mStreamHandlersProtector.unlock(); LOG_ERROR("Registered Stream is Empty!"); } catch (const std::out_of_range & oor) { m_mStreamHandlersProtector.unlock(); LOG_ERROR("No Such Stream Registered!"); }; return false;}
#undef LOG
#undef LOG_ERROR
#define LOG(X) streamHandler::m_pLog->Log("MEV_STR", this, X)
#ifdef DEBUG
#define LOG_ERROR(X) \
{ \ char _tBfrErrMSG2w34[256]; \ sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \ streamHandler::m_pLog->Log("MEV_STR", this, _LOG_ERROR, _tBfrErrMSG2w34); \ }#else
#define LOG_ERROR(X) streamHandler::m_pLog->Log("MEV_STR", this, _LOG_ERROR, X);
#endif
streamHandler::streamHandler(kernelModuleEmbedVideo * ptr, MS_WORK_MODE M, uint8_t flip_mode) : basicMediaDestination(),#ifdef EVE_ENABLE_VIDEO
basicThread(),#endif
m_pMaster(ptr), m_eWM(M){ m_pLog = basicLogCollection::getInstance(); memset(&m_sStreamData, 0, sizeof(DBC_MEDIA_STREAM_DATA)); m_pSource = NULL; m_bEvtMarkerCounter = 0; m_bCamMoveCounter = 0; m_bFlipMode = flip_mode;#ifdef EVE_ENABLE_EASE_OUTPUT_FPS
#ifdef EVE_ENABLE_VIDEO
m_bAFrameSkeepDivider = 1; m_bAFrameSkeepDividerCounter = 0; m_bAOutputFPS = VIDEO_OUTPUT_FPS;
m_bBFrameSkeepDivider = 1; m_bBFrameSkeepDividerCounter = 0; m_bBOutputFPS = VIDEO_OUTPUT_FPS; #endif
m_bWebFrameSkeepDivider = 1; m_bWebFrameSkeepDividerCounter = 0; m_bInitialOutputFPS = m_bCurrentOutputFPS = VIDEO_OUTPUT_FPS;#endif
#ifdef EVE_ENABLE_VIDEO
#ifdef EVE_ENABLE_EASE_OUTPUT_FPS
m_nAPreAlarmFrames = 0; m_nAPostAlarmFrames = 0; m_nASegmentLimitFrames = 0; m_nAHardLimitFrames = 0;
m_nBPreAlarmFrames = 0; m_nBPostAlarmFrames = 0; m_nBSegmentLimitFrames = 0; m_nBHardLimitFrames = 0; #else
m_nPreAlarmFrames = 0; m_nPostAlarmFrames = 0; m_nSegmentLimitFrames = 0; m_nHardLimitFrames = 0; #endif
m_nSegAFrameCounter = 0; m_nSegBFrameCounter = 0; m_nGlobalFrameCounter = 0;
// m_nVideoRegisteredDBID = 0;
m_nSegAShiftFrames = 0; m_nSegBShiftFrames = 0; m_nSegASkippedFrames = m_nSegBSkippedFrames = 0;
m_bActiveEncoderStream = 0; m_bSegAActive = false; m_bSegADelete = true; m_bSegBActive = false; m_bSegBDelete = true; m_bCOP = 0; m_cSourceType = 'A';
//todo: must be writen helper function to clean VIDEO_SEGMENT_INFO
//that is not dynamicaly created by NEW operator
//memset(&m_sStreamSegmentInfo[0], 0, sizeof(VIDEO_SEGMENT_INFO));
//memset(&m_sStreamSegmentInfo[1], 0, sizeof(VIDEO_SEGMENT_INFO));
#ifdef DIRECT_MJPEG_COMPOSING
m_pOutputFD[0] = NULL; m_pOutputFD[1] = NULL; #else // !DIRECT_MJPEG_COMPOSING
#ifdef OPENCV_VIDEO_OUTPUT
m_pEncoderA = NULL; m_pEncoderB = NULL; #endif
#endif
#endif // EVE_ENABLE_VIDEO
// if( M == MS_MODE_DECODE_FRAMES ) 1=1;
}
streamHandler::~streamHandler(){ if (m_sStreamData.id) { if (m_pSource != NULL) { switch (m_cSourceType) { // m_sStreamData.source_type[0] ) {
case 'D': delete((videoLIVE555Source *) m_pSource); break; case 'A': delete((videoAVLIBSource *) m_pSource); break; }; };#ifdef EVE_ENABLE_VIDEO
closeAll();#endif // EVE_ENABLE_VIDEO
};}
bool streamHandler::create(dataBinder * ptr, uint32_t stremID){ if (ptr == NULL) { return false; } m_pDBC = ptr; if (stremID) { DBC_MEDIA_STREAM_DATA * tData = m_pDBC->getMediaStreamData(stremID); if (tData) { memcpy(&m_sStreamData, tData, sizeof(DBC_MEDIA_STREAM_DATA)); free(tData); DBC_CAM_DATA * tCAM = m_pDBC->getCamData(m_sStreamData.source_id); if (tCAM) {
m_sSourceDesc.mediaStreamId = stremID;
m_sSourceDesc.mediaSourceId = m_sStreamData.source_id; uint32_t tNID = m_pDBC->getNodeIdByTypeAndAux(tCAM->type, m_sStreamData.source_id); // ToDo: Check Camera Addition
// Just Work around to handle Wrong tyoe 12 instead of 13
if (tNID == 0) { tNID = m_pDBC->getNodeIdByTypeAndAux(13, m_sStreamData.source_id); }; if (tNID) { CSTR tNAM = m_pDBC->getNodeName(tNID); if (tNAM != NULL) { strncpy(m_sSourceDesc.mediaName, tNAM, 127); m_sSourceDesc.mediaName[127] = (char) 0; free(tNAM); } else { sprintf(m_sSourceDesc.mediaName, "No Name Cam"); }; } else { sprintf(m_sSourceDesc.mediaName, "No-Name-Cam"); };
m_cSourceType = m_sStreamData.source_type[0];
switch (m_cSourceType) { case 'A': m_pSource = (basicMediaSource *) new videoAVLIBSource(&m_sSourceDesc); break; case 'D': { // Check Auth mode if basic - Override and use AVLIB
// To Debug LIVE555 ONLY
if (1 || tCAM->auth_mode == 0) { m_cSourceType = 'A'; m_pSource = (basicMediaSource *) new videoAVLIBSource(&m_sSourceDesc); break; } else { m_pSource = (basicMediaSource *) new videoLIVE555Source(&m_sSourceDesc); break; }; break; }; }; if (m_pSource != NULL) { char tMRL[1024];#ifdef DEBUG_EXTRA
LOG("Source OK");#endif
int tW = m_pMaster->getWidh(); int tH = m_pMaster->getHeight(); int pix = -1; bool in_16_9 = (((m_sStreamData.width * 100) / m_sStreamData.height) > 140); bool out_16_9 = (((tW * 100) / tH) > 140); // if( tW > 0 ){
// //m_pSource->setProportionalByWidth( tW );
// m_pSource->setSize( tW, tH );
// };
if (in_16_9 != out_16_9) { if (in_16_9) { tH = (((tW * 1000) / 16) * 9) / 1000; } else { tW = (((tH * 1000) / 3) * 4) / 1000; }; }; // export PATH=/usr/sbin:$PATH
if (strncmp(m_sStreamData.mrl_proto, "v4l2", 4) == 0) { sprintf(tMRL, m_sStreamData.mrl); pix = atoi(m_sStreamData.c_type); } else { sprintf(tMRL, "%s://%s:%s@%s:%d%s", m_sStreamData.mrl_proto, tCAM->username, tCAM->password, tCAM->ip, m_sStreamData.mrl_port, m_sStreamData.mrl); }; if (m_pSource->_open(tMRL, false, -1.0f, pix, m_sStreamData.width, m_sStreamData.height, tW, tH)) { if (! m_pSource->attachDestination(this)) { switch (m_cSourceType) { case 'D': delete((videoLIVE555Source *) m_pSource); break; case 'A': delete((videoAVLIBSource *) m_pSource); break; }; m_pSource = NULL; } else {#ifdef DEBUG_EXTRA
LOG("Source is Connected to Output.");#endif
}; } else { LOG_ERROR("Can not Open Video Source!"); switch (m_cSourceType) { case 'D': delete((videoLIVE555Source *) m_pSource); break; case 'A': delete((videoAVLIBSource *) m_pSource); break; }; m_pSource = NULL; }; } else { LOG_ERROR("Video Source Stream Failure!"); }; free(tCAM); } else { LOG_ERROR("Error Getting CAM Data!"); m_pSource = NULL; return false; }; }; };
if (m_pSource) {#ifdef EVE_ENABLE_VIDEO
return initVideoOutput();#else
return true;#endif // EVE_ENABLE_VIDEO
};
return false;}
bool streamHandler::pushFrame(AVFrame * Frame, void * src){ if( !Frame ) return false; if( !m_pMaster )return false;
MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; if (tMD) { }; return true;}
bool streamHandler::pushFrame(cv::Mat & Frame, void * src){
/// @todo Valgrind is reporting an important memory leak in this method.
#ifdef EVE_ENABLE_EASE_OUTPUT_FPS
bool SkeepW, SkeepA, SkeepB;#endif
if (m_pMaster == NULL) { return false; } MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; char tBuffer[512]; if (tMD) { float mK, oK; cv::Rect ROI;
m_pMaster->m_mPictureProtector.lock();
if (m_pMaster->m_mapMATS[tMD->mediaStreamId].cols == 0) { LOG("First Frame Enqueued"); sprintf(tBuffer, "INP: [%dx%d] SrcID:%d StreamID:%d", Frame.cols, Frame.rows, tMD->mediaSourceId, tMD->mediaStreamId); LOG(tBuffer);
m_pMaster->m_mapMATS[tMD->mediaStreamId].create(m_pMaster->m_sEmbedVideoData.height, m_pMaster->m_sEmbedVideoData.width, CV_8UC3); cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Point(0, 0), cv::Point(m_pMaster->m_sEmbedVideoData.height, m_pMaster->m_sEmbedVideoData.width), cv::Scalar(0, 0, 0), cv::FILLED); };
#ifdef EVE_ENABLE_EASE_OUTPUT_FPS
SkeepW = ! ((m_bWebFrameSkeepDividerCounter % m_bWebFrameSkeepDivider) == 0); m_bWebFrameSkeepDividerCounter = (++m_bWebFrameSkeepDividerCounter) % m_bWebFrameSkeepDivider; #ifdef EVE_ENABLE_VIDEO
SkeepA = ! ((m_bAFrameSkeepDividerCounter % m_bAFrameSkeepDivider) == 0); // m_bAFrameSkeepDividerCounter++;
m_bAFrameSkeepDividerCounter = (++m_bAFrameSkeepDividerCounter) % m_bAFrameSkeepDivider; SkeepB = ! ((m_bBFrameSkeepDividerCounter % m_bBFrameSkeepDivider) == 0); // m_bBFrameSkeepDividerCounter++;
m_bBFrameSkeepDividerCounter = (++m_bBFrameSkeepDividerCounter) % m_bBFrameSkeepDivider; #ifdef DEBUG_ALL
if (SkeepW || SkeepA || SkeepB) { char tzB[256]; sprintf(tzB, "SkipF: %d:%d %d:%d %d:%d", m_bWebFrameSkeepDividerCounter, m_bWebFrameSkeepDivider, m_bAFrameSkeepDividerCounter, m_bAFrameSkeepDivider, m_bBFrameSkeepDividerCounter, m_bBFrameSkeepDivider); LOG(tzB); } else { LOG("PushF"); }; #endif
// if( m_bWebFrameSkeepDivider == m_bAFrameSkeepDividerCounter ) = 1;
// if( SkeepB ) m_bBFrameSkeepDividerCounter = 1;
// if( SkeepW ) m_bWebFrameSkeepDividerCounter = 1;
#else
#ifdef DEBUG_ALL
if (SkeepW) { char tB[256]; sprintf(tB, "Skip: %d:%d", m_bWebFrameSkeepDividerCounter, m_bWebFrameSkeepDivider); LOG(tB); }; #endif
if (SkeepW) { m_bWebFrameSkeepDividerCounter = 1; } #endif
#endif
#ifdef USE_SCALING_IN
oK = ((float) m_pMaster->m_sEmbedVideoData.height) / ((float) m_pMaster->m_sEmbedVideoData.width); mK = ((float) Frame.rows) / ((float) Frame.cols); // sprintf( tBuffer, "INP: [%dx%d] IK:%0.3f OK:%0.3f", Frame.cols, Frame.rows, mK, oK );
if ((fabsf(mK - oK) < 0.1f) || (fabsf(oK - mK) < 0.1f)) { ROI.width = (int) m_pMaster->m_sEmbedVideoData.width; ROI.height = (int) m_pMaster->m_sEmbedVideoData.height; ROI.x = (int) 0; ROI.y = (int) 0; } else { if (mK < oK) { ROI.width = (int) m_pMaster->m_sEmbedVideoData.width; ROI.height = (int) (((float) m_pMaster->m_sEmbedVideoData.width) * mK); ROI.x = (int) 0; ROI.y = (int) (m_pMaster->m_sEmbedVideoData.height - ROI.height) >> 1; } else { ROI.height = (int) m_pMaster->m_sEmbedVideoData.height; ROI.width = (int) (((float) m_pMaster->m_sEmbedVideoData.height) / mK); ROI.y = (int) 0; ROI.x = (int) (m_pMaster->m_sEmbedVideoData.width - ROI.width) >> 1; }; }; cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId](ROI); #ifndef USE_CV_DENOISE
cv::resize(Frame, mROI, mROI.size(), 0, 0, cv::INTER_LINEAR); #else
cv::Mat mDenoiser; cv::resize(Frame, mDenoiser, mROI.size(), 0, 0, cv::INTER_LINEAR); cv::fastNlMeansDenoisingColored(mDenoiser, mROI, 10, 10, 7, 17); #endif
#ifdef USE_CV_TONEMAP
cv::Mat ldrReinhard; cv::Ptr<cv::TonemapReinhard> tonemapReinhard = cv::createTonemapReinhard(1.5, 0, 0, 0); tonemapReinhard->process(mROI, ldrReinhard); ldrReinhard = ldrReinhard * 255; ldrReinhard.copyTo(mROI); #endif
#else
if ((m_pMaster->m_sEmbedVideoData.height == Frame.rows) && (m_pMaster->m_sEmbedVideoData.width == Frame.cols)) { Frame.copyTo(m_pMaster->m_mapMATS[tMD->mediaStreamId]); } else { // Mat dst_roi = dst(Rect(left, top, src.cols, src.rows));
// src.copyTo(dst_roi);
if (m_pMaster->m_sEmbedVideoData.width == Frame.cols) { ROI.width = Frame.cols; ROI.height = Frame.rows; ROI.x = 0; ROI.y = (m_pMaster->m_sEmbedVideoData.height - Frame.rows) >> 1; cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId](ROI); #ifdef USE_CV_DENOISE
cv::fastNlMeansDenoisingColored(Frame, mROI, 10, 10, 7, 17); #else
Frame.copyTo(mROI); #endif
#ifdef USE_CV_TONEMAP
cv::Mat ldrReinhard; cv::Ptr<cv::TonemapReinhard> tonemapReinhard = cv::createTonemapReinhard(1.5, 0, 0, 0); tonemapReinhard->process(mROI, ldrReinhard); ldrReinhard = ldrReinhard * 255; ldrReinhard.copyTo(mROI); #endif
} else { ROI.width = Frame.cols; ROI.height = Frame.rows; ROI.x = (m_pMaster->m_sEmbedVideoData.width - Frame.cols) >> 1; ROI.y = 0; cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId](ROI); #ifdef USE_CV_DENOISE
cv::fastNlMeansDenoisingColored(Frame, mROI, 10, 10, 7, 17); #else
Frame.copyTo(mROI); #endif
#ifdef USE_CV_TONEMAP
cv::Mat ldrReinhard; cv::Ptr<cv::TonemapReinhard> tonemapReinhard = cv::createTonemapReinhard(1.5, 0, 0, 0); tonemapReinhard->process(mROI, ldrReinhard); ldrReinhard = ldrReinhard * 255; ldrReinhard.copyTo(mROI); #endif
}; };#endif
// 0 - dis .. 1 - Hor ... 2 - vert 3 - both
if (m_bFlipMode) { // Flip Horizontally = 1 vertically = 0 both = -1
cv::Mat mirroredImage; cv::flip(m_pMaster->m_mapMATS[tMD->mediaStreamId], mirroredImage, 2 - m_bFlipMode); mirroredImage.copyTo(m_pMaster->m_mapMATS[tMD->mediaStreamId]); };
#ifdef EVE_ENABLE_DROP_OUTPUT_FPS
// LOG("T");
m_mEncodingQueueProtector.lock(); if (m_qEncodingQueue.size() > 10) { m_mEncodingQueueProtector.unlock(); m_pMaster->m_mPictureProtector.unlock(); // LOG("D");
return true; }; m_mEncodingQueueProtector.unlock(); // LOG("Q");
#endif
#ifdef EVE_ENABLE_EASE_OUTPUT_FPS
#ifdef EVE_ENABLE_VIDEO
if (SkeepW && SkeepA && SkeepB) { m_pMaster->m_mPictureProtector.unlock(); return true; }; #else
if (SkeepW) { m_pMaster->m_mPictureProtector.unlock(); return true; }; #endif
#endif
if (m_bCamMoveCounter > m_bEvtMarkerCounter) { cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Rect(10, 10, 20, 20), cv::Scalar(m_bCamMoveCounter, 0, 0), cv::FILLED); m_bCamMoveCounter -= 4; if (m_bCamMoveCounter < 4) { m_bCamMoveCounter = 0; } } else { if (m_bEvtMarkerCounter) { m_bCamMoveCounter = 0; cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Rect(10, 10, 20, 20), cv::Scalar(0, 0, m_bEvtMarkerCounter), cv::FILLED); m_bEvtMarkerCounter -= 4; if (m_bEvtMarkerCounter < 4) { m_bEvtMarkerCounter = 0; } }; }; if (m_pMaster->m_sEmbedVideoData.show_label) { time_t t = time(NULL); // struct tm * tmp = gmtime( &t );
struct tm * tmp = localtime(&t); if (tmp) { char tsb[64]; // if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){
if (strftime(tsb, sizeof(tsb), "%F %T", tmp) != 0) {
// sprintf( tBuffer, ">>%d>%d>%s>%s>", tMD->mediaSourceId, tMD->mediaStreamId, tMD->mediaName, tsb );
sprintf(tBuffer, ">>>%s>%s>", tMD->mediaName, tsb); int baseline = 0; cv::Size textSize = cv::getTextSize(tBuffer, m_pMaster->m_sEmbedVideoData.label_font_face, m_pMaster->m_sEmbedVideoData.label_font_scale, m_pMaster->m_sEmbedVideoData.label_font_thickness, &baseline); int x = m_pMaster->m_sEmbedVideoData.label_x; int y = m_pMaster->m_sEmbedVideoData.label_y; if (x < 0) { x = m_pMaster->m_sEmbedVideoData.width + x - textSize.width; }; if (y < 0) { y = m_pMaster->m_sEmbedVideoData.height + y - baseline; //
}; if (! m_pMaster->m_sEmbedVideoData.label_transperant) { cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Rect(x, y - textSize.height - 4, textSize.width, textSize.height + baseline + 4), cv::Scalar(0, 0, 0), cv::FILLED); }; cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(x, y), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.label_font_face, m_pMaster->m_sEmbedVideoData.label_font_scale, cv::Scalar(0, 255, 0), m_pMaster->m_sEmbedVideoData.label_font_thickness, m_pMaster->m_sEmbedVideoData.label_line_type); }; }; } else { if (m_pMaster->m_sEmbedVideoData.show_ts) { time_t t = time(NULL); // struct tm * tmp = gmtime( &t );
struct tm * tmp = localtime(&t); if (tmp) { if (strftime(tBuffer, sizeof(tBuffer), "%F %T GMT", tmp) != 0) { uint8_t shift_x = 0; uint8_t shift_y = 15; if (! m_pMaster->m_sEmbedVideoData.ts_transperant) { if (m_pMaster->m_sEmbedVideoData.ts_font_face) { shift_y = 15; cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Point(m_pMaster->m_sEmbedVideoData.ts_x, m_pMaster->m_sEmbedVideoData.ts_y), cv::Point(490, 60), cv::Scalar(0, 0, 0), cv::FILLED); } else { shift_y = 23; cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Point(m_pMaster->m_sEmbedVideoData.ts_x, m_pMaster->m_sEmbedVideoData.ts_y), cv::Point(490, 60), cv::Scalar(0, 0, 0), cv::FILLED); }; cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x, m_pMaster->m_sEmbedVideoData.ts_y + shift_y), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 255, 255), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type); } else { if (m_pMaster->m_sEmbedVideoData.ts_font_face) { shift_y = 15; } else { shift_y = 23; }; cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 0, 0), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type); cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x + 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 0, 0), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type); cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 1), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 0, 0), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type); cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 2), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 0, 0), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type); cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x, m_pMaster->m_sEmbedVideoData.ts_y + shift_y), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 255, 255), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type); } }; }; }; }; if (m_pMaster->m_sEmbedVideoData.show_logo) { cv::Rect roi(cv::Point(m_pMaster->m_sEmbedVideoData.logo_x, m_pMaster->m_sEmbedVideoData.logo_y), cv::Size(m_pMaster->m_sEmbedVideoData.logo_w, m_pMaster->m_sEmbedVideoData.logo_h)); cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId](roi); m_pMaster->m_mLogoPic.copyTo(destinationROI, m_pMaster->m_mLogoMask); };#ifdef EVE_ENABLE_EASE_OUTPUT_FPS
if (! SkeepW) {#endif
vector<int> compression_params; // compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
// compression_params.push_back(9);
compression_params.push_back(cv::IMWRITE_JPEG_QUALITY); compression_params.push_back(50); // m_pMaster->m_sEmbedVideoData.compression_quality );
m_pMaster->m_mEncodedProtector.lock(); m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].clear(); cv::imencode(".jpg", m_pMaster->m_mapMATS[tMD->mediaStreamId], m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params);
// cv::Mat bw_dst;
// cv::cvtColor( m_pMaster->m_mapMATS[tMD->mediaStreamId], bw_dst, cv::COLOR_BGR2GRAY );
// cv::imencode( ".jpg", bw_dst, m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params );
#ifdef HAVE_SMAL_PREVIEW_STREAMS
// Make Small Preview Thumb
cv::Mat dst; cv::resize(m_pMaster->m_mapMATS[tMD->mediaStreamId], dst, cv::Size(PREVIEW_SIZE_WIDTH, PREVIEW_SIZE_HEIGHT)); // cv::resize( bw_dst, dst, cv::Size( PREVIEW_SIZE_WIDTH, PREVIEW_SIZE_HEIGHT ));
m_pMaster->m_mapPREVIEWS[tMD->mediaStreamId].clear(); cv::imencode(".jpg", dst, m_pMaster->m_mapPREVIEWS[tMD->mediaStreamId], compression_params);#endif
m_pMaster->m_mEncodedProtector.unlock();#ifdef EVE_ENABLE_EASE_OUTPUT_FPS
};#endif
#ifdef EVE_ENABLE_VIDEO
// if only decode Video Stream -> Exit
if (m_eWM == MS_MODE_DECODE_FRAMES) { m_pMaster->m_mPictureProtector.unlock(); return true; }; // encode Video Stream
// m_nPreAlarmFrames
// m_nPostAlarmFrames
// m_nNoAlarmSegmentFrames
// m_nSegmentLimitFrames
// m_nHardLimitFrames
if (m_bSegAActive || m_bSegBActive) { m_mFrameCounterProtector.lock();
if (m_bSegAActive) { #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
// do {
// In Any Case Close Stream if it Long enough
if (m_nSegAFrameCounter > m_nAHardLimitFrames) { #ifdef DEBUG_EXTRA
LOG("HardLimit Reached!(A)"); #endif
closeSegmentA(); // break;
}; if (m_nSegAFrameCounter > (m_nASegmentLimitFrames - (m_nAPostAlarmFrames + m_nBPreAlarmFrames))) { if (! m_bSegBActive) { #ifdef DEBUG_EXTRA
LOG("Start Alt!(A)"); #endif
openSegmentB(); }; }; if (m_nSegAFrameCounter > (m_nASegmentLimitFrames - m_nAPostAlarmFrames) && ! m_bActiveEncoderStream) { #ifdef DEBUG_EXTRA
LOG("Swap Active!(A)"); #endif
swapActiveStreams(); // break;
}; // } while ( 0 );
#else
// do {
// In Any Case Close Stream if it Long enough
if (m_nSegAFrameCounter > m_nHardLimitFrames) { #ifdef DEBUG_EXTRA
LOG("HardLimit Reached!(A)"); #endif
closeSegmentA(); // break;
}; if (m_nSegAFrameCounter > (m_nSegmentLimitFrames - (m_nPostAlarmFrames + m_nPreAlarmFrames))) { if (! m_bSegBActive) { #ifdef DEBUG_EXTRA
LOG("Start Alt!(A)"); #endif
openSegmentB(); }; }; if (m_nSegAFrameCounter > (m_nSegmentLimitFrames - m_nPostAlarmFrames) && ! m_bActiveEncoderStream) { #ifdef DEBUG_EXTRA
LOG("Swap Active!(A)"); #endif
swapActiveStreams(); // break;
}; // } while ( 0 );
#endif // !EVE_ENABLE_EASE_OUTPUT_FPS
};
if (m_bSegBActive) { #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
// do {
// In Any Case Close Stream if it Long enough
if (m_nSegBFrameCounter > m_nBHardLimitFrames) { #ifdef DEBUG_EXTRA
LOG("HardLimit Reached!(B)"); #endif
closeSegmentB(); // break;
}; if (m_nSegBFrameCounter > (m_nBSegmentLimitFrames - (m_nBPostAlarmFrames + m_nAPreAlarmFrames))) { if (! m_bSegAActive) { #ifdef DEBUG_EXTRA
LOG("Start Alt!(B)"); #endif
openSegmentA(); }; }; if (m_nSegBFrameCounter > (m_nBSegmentLimitFrames - m_nBPostAlarmFrames) && m_bActiveEncoderStream) { #ifdef DEBUG_EXTRA
LOG("Swap Active!(B)"); #endif
swapActiveStreams(); // break;
}; //} while ( 0 );
#else // !EVE_ENABLE_EASE_OUTPUT_FPS
// do {
// In Any Case Close Stream if it Long enough
if (m_nSegBFrameCounter > m_nHardLimitFrames) { #ifdef DEBUG_EXTRA
LOG("HardLimit Reached!(B)"); #endif
closeSegmentB(); // break;
}; if (m_nSegBFrameCounter > (m_nSegmentLimitFrames - (m_nPostAlarmFrames + m_nPreAlarmFrames))) { if (! m_bSegAActive) { #ifdef DEBUG_EXTRA
LOG("Start Alt!(B)"); #endif
openSegmentA(); }; }; if (m_nSegBFrameCounter > (m_nSegmentLimitFrames - m_nPostAlarmFrames) && m_bActiveEncoderStream) { #ifdef DEBUG_EXTRA
LOG("Swap Active!(B)"); #endif
swapActiveStreams(); // break;
}; //} while ( 0 );
#endif // !EVE_ENABLE_EASE_OUTPUT_FPS
};
m_mFrameCounterProtector.unlock();
ENCODING_BUFFER * tData = (ENCODING_BUFFER *) malloc(sizeof(ENCODING_BUFFER)); if (tData) { #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
tData->flag_sa = SkeepA; tData->flag_sb = SkeepB; #endif
#ifdef DIRECT_MJPEG_COMPOSING
tData->size = m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].size(); tData->data = (uint8_t *) malloc(tData->size); if (tData->data) { memcpy(tData->data, m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].data(), tData->size); // tData->data = m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].data();
// if ( tData->data ) {
#else
#ifdef OPENCV_VIDEO_OUTPUT
tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows; tData->cols = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols; tData->size = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols * m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize() * tData->rows; tData->data = (uint8_t *) malloc(tData->size); if (tData->data) { memcpy(tData->data, m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size); #else // OPENCV_VIDEO_OUTPUT
tData->linesize[0] = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols * m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize(); tData->linesize[1] = 0; tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows; tData->size = tData->linesize[0] * tData->rows; tData->data[1] = NULL; tData->data[0] = (uint8_t *) malloc(tData->size); if (tData->data[0]) { memcpy(tData->data[0], m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size); #endif // OPENCV_VIDEO_OUTPUT
#endif //! DIRECT_MJPEG_COMPOSING
m_mEncodingQueueProtector.lock(); m_qEncodingQueue.push(tData); m_mEncodingQueueProtector.unlock(); } else { LOG_ERROR("MAT_CPY malloc Error!"); free(tData); }; } else { LOG_ERROR("ENC_BUF malloc Error!"); } };#endif // EVE_ENABLE_VIDEO
m_pMaster->m_mPictureProtector.unlock(); } else { LOG_ERROR("No PayLoad!"); }; return true;}
#ifdef EVE_ENABLE_VIDEO
void streamHandler::closeSegmentA(void){ m_mCurrentOperationProtector.lock(); if (m_bCOP == 0) { m_bCOP = 0x01; } m_mCurrentOperationProtector.unlock(); #ifdef DEBUG_EXTRA
LOG("Closing Stream A"); #endif
}
void streamHandler::closeSegmentB(void){ m_mCurrentOperationProtector.lock(); if (m_bCOP == 0) { m_bCOP = 0x02; } m_mCurrentOperationProtector.unlock(); #ifdef DEBUG_EXTRA
LOG("Closing Stream B"); #endif
}
void streamHandler::closeAll(){ waitThreadEnd(true); #ifdef OPENCV_VIDEO_OUTPUT
if (m_pEncoderA) { if (m_pEncoderA->isOpened()) { m_pEncoderA->release(); }; delete(m_pEncoderA); }; if (m_pEncoderB) { if (m_pEncoderB->isOpened()) { m_pEncoderB->release(); }; delete(m_pEncoderB); };
#else // OPENCV_VIDEO_OUTPUT
#ifdef DIRECT_MJPEG_COMPOSING
if (m_pOutputFD[0]) { fclose(m_pOutputFD[0]); m_pOutputFD[0] = NULL; }; if (m_pOutputFD[1]) { fclose(m_pOutputFD[1]); m_pOutputFD[1] = NULL; }; #else // ! DIRECT_MJPEG_COMPOSING
#ifdef SEPARATED_VIDEO_ENCODERS
if ((m_pCodecACtx != NULL || m_pCodecBCtx != NULL) && (m_bSegAActive || m_bSegBActive)) { if (m_pCodecACtx != NULL) { avcodec_send_frame(m_pCodecACtx, NULL); int ret = 0; AVPacket * avp = av_packet_alloc(); if (avp) { do { av_packet_unref(avp); ret = avcodec_receive_packet(m_pCodecACtx, avp); if (! ret) { if (m_bSegAActive) { av_write_frame(m_pFormatCtxA, avp); } }; } while (! ret); av_packet_unref(avp); av_packet_free(&avp); }; }; if (m_pCodecBCtx != NULL) { avcodec_send_frame(m_pCodecBCtx, NULL); int ret = 0; AVPacket * avp = av_packet_alloc(); if (avp) { do { av_packet_unref(avp); ret = avcodec_receive_packet(m_pCodecBCtx, avp); if (! ret) { if (m_bSegBActive) { av_write_frame(m_pFormatCtxB, avp); } }; } while (! ret); av_packet_unref(avp); av_packet_free(&avp); }; }; if (m_bSegAActive) { av_write_trailer(m_pFormatCtxA); avformat_close_input(&m_pFormatCtxA); m_bSegAActive = false; }; if (m_bSegBActive) { av_write_trailer(m_pFormatCtxB); avformat_close_input(&m_pFormatCtxB); m_bSegBActive = false; }; }; #else // !SEPARATED_VIDEO_ENCODERS
if (m_pCodecCtx != NULL && (m_bSegAActive || m_bSegBActive)) { avcodec_send_frame(m_pCodecCtx, NULL); int ret = 0; AVPacket * avp = av_packet_alloc(); if (avp) { do { av_packet_unref(avp); ret = avcodec_receive_packet(m_pCodecCtx, avp); if (! ret) { if (m_bSegAActive) { av_write_frame(m_pFormatCtxA, avp); } if (m_bSegBActive) { av_write_frame(m_pFormatCtxB, avp); } }; } while (! ret); av_packet_unref(avp); av_packet_free(&avp); }; if (m_bSegAActive) { av_write_trailer(m_pFormatCtxA); avformat_close_input(&m_pFormatCtxA); m_bSegAActive = false; }; if (m_bSegBActive) { av_write_trailer(m_pFormatCtxB); avformat_close_input(&m_pFormatCtxB); m_bSegBActive = false; }; }; #endif // !SEPARATED_VIDEO_ENCODERS
#endif // !DIRECT_MJPEG_COMPOSING
// if( m_pFormat != NULL ) {
// av_free( m_pFormat );
//};
#endif // OPENCV_VIDEO_OUTPUT
}
bool streamHandler::openSegmentA(void){ if (! m_bSegAActive) { CSTR tAM = getUniqID_MD5(); if (tAM) { sprintf(m_sStreamSegmentInfo[0].scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER); strncpy(m_sStreamSegmentInfo[0].recordMD5, tAM, 32); m_sStreamSegmentInfo[0].recordMD5[32] = (char) 0; free(tAM); m_sStreamSegmentInfo[0].stream_id = m_sStreamData.id; PF_TIMESTAMP ts; getPFTS(&ts); m_sStreamSegmentInfo[0].streamTSS = ts.seconds; m_sStreamSegmentInfo[0].streamTMS = ts.milliseconds; #ifdef DEBUG_EXTRA
char tB[128]; sprintf(tB, "A opened %d.%d", m_sStreamSegmentInfo[0].streamTSS, m_sStreamSegmentInfo[0].streamTMS); LOG(tB); #endif
strncpy(m_sStreamSegmentInfo[0].recordEXT, VIDEO_OUTPUT_CONTAINER, 6); m_sStreamSegmentInfo[0].streamFPS = m_sStreamData.fps; m_sStreamSegmentInfo[0].streamWidth = m_pMaster->getWidh(); m_sStreamSegmentInfo[0].streamHeight = m_pMaster->getHeight(); m_sStreamSegmentInfo[0].eventIDS.clear(); m_sStreamSegmentInfo[0].eventTSS.clear(); m_sStreamSegmentInfo[0].eventTMS.clear(); m_sStreamSegmentInfo[0].eventFrames.clear(); m_sStreamSegmentInfo[0].dataSize = 0; m_sStreamSegmentInfo[0].db_id = 0; #ifdef DIRECT_MJPEG_COMPOSING
m_pOutputFD[0] = fopen(m_sStreamSegmentInfo[0].scratchPath, "wb+"); m_nSegAFrameCounter = 0; m_nSegAShiftFrames = 0; m_bSegAActive = true; m_bSegADelete = true; #else // !DIRECT_MJPEG_COMPOSING
#ifdef OPENCV_VIDEO_OUTPUT
if (m_pEncoderA) { // int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4');
int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G'); #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
m_bAFrameSkeepDivider = m_bWebFrameSkeepDivider; m_bAOutputFPS = m_bInitialOutputFPS / m_bAFrameSkeepDivider; double fps = m_bAOutputFPS; #else
double fps = m_sStreamData.fps; #endif
cv::String mn(m_sStreamSegmentInfo[0].scratchPath); cv::Size fz(m_sStreamData.width, m_sStreamData.height); // open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
if (! m_pEncoderA->open(mn, fourcc, fps, fz)) { LOG_ERROR("Cannot Open Output Segment A!"); return false; #ifdef DEBUG_EXTRA
} else { char tB[256]; sprintf(tB, "VideoStream A is Created [%s] %.2f fps", m_sStreamSegmentInfo[0].scratchPath, fps); LOG(tB); #endif
}; m_bSegAActive = true; m_bSegADelete = true; m_nSegAFrameCounter = 0; m_nSegAShiftFrames = 0; } else { LOG_ERROR("No Encoder(A) Object!"); return false; }; #else // !OPENCV_VIDEO_OUTPUT
// Check if Encoder is Ready
if (m_pFormat == NULL) { return false; }
#ifdef SEPARATED_VIDEO_ENCODERS
if (avformat_alloc_output_context2(&m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0) { LOG_ERROR("Format CTX A alloc error!"); return false; } else { av_dict_set(&m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0); m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; };
m_pVideoStrA = avformat_new_stream(m_pFormatCtxA, m_pVideoACodec); if (m_pVideoStrA == NULL) { avformat_free_context(m_pFormatCtxA); return false; #ifdef DEBUG_EXTRA
} else { LOG("VideoStream A is Created"); #endif
}; const AVRational dst_fps = {m_sStreamData.fps, 1}; m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate = dst_fps; m_pVideoStrA->time_base = m_pCodecACtx->time_base; avcodec_parameters_from_context(m_pVideoStrA->codecpar, m_pCodecACtx); #ifdef DEBUG_EXTRA
LOG("Opening Stream A"); LOG(m_cSegNameA); char tB[128]; sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts); LOG(tB); sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration); LOG(tB); #endif
// if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) {
if (avio_open(&m_pFormatCtxA->pb, m_sStreamSegmentInfo[0].scratchPath, AVIO_FLAG_WRITE) < 0) { LOG_ERROR("Could not open output file."); return m_bSegAActive; }; if (avformat_write_header(m_pFormatCtxA, &m_pFormatOpts) < 0) { LOG_ERROR("Error occurred when writing header to output file."); return m_bSegAActive; }; // m_mFrameCounterProtector.lock();
m_nSegAFrameCounter = 0; m_nSegAShiftFrames = 0; m_bSegAActive = true; m_bSegADelete = true; // m_mFrameCounterProtector.unlock();
#else // SEPARATED_VIDEO_ENCODERS
m_nSegASkippedFrames = m_pVideoStrA->nb_frames + 1; if (m_pVideoStrA->nb_frames) { m_pVideoStrA->nb_frames = 0; m_pVideoStrA->start_time = 0; m_pVideoStrA->first_dts = 0; m_pFormatCtxA->start_time = 0; }; #ifdef DEBUG_EXTRA
LOG("Opening Stream A"); LOG(m_cSegNameA); char tB[128]; sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts); LOG(tB); sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration); LOG(tB); #endif
if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) { LOG_ERROR("Could not open output file."); return m_bSegAActive; }; if (avformat_write_header(m_pFormatCtxA, &m_pFormatOpts) < 0) { LOG_ERROR("Error occurred when writing header to output file."); return m_bSegAActive; }; // m_mFrameCounterProtector.lock();
m_nSegAFrameCounter = 0; m_nSegAShiftFrames = 0; m_bSegAActive = true; m_bSegADelete = true; // m_mFrameCounterProtector.unlock();
#endif // SEPARATED_VIDEO_ENCODERS
#ifdef DEBUG_EXTRA
LOG("Stream A Opened"); #endif
#endif // !OPENCV_VIDEO_OUTPUT
#endif // !DIRECT_MJPEG_COMPOSING
}; }; return m_bSegAActive;}
bool streamHandler::openSegmentB(void){ if (! m_bSegBActive) { CSTR tAM = getUniqID_MD5(); if (tAM) { sprintf(m_sStreamSegmentInfo[1].scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER); strncpy(m_sStreamSegmentInfo[1].recordMD5, tAM, 32); m_sStreamSegmentInfo[1].recordMD5[32] = (char) 0; free(tAM); m_sStreamSegmentInfo[1].stream_id = m_sStreamData.id; PF_TIMESTAMP ts; getPFTS(&ts); m_sStreamSegmentInfo[1].streamTSS = ts.seconds; m_sStreamSegmentInfo[1].streamTMS = ts.milliseconds; #ifdef DEBUG_EXTRA
char tB[128]; sprintf(tB, "B opened %d.%d", m_sStreamSegmentInfo[1].streamTSS, m_sStreamSegmentInfo[1].streamTMS); LOG(tB); #endif
strncpy(m_sStreamSegmentInfo[1].recordEXT, VIDEO_OUTPUT_CONTAINER, 6); m_sStreamSegmentInfo[1].streamFPS = m_sStreamData.fps; m_sStreamSegmentInfo[1].streamWidth = m_pMaster->getWidh(); m_sStreamSegmentInfo[1].streamHeight = m_pMaster->getHeight(); m_sStreamSegmentInfo[1].eventIDS.clear(); m_sStreamSegmentInfo[1].eventTSS.clear(); m_sStreamSegmentInfo[1].eventTMS.clear(); m_sStreamSegmentInfo[1].eventFrames.clear(); m_sStreamSegmentInfo[1].dataSize = 0; m_sStreamSegmentInfo[1].db_id = 0;
#ifdef DIRECT_MJPEG_COMPOSING
m_pOutputFD[1] = fopen(m_sStreamSegmentInfo[1].scratchPath, "wb+"); m_nSegBFrameCounter = 0; m_nSegBShiftFrames = 0; m_bSegBActive = true; m_bSegBDelete = true; #else // !DIRECT_MJPEG_COMPOSING
#ifdef OPENCV_VIDEO_OUTPUT
if (m_pEncoderB) { // int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4');
int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G'); #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
m_bBFrameSkeepDivider = m_bWebFrameSkeepDivider; m_bBOutputFPS = m_bInitialOutputFPS / m_bBFrameSkeepDivider; double fps = m_bBOutputFPS; #else
double fps = m_sStreamData.fps; #endif
cv::String mn(m_sStreamSegmentInfo[1].scratchPath); cv::Size fz(m_sStreamData.width, m_sStreamData.height); // open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
if (! m_pEncoderB->open(mn, fourcc, fps, fz)) { LOG_ERROR("Cannot Open Output Segment B!"); return false; #ifdef DEBUG_EXTRA
} else { char tB[256]; sprintf(tB, "VideoStream B is Created [%s] %.2f fps", m_sStreamSegmentInfo[1].scratchPath, fps); LOG(tB); #endif
}; m_bSegBActive = true; m_bSegBDelete = true; m_nSegBFrameCounter = 0; m_nSegBShiftFrames = 0; } else { LOG_ERROR("No Encoder(B) Object!"); return false; }; #else // !OPENCV
// Check if Encoder is Ready
if (m_pFormat == NULL) { return false; } #ifdef SEPARATED_VIDEO_ENCODERS
if (avformat_alloc_output_context2(&m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0) { LOG_ERROR("Format CTX B alloc error!"); return false; } else { av_dict_set(&m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0); m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; };
m_pVideoStrB = avformat_new_stream(m_pFormatCtxB, m_pVideoBCodec); if (m_pVideoStrB == NULL) { avformat_free_context(m_pFormatCtxB); return false; #ifdef DEBUG_EXTRA
} else { LOG("VideoStream B is Created"); #endif
}; const AVRational dst_fps = {m_sStreamData.fps, 1}; m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps; m_pVideoStrB->time_base = m_pCodecBCtx->time_base; avcodec_parameters_from_context(m_pVideoStrB->codecpar, m_pCodecBCtx); #ifdef DEBUG_EXTRA
LOG("Opening Stream B"); LOG(m_cSegNameB); char tB[128]; sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrB->start_time, m_pVideoStrB->nb_frames, m_pVideoStrB->first_dts); LOG(tB); sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtxB->start_time, m_pFormatCtxB->duration); LOG(tB); #endif
// if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){
if (avio_open(&m_pFormatCtxB->pb, m_sStreamSegmentInfo[1].scratchPath, AVIO_FLAG_WRITE) < 0) { LOG_ERROR("Could not open output file."); avformat_free_context(m_pFormatCtxB); return false; }; if (avformat_write_header(m_pFormatCtxB, &m_pFormatOpts) < 0) { LOG_ERROR("Error occurred when writing header to output file."); avio_close(m_pFormatCtxB->pb); avformat_free_context(m_pFormatCtxB); return false; }; // m_mFrameCounterProtector.lock();
m_nSegBFrameCounter = 0; m_nSegBShiftFrames = 0; m_bSegBActive = true; m_bSegBDelete = true; // m_mFrameCounterProtector.unlock();
#else // SEPARATED_VIDEO_ENCODERS
m_nSegBSkippedFrames = m_pVideoStrB->nb_frames + 1; if (m_pVideoStrB->nb_frames) { m_pVideoStrB->nb_frames = 0; m_pVideoStrB->start_time = 0; m_pVideoStrB->first_dts = 0; m_pFormatCtxB->start_time = 0; }; if (avio_open(&m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE) < 0) { LOG_ERROR("Could not open output file."); return m_bSegBActive; }; if (avformat_write_header(m_pFormatCtxB, &m_pFormatOpts) < 0) { LOG_ERROR("Error occurred when writing header to output file."); return m_bSegBActive; }; // m_mFrameCounterProtector.lock();
m_nSegBFrameCounter = 0; m_nSegBShiftFrames = 0; m_bSegBActive = true; m_bSegBDelete = true; // m_mFrameCounterProtector.unlock();
#endif // SEPARATED_VIDEO_ENCODERS
#ifdef DEBUG_EXTRA
LOG("Stream B Opened"); #endif
#endif // !OPENCV_VIDEO_OUTPUT
#endif // !DIRECT_MJPEG_COMPOSING
}; }; return m_bSegBActive;}
bool streamHandler::initVideoOutput(){
#ifdef EVE_ENABLE_EASE_OUTPUT_FPS
m_bAFrameSkeepDivider = m_bBFrameSkeepDivider = 1; m_bAFrameSkeepDividerCounter = m_bBFrameSkeepDividerCounter = 0; m_bCurrentOutputFPS = m_bInitialOutputFPS = m_sStreamData.fps;
m_nAPreAlarmFrames = (PRE_ALARM_TIME_MILSECONDS * m_bAOutputFPS) / 1000; m_nAPostAlarmFrames = (POST_ALARM_TIME_MILSECONDS * m_bAOutputFPS) / 1000; m_nASegmentLimitFrames = (ENCODING_SEGMENT_MILSECONDS * m_bAOutputFPS) / 1000; m_nAHardLimitFrames = (ENCODING_SEGMENT_LIMIT_MILSECONDS * m_bAOutputFPS) / 1000;
m_nBPreAlarmFrames = (PRE_ALARM_TIME_MILSECONDS * m_bBOutputFPS) / 1000; m_nBPostAlarmFrames = (POST_ALARM_TIME_MILSECONDS * m_bBOutputFPS) / 1000; m_nBSegmentLimitFrames = (ENCODING_SEGMENT_MILSECONDS * m_bBOutputFPS) / 1000; m_nBHardLimitFrames = (ENCODING_SEGMENT_LIMIT_MILSECONDS * m_bBOutputFPS) / 1000; #else
m_nPreAlarmFrames = (PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps) / 1000; m_nPostAlarmFrames = (POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps) / 1000; m_nSegmentLimitFrames = (ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps) / 1000; m_nHardLimitFrames = (ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps) / 1000; #endif
#ifndef DIRECT_MJPEG_COMPOSING
#ifdef OPENCV_VIDEO_OUTPUT
m_pEncoderA = new cv::VideoWriter(); if (m_pEncoderA == NULL) { LOG_ERROR("Encoder A Create Failure!"); return false; };
m_pEncoderA->set(cv::VIDEOWRITER_PROP_QUALITY, 10.0); m_pEncoderA->set(cv::VIDEOWRITER_PROP_NSTRIPES, -1.0);
m_pEncoderB = new cv::VideoWriter(); if (m_pEncoderA == NULL) { LOG_ERROR("Encoder B Create Failure!"); return false; };
m_pEncoderB->set(cv::VIDEOWRITER_PROP_QUALITY, 10.0); m_pEncoderB->set(cv::VIDEOWRITER_PROP_NSTRIPES, -1.0);
#else
if (! initLibAV()) { return false; }
m_pFormat = av_guess_format(VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL);
if (m_pFormat == NULL) { LOG_ERROR("Out VideoFormat Not Found!"); return false; #ifdef DEBUG_EXTRA
} else { LOG("Output video Format"); LOG(VIDEO_OUTPUT_CONTAINER); #endif
};
#ifdef SEPARATED_VIDEO_ENCODERS
/* Stream A */ m_pVideoACodec = avcodec_find_encoder(VIDEO_OUTPUT_CODEC); if (m_pVideoACodec == NULL) { LOG_ERROR("Encoder Video Codec Not Found!"); return false; #ifdef DEBUG_EXTRA
} else { LOG("Video Encoder A Created"); #endif
}; m_pCodecACtx = avcodec_alloc_context3(m_pVideoACodec); if (m_pCodecACtx == NULL) { LOG_ERROR("Video Encoder A Context Memory Allocation Error!"); av_free(m_pVideoACodec); avformat_free_context(m_pFormatCtxA); return false; #ifdef DEBUG_EXTRA
} else { LOG("Video Encoder Context A Allocated"); #endif
}; /* Stream B */ m_pVideoBCodec = avcodec_find_encoder(VIDEO_OUTPUT_CODEC); if (m_pVideoBCodec == NULL) { LOG_ERROR("Out VideoCodec Not Found!"); av_free(m_pVideoACodec); return false; #ifdef DEBUG_EXTRA
} else { LOG("Video Encoder B Created"); #endif
}; m_pCodecBCtx = avcodec_alloc_context3(m_pVideoBCodec); if (m_pCodecBCtx == NULL) { LOG_ERROR("Video Encoder B Context Memory Allocation Error!"); av_free(m_pVideoACodec); av_free(m_pVideoBCodec); avformat_free_context(m_pFormatCtxA); avformat_free_context(m_pFormatCtxB); return false; #ifdef DEBUG_EXTRA
} else { LOG("Video Encoder Context B Allocated"); #endif
};
m_pCodecACtx->codec_id = VIDEO_OUTPUT_CODEC; m_pCodecACtx->codec_type = AVMEDIA_TYPE_VIDEO; m_pCodecACtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; m_pCodecACtx->bit_rate = VIDEO_OUTPUT_BITRATE; m_pCodecACtx->max_b_frames = 1; m_pCodecACtx->width = m_pMaster->m_sEmbedVideoData.width; m_pCodecACtx->height = m_pMaster->m_sEmbedVideoData.height; m_pCodecACtx->time_base.num = 1; m_pCodecACtx->time_base.den = m_sStreamData.fps; m_pCodecACtx->framerate.num = m_sStreamData.fps; m_pCodecACtx->framerate.den = 1;
m_pCodecBCtx->codec_id = VIDEO_OUTPUT_CODEC; m_pCodecBCtx->codec_type = AVMEDIA_TYPE_VIDEO; m_pCodecBCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; m_pCodecBCtx->bit_rate = VIDEO_OUTPUT_BITRATE; m_pCodecBCtx->max_b_frames = 1; m_pCodecBCtx->width = m_pMaster->m_sEmbedVideoData.width; m_pCodecBCtx->height = m_pMaster->m_sEmbedVideoData.height; m_pCodecBCtx->time_base.num = 1; m_pCodecBCtx->time_base.den = m_sStreamData.fps; m_pCodecBCtx->framerate.num = m_sStreamData.fps; m_pCodecBCtx->framerate.den = 1;
// https://pastebin.com/yG37YhWW
// https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec
// G@ avcodec encode NALU mp4
#if (LIBAVCODEC_VERSION_MAJOR > 54)
////m_pCodecACtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
#endif
#if (LIBAVCODEC_VERSION_MAJOR > 54)
////m_pCodecBCtx->codec_tag = av_codec_get_tag( m_pFormatCtxB->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
#endif
m_pFormatOpts = NULL;
// https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate
if ((m_pCodecACtx->codec_id == AV_CODEC_ID_H264) || (m_pCodecACtx->codec_id == AV_CODEC_ID_H265)) { #ifdef DEBUG_EXTRA
LOG("Begin Options!"); #endif
// Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
// Set format's privater options, to be passed to avformat_write_header()
/*
mp4 muxer AVOptions: -movflags E..... MOV muxer flags (default 0) rtphint E..... Add RTP hint tracks empty_moov E..... Make the initial moov atom empty (not supported by QuickTime) frag_keyframe E..... Fragment at video keyframes separate_moof E..... Write separate moof/mdat atoms for each track frag_custom E..... Flush fragments on caller requests isml E..... Create a live smooth streaming feed (for pushing to a publishing point) faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file omit_tfhd_offset E..... Omit the base data offset in tfhd atoms delay_moov ?? -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0) -rtpflags E..... RTP muxer flags (default 0) latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263 skip_rtcp E..... Don't send RTCP sender reports h264_mode0 E..... Use mode 0 for H264 in RTP send_bye E..... Send RTCP BYE packets when finishing -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1) -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1) -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1) -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0) -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0) -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0) -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0) -use_editlist E..... use edit list (from -1 to 1) (default -1) -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
*/ if (av_dict_set(&m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0) < 0) { LOG_ERROR("av_dict_set movflags!"); #ifdef DEBUG_EXTRA
} else { LOG("MOV FLAG SET!"); #endif
};
// if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
// LOG_ERROR( "av_dict_set live!" );
// };
// default brand is "isom", which fails on some devices
if (av_dict_set(&m_pFormatOpts, "brand", "mp42", 0) < 0) { LOG_ERROR("av_dict_set brand!"); }; // m_pCodecCtx->max_b_frames = 1;
// m_pCodecCtx->level = 31;
m_pCodecACtx->gop_size = m_sStreamData.fps << 1; // VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
/// P-frames, generated by referencing data from prev and future frames.
/// [Compression up, CPU usage up]
/// [use 3/gop]
m_pCodecACtx->max_b_frames = 5;
/// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
/// [use 3?5 ref per P]
m_pCodecACtx->refs = 3;
/// Compression efficiency (slower -> better quality + higher cpu%)
/// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
/// Set this option to "ultrafast" is critical for realtime encoding
av_opt_set(m_pCodecACtx->priv_data, "preset", "ultrafast", 0); // av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
// av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
/// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
/// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
av_opt_set(m_pCodecACtx->priv_data, "crf", "32", 0);
/// Change settings based upon the specifics of input
/// [psnr, ssim, grain, zerolatency, fastdecode, animation]
/// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
av_opt_set(m_pCodecACtx->priv_data, "tune", "zerolatency", 0);
/// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
/// Because Quicktime (ie. iOS) doesn't support this option
av_opt_set(m_pCodecACtx->priv_data, "b-pyramid", "0", 0); #ifdef DEBUG_EXTRA
LOG("End Options!"); #endif
} else { if (m_pFormat->flags & AVFMT_GLOBALHEADER) { m_pCodecACtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; } };
if ((m_pCodecBCtx->codec_id == AV_CODEC_ID_H264) || (m_pCodecBCtx->codec_id == AV_CODEC_ID_H265)) { #ifdef DEBUG_EXTRA
LOG("Begin Options!"); #endif
// Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
// Set format's privater options, to be passed to avformat_write_header()
/*
mp4 muxer AVOptions: -movflags E..... MOV muxer flags (default 0) rtphint E..... Add RTP hint tracks empty_moov E..... Make the initial moov atom empty (not supported by QuickTime) frag_keyframe E..... Fragment at video keyframes separate_moof E..... Write separate moof/mdat atoms for each track frag_custom E..... Flush fragments on caller requests isml E..... Create a live smooth streaming feed (for pushing to a publishing point) faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file omit_tfhd_offset E..... Omit the base data offset in tfhd atoms delay_moov ?? -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0) -rtpflags E..... RTP muxer flags (default 0) latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263 skip_rtcp E..... Don't send RTCP sender reports h264_mode0 E..... Use mode 0 for H264 in RTP send_bye E..... Send RTCP BYE packets when finishing -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1) -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1) -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1) -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0) -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0) -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0) -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0) -use_editlist E..... use edit list (from -1 to 1) (default -1) -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
*/ // m_pCodecCtx->max_b_frames = 1;
// m_pCodecCtx->level = 31;
m_pCodecBCtx->gop_size = m_sStreamData.fps << 1; // VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
/// P-frames, generated by referencing data from prev and future frames.
/// [Compression up, CPU usage up]
/// [use 3/gop]
m_pCodecBCtx->max_b_frames = 5;
/// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
/// [use 3?5 ref per P]
m_pCodecBCtx->refs = 3;
/// Compression efficiency (slower -> better quality + higher cpu%)
/// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
/// Set this option to "ultrafast" is critical for realtime encoding
av_opt_set(m_pCodecBCtx->priv_data, "preset", "ultrafast", 0); // av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
// av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
/// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
/// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
av_opt_set(m_pCodecBCtx->priv_data, "crf", "32", 0);
/// Change settings based upon the specifics of input
/// [psnr, ssim, grain, zerolatency, fastdecode, animation]
/// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
av_opt_set(m_pCodecBCtx->priv_data, "tune", "zerolatency", 0);
/// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
/// Because Quicktime (ie. iOS) doesn't support this option
av_opt_set(m_pCodecBCtx->priv_data, "b-pyramid", "0", 0); #ifdef DEBUG_EXTRA
LOG("End Options!"); #endif
} else { if (m_pFormat->flags & AVFMT_GLOBALHEADER) { m_pCodecBCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; } };
const AVRational dst_fps = {m_sStreamData.fps, 1};
#ifdef DEBUG_EXTRA
char TB[129]; sprintf(TB, "TimeBaseA: num[%d]/den[%d]", m_pCodecACtx->time_base.num, m_pCodecACtx->time_base.den); LOG(TB); sprintf(TB, "TimeBaseB: num[%d]/den[%d]", m_pCodecBCtx->time_base.num, m_pCodecBCtx->time_base.den); LOG(TB); #endif
////m_pVideoStrA->time_base = m_pCodecACtx->time_base;
////m_pVideoStrB->time_base = m_pCodecBCtx->time_base;
// avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec );
// m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width;
// m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height;
// m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
// m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
//// m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate =
////dst_fps;
// avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec );
// m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width;
// m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height;
// m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
// m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
//// m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate =
////dst_fps;
// if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
// if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
//// avcodec_parameters_from_context( m_pVideoStrA->codecpar,
////m_pCodecACtx );
// m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
// m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata;
// m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size;
//// avcodec_parameters_from_context( m_pVideoStrB->codecpar,
////m_pCodecBCtx );
// m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
// m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata;
// m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size;
if (avcodec_is_open(m_pCodecACtx) == 0) { LOG("output codec context is closed, opening"); if (avcodec_open2(m_pCodecACtx, m_pVideoACodec, NULL) < 0) { LOG_ERROR("Error opening2 encoder"); return false; #ifdef DEBUG_EXTRA
} else { LOG("output codec context is opened"); #endif
};
#ifdef DEBUG_EXTRA
} else { LOG("output codec context is already opened"); #endif
};
if (avcodec_is_open(m_pCodecBCtx) == 0) { LOG("output codec context is closed, opening"); if (avcodec_open2(m_pCodecBCtx, m_pVideoBCodec, NULL) < 0) { LOG_ERROR("Error opening2 encoder"); return false; #ifdef DEBUG_EXTRA
} else { LOG("output codec context is opened"); #endif
};
#ifdef DEBUG_EXTRA
} else { LOG("output codec context is already opened"); #endif
}; #else // SEPARATED_VIDEO_ENCODERS
if (avformat_alloc_output_context2(&m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0) { LOG_ERROR("Format CTX A alloc error!"); return false; } else { av_dict_set(&m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0); m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; };
if (avformat_alloc_output_context2(&m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0) { LOG_ERROR("Format CTX B alloc error!"); avformat_free_context(m_pFormatCtxA); return false; } else { av_dict_set(&m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0); m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; }; m_pVideoCodec = avcodec_find_encoder(VIDEO_OUTPUT_CODEC); if (m_pVideoCodec == NULL) { LOG_ERROR("Output VideoCodec Not Found!"); avformat_free_context(m_pFormatCtxA); avformat_free_context(m_pFormatCtxB); return false; #ifdef DEBUG_EXTRA
} else { LOG("Output Video Codec Found"); #endif
};
m_pCodecCtx = avcodec_alloc_context3(m_pVideoCodec); if (m_pCodecCtx == NULL) { LOG_ERROR("Out VideoCodec Context Memory Allocation Error"); av_free(m_pVideoCodec); avformat_free_context(m_pFormatCtxA); avformat_free_context(m_pFormatCtxB); return false; #ifdef DEBUG_EXTRA
} else { LOG("Out Codec Context3 Allocated"); #endif
}; m_pVideoStrA = avformat_new_stream(m_pFormatCtxA, m_pVideoCodec); if (m_pVideoStrA == NULL) { LOG_ERROR("VideoStream A Not Created!"); avcodec_free_context(&m_pCodecCtx); av_free(m_pCodecCtx); av_free(m_pVideoCodec); // avformat_close_input ( &m_pFormatCtxA );
// avformat_close_input ( &m_pFormatCtxB );
avformat_free_context(m_pFormatCtxA); avformat_free_context(m_pFormatCtxB); return false; #ifdef DEBUG_EXTRA
} else { LOG("VideoStream A is Created"); #endif
};
m_pVideoStrB = avformat_new_stream(m_pFormatCtxB, m_pVideoCodec); if (m_pVideoStrB == NULL) { LOG_ERROR("VideoStream B Not Created!");
avcodec_free_context(&m_pCodecCtx); av_free(m_pCodecCtx); av_free(m_pVideoCodec); // avformat_close_input ( &m_pFormatCtxA );
// avformat_close_input ( &m_pFormatCtxB );
avformat_free_context(m_pFormatCtxA); avformat_free_context(m_pFormatCtxB); return false; #ifdef DEBUG_EXTRA
} else { LOG("VideoStream B is Created"); #endif
}; m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC; m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO; m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE; // m_pCodecCtx->thread_count = 1;
// m_pCodecCtx->bit_rate_tolerance = 1;
// m_pCodecCtx->global_quality = 100;
// m_pCodecCtx->compression_level = 2;
m_pCodecCtx->max_b_frames = 1; m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width; m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height; m_pCodecCtx->time_base.num = 1; m_pCodecCtx->time_base.den = m_sStreamData.fps; m_pCodecCtx->framerate.num = m_sStreamData.fps; m_pCodecCtx->framerate.den = 1;
// https://pastebin.com/yG37YhWW
// https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec
// G@ avcodec encode NALU mp4
#if (LIBAVCODEC_VERSION_MAJOR > 54)
m_pCodecCtx->codec_tag = av_codec_get_tag(m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC); #endif
m_pFormatOpts = NULL;
// https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate
if ((m_pCodecCtx->codec_id == AV_CODEC_ID_H264) || (m_pCodecCtx->codec_id == AV_CODEC_ID_H265)) { #ifdef DEBUG_EXTRA
LOG("Begin Options!"); #endif
// Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
// Set format's privater options, to be passed to avformat_write_header()
/*
mp4 muxer AVOptions: -movflags E..... MOV muxer flags (default 0) rtphint E..... Add RTP hint tracks empty_moov E..... Make the initial moov atom empty (not supported by QuickTime) frag_keyframe E..... Fragment at video keyframes separate_moof E..... Write separate moof/mdat atoms for each track frag_custom E..... Flush fragments on caller requests isml E..... Create a live smooth streaming feed (for pushing to a publishing point) faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file omit_tfhd_offset E..... Omit the base data offset in tfhd atoms delay_moov ?? -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0) -rtpflags E..... RTP muxer flags (default 0) latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263 skip_rtcp E..... Don't send RTCP sender reports h264_mode0 E..... Use mode 0 for H264 in RTP send_bye E..... Send RTCP BYE packets when finishing -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1) -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1) -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1) -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0) -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0) -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0) -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0) -use_editlist E..... use edit list (from -1 to 1) (default -1) -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
*/ if (av_dict_set(&m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0) < 0) { LOG_ERROR("av_dict_set movflags!"); #ifdef DEBUG_EXTRA
} else { LOG("MOV FLAG SET!"); #endif
};
// if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
// LOG_ERROR( "av_dict_set live!" );
// };
// default brand is "isom", which fails on some devices
if (av_dict_set(&m_pFormatOpts, "brand", "mp42", 0) < 0) { LOG_ERROR("av_dict_set brand!"); }; // m_pCodecCtx->max_b_frames = 1;
// m_pCodecCtx->level = 31;
m_pCodecCtx->gop_size = m_sStreamData.fps << 1; // VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
/// P-frames, generated by referencing data from prev and future frames.
/// [Compression up, CPU usage up]
/// [use 3/gop]
m_pCodecCtx->max_b_frames = 5;
/// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
/// [use 3?5 ref per P]
m_pCodecCtx->refs = 3;
/// Compression efficiency (slower -> better quality + higher cpu%)
/// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
/// Set this option to "ultrafast" is critical for realtime encoding
av_opt_set(m_pCodecCtx->priv_data, "preset", "ultrafast", 0); // av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
// av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
/// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
/// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
av_opt_set(m_pCodecCtx->priv_data, "crf", "32", 0);
/// Change settings based upon the specifics of input
/// [psnr, ssim, grain, zerolatency, fastdecode, animation]
/// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
av_opt_set(m_pCodecCtx->priv_data, "tune", "zerolatency", 0);
/// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
/// Because Quicktime (ie. iOS) doesn't support this option
av_opt_set(m_pCodecCtx->priv_data, "b-pyramid", "0", 0); #ifdef DEBUG_EXTRA
LOG("End Options!"); #endif
} else { if (m_pFormat->flags & AVFMT_GLOBALHEADER) { m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; } };
const AVRational dst_fps = {m_sStreamData.fps, 1};
#ifdef DEBUG_EXTRA
char TB[129]; sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den); LOG(TB); #endif
m_pVideoStrA->time_base = m_pCodecCtx->time_base; m_pVideoStrB->time_base = m_pCodecCtx->time_base;
// avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec );
// m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width;
// m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height;
// m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
// m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
m_pVideoStrA->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
// avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec );
// m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width;
// m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height;
// m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
// m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
// if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
// if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
avcodec_parameters_from_context(m_pVideoStrA->codecpar, m_pCodecCtx); // m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
// m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata;
// m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size;
avcodec_parameters_from_context(m_pVideoStrB->codecpar, m_pCodecCtx); // m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
// m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata;
// m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size;
if (avcodec_is_open(m_pCodecCtx) == 0) { LOG("output codec context is closed, opening"); if (avcodec_open2(m_pCodecCtx, m_pVideoCodec, NULL) < 0) { LOG_ERROR("Error opening2 encoder"); return false; #ifdef DEBUG_EXTRA
} else { LOG("output codec context is opened"); #endif
};
#ifdef DEBUG_EXTRA
} else { LOG("output codec context is already opened"); #endif
}; #endif // SEPARATED_VIDEO_ENCODERS
m_pConvertCtx = sws_getContext(m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, AV_PIX_FMT_BGR24, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, VIDEO_OUTPUT_PIX_FMT, SWS_FAST_BILINEAR, NULL, NULL, NULL); if (m_pConvertCtx == NULL) { return false; } m_pAVFrame = av_frame_alloc(); if (m_pAVFrame == NULL) { return false; }; m_pOutBuffer = (uint8_t *) av_malloc(av_image_get_buffer_size(VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, BUFFER_ALIGN)); if (m_pOutBuffer == NULL) { return false; }; m_pAVFrame->width = m_pMaster->m_sEmbedVideoData.width; m_pAVFrame->height = m_pMaster->m_sEmbedVideoData.height; m_pAVFrame->format = VIDEO_OUTPUT_PIX_FMT; // av_frame_get_buffer( m_pAVFrame, 0 );
av_image_fill_arrays(m_pAVFrame->data, m_pAVFrame->linesize, m_pOutBuffer, VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, 1);
// av_frame_make_writable( m_pAVFrame );
#endif // !OPENCV_VIDEO_OUTPUT
#endif // !DIRECT_MJPEG_COMPOSING
return init();}
// encoding thread
void streamHandler::m_fThreadProc(void){ //char tB[128];
// #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
size_t nQueueSize; // #endif
#ifndef DIRECT_MJPEG_COMPOSING
#ifndef OPENCV_VIDEO_OUTPUT
AVPacket mPacket; int bGotPacket; int rVal = 0; av_init_packet(&mPacket); #endif
#endif
pthread_setname_np(pthread_self(), "VideoStream"); while (m_bThreadStatus != TH_ENDED) { // At the begining All streams are closed --> try to Open
if (m_bThreadStatus < TH_WORKING) { if (! openSegmentA()) { m_bThreadStatus = TH_ENDED; LOG_ERROR("Can not Open Seg A for first time!"); continue; }; // if( !openSegmentB() ){
// m_bThreadStatus = TH_ENDED;
// continue;
// };
m_bThreadStatus = TH_WORKING; continue; };
m_mEncodingQueueProtector.lock(); nQueueSize = m_qEncodingQueue.size(); m_mEncodingQueueProtector.unlock();
#ifdef EVE_ENABLE_EASE_OUTPUT_FPS
if (nQueueSize > EVE_EASE_FPS_QUEUE_SIZE_MAXIMUM) { // Just in case allredy applied to a streams
if (m_bWebFrameSkeepDivider == m_bAFrameSkeepDivider && m_bWebFrameSkeepDivider == m_bBFrameSkeepDivider) { m_bWebFrameSkeepDivider++; if (m_bWebFrameSkeepDivider > EVE_EASE_FPS_DIVIDER_MAXIMUM) { m_bWebFrameSkeepDivider = EVE_EASE_FPS_DIVIDER_MAXIMUM; } else { #ifdef DEBUG_EXTRA
LOG("Video Quality Degraded!"); #endif
EVENT_CONTAINER * bEVT = createBasicEvent(m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_VIDEO_FPS_DEGRADED, NULL, NULL, NULL); if (bEVT) { basicEventHeap::getInstance()->broadcast(bEVT); } else { LOG_ERROR("Event Creation failure!"); } }; }; } else if (nQueueSize < EVE_EASE_FPS_QUEUE_SIZE_MINIMUM) { // Just in case allredy applied to a streams
if (m_bWebFrameSkeepDivider == m_bAFrameSkeepDivider && m_bWebFrameSkeepDivider == m_bBFrameSkeepDivider) { m_bWebFrameSkeepDivider--; if (m_bWebFrameSkeepDivider < EVE_EASE_FPS_DIVIDER_MINIMUM) { m_bWebFrameSkeepDivider = EVE_EASE_FPS_DIVIDER_MINIMUM; } else { #ifdef DEBUG_EXTRA
LOG("Video Quality Upgraded!"); #endif
EVENT_CONTAINER * bEVT = createBasicEvent(m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_VIDEO_FPS_RAISED, NULL, NULL, NULL); if (bEVT) { basicEventHeap::getInstance()->broadcast(bEVT); } else { LOG_ERROR("Event Creation failure!"); } }; }; }; #endif // EVE_ENABLE_EASE_OUTPUT_FPS
if (nQueueSize) { m_mEncodingQueueProtector.lock(); ENCODING_BUFFER * tData = m_qEncodingQueue.front(); if (tData) { m_qEncodingQueue.pop(); m_mEncodingQueueProtector.unlock(); #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
bool bSkeepA = tData->flag_sa; bool bSkeepB = tData->flag_sb; #endif
#ifdef DIRECT_MJPEG_COMPOSING
#ifdef EVE_ENABLE_EASE_OUTPUT_FPS
if (! bSkeepA) #endif
if (m_bSegAActive) { if (m_pOutputFD[0]) { fwrite(tData->data, 1, tData->size, m_pOutputFD[0]); m_mFrameCounterProtector.lock(); m_nSegAFrameCounter++; m_mFrameCounterProtector.unlock(); }; } #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
if (! bSkeepB) #endif
if (m_bSegBActive) { if (m_pOutputFD[1]) { fwrite(tData->data, 1, tData->size, m_pOutputFD[1]); m_mFrameCounterProtector.lock(); m_nSegBFrameCounter++; m_mFrameCounterProtector.unlock(); }; } // Don't free tData->data since is pointer on static data
free(tData->data); #else // !DIRECT_MJPEG_COMPOSING
#ifdef OPENCV_VIDEO_OUTPUT
cv::Mat image(tData->rows, tData->cols, CV_8UC3); memcpy(image.data, tData->data, tData->size); free(tData->data); #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
if (! bSkeepA) #endif
if (m_bSegAActive) { if (m_pEncoderA->isOpened()) { m_pEncoderA->write(image); m_mFrameCounterProtector.lock(); m_nSegAFrameCounter++; m_mFrameCounterProtector.unlock(); }; } #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
if (! bSkeepB) #endif
if (m_bSegBActive) { if (m_pEncoderB->isOpened()) { m_pEncoderB->write(image); m_mFrameCounterProtector.lock(); m_nSegBFrameCounter++; m_mFrameCounterProtector.unlock(); }; } #else //! OPENCV_VIDEO_OUTPUT
// av_frame_make_writable( m_pAVFrame );
// m_qEncodingQueue.pop();
// m_mEncodingQueueProtector.unlock();
sws_scale(m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize); free(tData->data[0]); /*
AV_PICTURE_TYPE_NONE Undefined. AV_PICTURE_TYPE_I Intra. AV_PICTURE_TYPE_P Predicted. AV_PICTURE_TYPE_B Bi-dir predicted. AV_PICTURE_TYPE_S S(GMC)-VOP MPEG4. AV_PICTURE_TYPE_SI Switching Intra. AV_PICTURE_TYPE_SP Switching Predicted. AV_PICTURE_TYPE_BI BI type.
*/ if ((m_nGlobalFrameCounter % m_sStreamData.fps) == 0) { m_pAVFrame->key_frame = 1; m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I; } else { m_pAVFrame->key_frame = 0; m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_NONE; }; m_pAVFrame->pts = m_nGlobalFrameCounter + 1; #ifdef SEPARATED_VIDEO_ENCODERS
if (m_bSegAActive) { rVal = avcodec_send_frame(m_pCodecACtx, m_pAVFrame); } if (m_bSegBActive) { rVal = avcodec_send_frame(m_pCodecBCtx, m_pAVFrame); } #else //! SEPARATED_VIDEO_ENCODERS
rVal = avcodec_send_frame(m_pCodecCtx, m_pAVFrame); #endif //! SEPARATED_VIDEO_ENCODERS
#endif //! OPENCV_VIDEO_OUTPUT
#endif //! DIRECT_MJPEG_COMPOSING
free(tData); m_mFrameCounterProtector.lock(); m_nGlobalFrameCounter++; m_mFrameCounterProtector.unlock(); } else { m_mEncodingQueueProtector.unlock(); } }; // Test Commands!
m_mCurrentOperationProtector.lock(); switch (m_bCOP) { case 0x01: { #ifdef DEBUG_EXTRA
LOG("Actual Closing Video Stream A!"); LOG(m_sStreamSegmentInfo[0].scratchPath); #endif
m_bSegAActive = false; if (! m_bSegADelete) { #ifdef DIRECT_MJPEG_COMPOSING
if (m_pOutputFD[0]) { fclose(m_pOutputFD[0]); m_pOutputFD[0] = NULL; }; #else //! DIRECT_MJPEG_COMPOSING
#ifdef OPENCV_VIDEO_OUTPUT
if (m_pEncoderA->isOpened()) { m_pEncoderA->release(); #ifdef DEBUG_EXTRA
} else { LOG(" Encoder A is NOT Opened!"); #endif
}; #else //! OPENCV_VIDEO_OUTPUT
av_write_trailer(m_pFormatCtxA); avio_close(m_pFormatCtxA->pb); #endif //! OPENCV_VIDEO_OUTPUT
#endif //! DIRECT_MJPEG_COMPOSING
EVENT_CONTAINER * bEVT = createBasicEvent(m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[0]); if (bEVT) { basicEventHeap::getInstance()->broadcast(bEVT); } else { LOG_ERROR("Event Creation failure!"); } #ifdef DEBUG_EXTRA
LOG("Stream A is Saved"); #endif
} else { #ifdef DIRECT_MJPEG_COMPOSING
if (m_pOutputFD[0]) { fclose(m_pOutputFD[0]); m_pOutputFD[0] = NULL; }; #else // !DIRECT_MJPEG_COMPOSING
#ifdef OPENCV_VIDEO_OUTPUT
if (m_pEncoderA->isOpened()) { m_pEncoderA->release(); #ifdef DEBUG_EXTRA
} else { LOG(" Encoder A is NOT Opened!"); #endif
}; #else // !OPENCV
#ifdef EVE_DONT_DELETE_SEGMENTS
av_write_trailer(m_pFormatCtxA); #endif
avio_close(m_pFormatCtxA->pb); #endif // !OPENCV_VIDEO_OUTPUT
#endif // !DIRECT_MJPEG_COMPOSING
#ifndef EVE_DONT_DELETE_SEGMENTS
unlink(m_sStreamSegmentInfo[0].scratchPath); #endif
#ifdef DEBUG_EXTRA
LOG("Stream A is Closed!"); #endif
}; #ifndef DIRECT_MJPEG_COMPOSING
#ifndef OPENCV_VIDEO_OUTPUT
#ifdef SEPARATED_VIDEO_ENCODERS
#ifdef DEBUG_EXTRA
LOG("Del FCTX"); #endif
avformat_free_context(m_pFormatCtxA); m_pVideoStrA = NULL; #ifdef DEBUG_EXTRA
LOG("Del FCTX DONE"); #endif
#endif // SEPARATED_VIDEO_ENCODERS
#endif // !OPENCV
#endif // !DIRECT_MJPEG_COMPOSING
break; }; case 0x02: { #ifdef DEBUG_EXTRA
LOG("Actual Closing Video Stream B!"); LOG(m_sStreamSegmentInfo[1].scratchPath); #endif
m_bSegBActive = false; if (! m_bSegBDelete) { #ifdef DIRECT_MJPEG_COMPOSING
if (m_pOutputFD[1]) { fclose(m_pOutputFD[1]); m_pOutputFD[1] = NULL; }; #else // !DIRECT_MJPEG_COMPOSING
#ifdef OPENCV_VIDEO_OUTPUT
if (m_pEncoderB->isOpened()) { m_pEncoderB->release(); #ifdef DEBUG_EXTRA
} else { LOG(" Encoder B is NOT Opened!"); #endif
}; #else // !OpenCV
av_write_trailer(m_pFormatCtxB); avio_close(m_pFormatCtxB->pb); #endif // !OPENCV_VIDEO_OUTPUT
#endif // !DIRECT_MJPEG_COMPOSING
EVENT_CONTAINER * bEVT = createBasicEvent(m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[1]); if (bEVT) { basicEventHeap::getInstance()->broadcast(bEVT); } else { LOG_ERROR("Event Creation failure!"); } #ifdef DEBUG_EXTRA
LOG("Stream B is Saved");
#endif
} else { #ifdef DIRECT_MJPEG_COMPOSING
if (m_pOutputFD[1]) { fclose(m_pOutputFD[1]); m_pOutputFD[1] = NULL; }; #else
#ifdef OPENCV_VIDEO_OUTPUT
if (m_pEncoderB->isOpened()) { m_pEncoderB->release(); #ifdef DEBUG_EXTRA
} else { LOG(" Encoder B is NOT Opened!"); #endif
}; #else // !OPenCV
#ifdef EVE_DONT_DELETE_SEGMENTS
av_write_trailer(m_pFormatCtxB); #endif
avio_close(m_pFormatCtxB->pb); #endif // !OPENCV_VIDEO_OUTPUT
#endif // !DIRECT_MJPEG_COMPOSING
#ifndef EVE_DONT_DELETE_SEGMENTS
unlink(m_sStreamSegmentInfo[1].scratchPath); #endif
#ifdef DEBUG_EXTRA
LOG("Stream B is Closed!"); #endif
}; #ifndef DIRECT_MJPEG_COMPOSING
#ifndef OPENCV_VIDEO_OUTPUT
#ifdef SEPARATED_VIDEO_ENCODERS
avformat_free_context(m_pFormatCtxB); m_pVideoStrB = NULL; #endif // SEPARATED_VIDEO_ENCODERS
#endif // !OPENCV
#endif // !DIRECT_MJPEG_COMPOSING
break; }; }; m_bCOP = 0; m_mCurrentOperationProtector.unlock(); //};
#ifndef DIRECT_MJPEG_COMPOSING
#ifndef OPENCV_VIDEO_OUTPUT
#ifdef SEPARATED_VIDEO_ENCODERS
do { mPacket.data = NULL; mPacket.size = 0; rVal = avcodec_receive_packet(m_pCodecACtx, &mPacket); if (rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF) { break; } else if (rVal < 0) { LOG_ERROR("Error during encoding "); m_bThreadStatus = TH_ENDED; break; }; if (! rVal) { if (m_bSegAActive) { mPacket.stream_index = m_pVideoStrA->index; mPacket.duration = 1; m_mFrameCounterProtector.lock(); m_nSegAFrameCounter++; m_mFrameCounterProtector.unlock(); mPacket.pts = av_rescale_q(m_nSegAFrameCounter, m_pCodecACtx->time_base, m_pVideoStrA->time_base); // mPacket.pts = AV_NOPTS_VALUE;
// mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
mPacket.dts = mPacket.pts; int rc = av_write_frame(m_pFormatCtxA, &mPacket); if (rc < 0) { // if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) {
m_bThreadStatus = TH_ENDED; LOG_ERROR("Trouble with Video Output A!"); av_strerror(rc, tB, 128); LOG_ERROR(tB); break; // continue (changed since embed into do-while)
}; }; if (m_bSegBActive) { mPacket.stream_index = m_pVideoStrB->index; mPacket.duration = 1; m_mFrameCounterProtector.lock(); m_nSegBFrameCounter++; m_mFrameCounterProtector.unlock(); mPacket.pts = av_rescale_q(m_nSegBFrameCounter, m_pCodecBCtx->time_base, m_pVideoStrB->time_base); // mPacket.pts = AV_NOPTS_VALUE;
// mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base );
mPacket.dts = mPacket.pts; int rc = av_write_frame(m_pFormatCtxB, &mPacket); if (rc < 0) { // if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) {
m_bThreadStatus = TH_ENDED; LOG_ERROR("Trouble with Video Output B!"); av_strerror(rc, tB, 128); LOG_ERROR(tB); break; // continue (changed since embed into do-while)
}; }; av_packet_unref(&mPacket); }; } while (rVal >= 0 && m_bThreadStatus != TH_ENDED); #else // ! SEPARATED_VIDEO_ENCODERS
do { mPacket.data = NULL; mPacket.size = 0; rVal = avcodec_receive_packet(m_pCodecCtx, &mPacket); if (rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF) { break; } else if (rVal < 0) { LOG_ERROR("Error during encoding "); m_bThreadStatus = TH_ENDED; break; }; if (! rVal) { if (m_bSegAActive) { mPacket.stream_index = m_pVideoStrA->index; mPacket.duration = 1; mPacket.pts = av_rescale_q(m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base); // mPacket.pts = AV_NOPTS_VALUE;
// mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
mPacket.dts = mPacket.pts; int rc = av_write_frame(m_pFormatCtxA, &mPacket); if (rc < 0) { // if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) {
m_bThreadStatus = TH_ENDED; LOG_ERROR("Trouble with Video Output A!"); av_strerror(rc, tB, 128); LOG_ERROR(tB); break; // continue (changed since embed into do-while)
}; }; if (m_bSegBActive) { mPacket.stream_index = m_pVideoStrB->index; mPacket.duration = 1; mPacket.pts = av_rescale_q(m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base); // mPacket.pts = AV_NOPTS_VALUE;
// mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base );
mPacket.dts = mPacket.pts; int rc = av_write_frame(m_pFormatCtxB, &mPacket); if (rc < 0) { // if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) {
m_bThreadStatus = TH_ENDED; LOG_ERROR("Trouble with Video Output B!"); av_strerror(rc, tB, 128); LOG_ERROR(tB); break; // continue (changed since embed into do-while)
}; }; av_packet_unref(&mPacket); }; } while (rVal >= 0 && m_bThreadStatus != TH_ENDED); #endif // ! SEPARATED_VIDEO_ENCODERS
#endif // !OPENCV_VIDEO_OUTPUT
#endif // !DIRECT_MJPEG_COMPOSING
SLEEP(10); }; #ifdef DEBUG_EXTRA
LOG("Encoder Loop Ended!"); #endif
}
void streamHandler::swapActiveStreams(void){ // m_mFrameCounterProtector.lock();
m_bActiveEncoderStream = 1 - m_bActiveEncoderStream; if (m_bActiveEncoderStream) { if (m_bSegADelete) { closeSegmentA(); } } else { if (m_bSegBDelete) { closeSegmentB(); } }; // m_mFrameCounterProtector.unlock();
}
#endif // EVE_ENABLE_VIDEO
bool streamHandler::triggerEvent(uint32_t eid, uint32_t & dbid, uint32_t & frame){
#ifdef DEBUG_EXTRA
LOG("Trig Evt");#endif
#ifdef EVE_ENABLE_VIDEO
m_mFrameCounterProtector.lock(); // To Mark Events Frames
m_bEvtMarkerCounter = 255; PF_TIMESTAMP ts; getPFTS(&ts); /*
if ( m_nVideoRegisteredDBID == 0 ) { LOG("New Event!");
if ( !m_bActiveEncoderStream ) { // Stream A is Active
m_nVideoRegisteredDBID = m_pDBC->addVideoRecord( m_sStreamData.id, m_cSegMD5A, VIDEO_OUTPUT_CONTAINER, ts.seconds, ts.milliseconds, m_sStreamData.fps ); m_bSegADelete = false; m_nSegAShiftFrames = frame = m_nSegAFrameCounter; } else { // Stream B is Active
m_nVideoRegisteredDBID = m_pDBC->addVideoRecord( m_sStreamData.id, m_cSegMD5B, VIDEO_OUTPUT_CONTAINER, ts.seconds, ts.milliseconds, m_sStreamData.fps ); m_bSegBDelete = false; m_nSegBShiftFrames = frame = m_nSegBFrameCounter; }; }; */ if ( dbid ) dbid = dbid; if (!m_bActiveEncoderStream) { // Stream A is Active
m_bSegADelete = false; m_nSegAShiftFrames = frame = m_nSegAFrameCounter; } else { // Stream B is Active
m_bSegBDelete = false; m_nSegBShiftFrames = frame = m_nSegBFrameCounter; }; m_sStreamSegmentInfo[m_bActiveEncoderStream].eventIDS.push_back(eid); m_sStreamSegmentInfo[m_bActiveEncoderStream].eventTSS.push_back(ts.seconds); m_sStreamSegmentInfo[m_bActiveEncoderStream].eventTMS.push_back(ts.milliseconds); m_sStreamSegmentInfo[m_bActiveEncoderStream].eventFrames.push_back(frame); // dbid = m_sStreamSegmentInfo[m_bActiveEncoderStream].db_id;// = m_nVideoRegisteredDBID;
m_mFrameCounterProtector.unlock(); // if ( dbid == 0 ) return false;
// dbid = m_nVideoRegisteredDBID;
#ifdef DEBUG_EXTRA
LOG("Event Registered!"); #endif
#endif // EVE_ENABLE_VIDEO
return true;}
bool streamHandler::triggerCamMove(void){#ifdef DEBUG_EXTRA
LOG("Trig Cammove");#endif
m_bCamMoveCounter = 255; return true;}
bool streamHandler::validate(void){ if (m_pSource) { if (m_pSource->getStatus() < MS_CLOSING) {#ifdef EVE_ENABLE_VIDEO
if (m_nGlobalFrameCounter) { // Frames Received from a source
if (m_nGlobalFrameCounter == m_nValidatorFrameCounter) { // Video Stalled!
LOG_ERROR("Video Stalled"); return false; // Try use System to recuperate
} else { m_nValidatorFrameCounter = m_nGlobalFrameCounter; } }; if (m_bThreadStatus < TH_ENDED) { return true; } else { LOG_ERROR("Thread Ended!"); }#endif
} else { LOG_ERROR("Video Ended"); } }; return false;}
// #undef DEBUG_EXTRA
// #undef DEBUG
#undef TLOG
#undef TLOG_ERROR
#else //LRF_PROXY_ONLY
kernelModuleEmbedVideo::kernelModuleEmbedVideo(uint32_t moduleID) : kernelModule(moduleID, KERNEL_MODULE_EMBED_VIDEO){
}
kernelModuleEmbedVideo::~kernelModuleEmbedVideo(){
}
#endif //LRF_PROXY_ONLY
#undef LOG
#undef LOG_ERROR
|