You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2916 lines
71 KiB

2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
2 years ago
2 years ago
​
2 years ago
​
​
​
​
​
​
2 years ago
​
​
​
2 years ago
​
​
2 years ago
​
​
​
​
2 years ago
2 years ago
​
​
​
​
​
​
2 years ago
2 years ago
​
​
​
2 years ago
2 years ago
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
2 years ago
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
2 years ago
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
2 years ago
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
2 years ago
2 years ago
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
2 years ago
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
2 years ago
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
2 years ago
2 years ago
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
2 years ago
2 years ago
​
​
​
2 years ago
2 years ago
2 years ago
​
​
​
​
2 years ago
2 years ago
2 years ago
2 years ago
​
2 years ago
2 years ago
​
​
​
2 years ago
​
​
​
​
2 years ago
2 years ago
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
2 years ago
2 years ago
​
​
2 years ago
2 years ago
​
​
2 years ago
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
2 years ago
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
2 years ago
2 years ago
​
​
2 years ago
2 years ago
​
​
2 years ago
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
2 years ago
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
2 years ago
​
​
2 years ago
2 years ago
​
2 years ago
​
2 years ago
​
​
​
​
​
​
​
2 years ago
​
2 years ago
​
​
​
2 years ago
2 years ago
​
​
2 years ago
​
​
​
​
​
​
​
2 years ago
​
​
2 years ago
2 years ago
​
2 years ago
​
2 years ago
​
​
​
​
​
​
​
2 years ago
​
2 years ago
​
​
​
2 years ago
2 years ago
​
2 years ago
​
​
​
​
​
2 years ago
​
​
2 years ago
2 years ago
​
​
​
​
​
2 years ago
2 years ago
​
2 years ago
2 years ago
​
​
​
​
2 years ago
​
​
​
​
2 years ago
​
​
​
​
2 years ago
​
​
​
2 years ago
​
​
​
​
2 years ago
2 years ago
​
2 years ago
2 years ago
​
​
​
​
2 years ago
2 years ago
​
​
​
2 years ago
2 years ago
​
2 years ago
2 years ago
​
2 years ago
2 years ago
2 years ago
2 years ago
​
​
2 years ago
2 years ago
​
​
2 years ago
2 years ago
​
​
2 years ago
​
2 years ago
​
​
​
​
​
​
​
​
2 years ago
2 years ago
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
2 years ago
2 years ago
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
2 years ago
​
​
2 years ago
2 years ago
2 years ago
2 years ago
​
2 years ago
​
2 years ago
2 years ago
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
2 years ago
​
​
​
2 years ago
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
2 years ago
2 years ago
​
​
​
​
2 years ago
2 years ago
2 years ago
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
5 days ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "kernelModuleEmbedVideo.h"
  2. #include "streamHandler.h"
  3. //#define DEBUG_EXTRA
  4. #define LOG(X) kernelModule::m_pLog->Log("MOD_EVIDEO", this, X)
  5. #ifdef DEBUG
  6. #define LOG_ERROR(X) \
  7. { \
  8. char _tBfrErrMSG2w34[2048]; \
  9. sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \
  10. kernelModule::m_pLog->Log("MOD_EVIDEO", this, _LOG_ERROR, _tBfrErrMSG2w34); \
  11. }
  12. #else
  13. #define LOG_ERROR(X) kernelModule::m_pLog->Log("MOD_EVIDEO", this, _LOG_ERROR, X);
  14. #endif
  15. #ifndef LRF_PROXY_ONLY
  16. // #include "rgooseHardwareResourceNetworkProvider.h"
  17. // #include "mojoKernel.h"
  18. #include "../alg/generic/base64.h"
  19. #include "../data/media/video/videoAVLIBSource.h"
  20. #include "../data/media/video/videoLive555AVLibSource.h"
  21. #include "../../data/media/mtx/servers/webrtc/webrtcServer.h"
  22. #include <arpa/inet.h>
  23. #include <ctype.h>
  24. #include <dirent.h>
  25. #include <sys/stat.h>
  26. #include <err.h>
  27. #include <errno.h>
  28. #include <getopt.h>
  29. #include <ifaddrs.h>
  30. #include <netdb.h>
  31. #include <netinet/ip.h>
  32. #include <netinet/udp.h>
  33. #include <openssl/sha.h>
  34. #include <paths.h>
  35. #include <poll.h>
  36. #include <signal.h>
  37. #include <stdint.h>
  38. #include <stdio.h>
  39. #include <stdlib.h>
  40. #include <string.h>
  41. #include <sys/param.h> /* MIN() */
  42. #include <sys/socket.h>
  43. #include <time.h>
  44. #include <unistd.h>
  45. // #define DEBUG
  46. // #undef DEBUG_EXTRA
  47. // #define DEBUG_EXTRA
  48. const char * m_pVideoScratchPath = VIDEO_SCRATCHPAD_PATH;
  49. #ifndef STORAGE_DIR_MODE
  50. #define STORAGE_DIR_MODE 0x1FF
  51. #endif
  52. #ifndef STORAGE_FILE_MODE
  53. #define STORAGE_FILE_MODE 0x1B6
  54. #endif
  55. #define TLOG(X) basicLogCollection::getInstance()->Log("MOD_EVIDEO_T", CTX, X)
  56. #ifdef DEBUG
  57. #define TLOG_ERROR(X) \
  58. { \
  59. char _tBfrErrMSG2w34[2048]; \
  60. sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \
  61. basicLogCollection::getInstance()->Log("MOD_EVIDEO_T", CTX, _LOG_ERROR, _tBfrErrMSG2w34); \
  62. }
  63. #else
  64. #define TLOG_ERROR(X) basicLogCollection::getInstance()->Log("MOD_EVIDEO_T", CTX, _LOG_ERROR, X);
  65. #endif
  66. enum
  67. {
  68. WEBRTC_REQ_SIGNIN = 0,
  69. WEBRTC_REQ_WAIT = 1,
  70. WEBRTC_REQ_SIGNOUT = 2,
  71. WEBRTC_REQ_MESSAGE = 3
  72. };
  73. //static const char * kRequestPaths[] = {"/stream", "/sign_in", "/wait", "/sign_out", "/message"};
  74. // buffer_data bd[1]={0};
  75. kernelModuleEmbedVideo::kernelModuleEmbedVideo(uint32_t moduleID) :
  76. kernelModule(moduleID, KERNEL_MODULE_EMBED_VIDEO)
  77. #ifndef EVE_WORK_WITH_MEDIAMTX
  78. ,basicDualThread()
  79. #endif // !EVE_WORK_WITH_MEDIAMTX
  80. {
  81. m_pEventHeap = basicEventHeap::getInstance();
  82. if (m_pDBC)
  83. {
  84. DBC_MODULE_EMBED_VIDEO_DATA * tDATA = m_pDBC->getEmbedVideoData(m_nDBAUXID);
  85. if (tDATA)
  86. {
  87. memcpy(&m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA));
  88. free(tDATA);
  89. }
  90. else
  91. {
  92. LOG_ERROR("No DB Data Error!");
  93. memset(&m_sEmbedVideoData, 0, sizeof(DBC_MODULE_EMBED_VIDEO_DATA));
  94. m_sEmbedVideoData.port = 8972;
  95. dbcEmbedVideoLiveDefaults(&m_sEmbedVideoData);
  96. };
  97. }
  98. else
  99. {
  100. LOG_ERROR("DB Error!");
  101. };
  102. m_bDetached = true;
  103. m_tLiveRetry = 0;
  104. m_tClipsScan = 0;
  105. m_nClipWaitUs = 0;
  106. // The MediaMtx library logs into the la_mojo log (tag MTX)
  107. mtx::Logger::instance().setDestinations(false, std::string());
  108. mtx::Logger::instance().setSink([](mtx::LogLevel level, const char * line) {
  109. if (level == mtx::LogLevel::Debug)
  110. {
  111. return;
  112. }
  113. if (level == mtx::LogLevel::Error)
  114. {
  115. basicLogCollection::getInstance()->Log("MTX", NULL, _LOG_ERROR, line);
  116. }
  117. else
  118. {
  119. basicLogCollection::getInstance()->Log("MTX", NULL, line);
  120. }
  121. });
  122. applyLiveSettings();
  123. n_pNoSignalData = NULL;
  124. m_nNoSignalSize = 0;
  125. m_bLogoActive = false;
  126. m_nLogoX = 0;
  127. m_nLogoY = 0;
  128. #ifdef HAVE_SMAL_PREVIEW_STREAMS
  129. n_pNoSignalSmallData = NULL;
  130. m_nNoSignalSmallSize = 0;
  131. #endif
  132. char tBuff[1024];
  133. sprintf(m_pBaseSavePath, "%s/data/reports", getcwd(tBuff, 1024));
  134. #ifdef DEBUG
  135. char tB[64];
  136. sprintf(tB, "Web Streams Port: %d", m_sEmbedVideoData.port);
  137. LOG(tB);
  138. sprintf(tB, "Frame: [%dx%d]", m_sEmbedVideoData.width, m_sEmbedVideoData.height);
  139. LOG(tB);
  140. if (m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES)
  141. {
  142. LOG("Output Pictures");
  143. }
  144. if ((m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO) == EVE_OUTPUT_VIDEO)
  145. {
  146. LOG("Output Video");
  147. }
  148. if (m_sEmbedVideoData.show_ts)
  149. {
  150. LOG("Show TimeStamp");
  151. }
  152. if (m_sEmbedVideoData.show_label)
  153. {
  154. LOG("Show Label");
  155. }
  156. if (m_sEmbedVideoData.show_logo)
  157. {
  158. LOG("Show Logo");
  159. }
  160. #endif
  161. if (m_sEmbedVideoData.show_logo)
  162. {
  163. LOG(m_sEmbedVideoData.logo_md5);
  164. char tPath[MAX_PATH];
  165. sprintf(tPath, "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5);
  166. if (! fileExist(tPath))
  167. {
  168. LOG_ERROR("Logo File Missed!"); // startService() leaves the logo off
  169. }
  170. #ifdef DEBUG
  171. else
  172. {
  173. LOG("Logo File is OK");
  174. }
  175. #endif
  176. ;
  177. };
  178. if (! fileExist(DB_SHMEM_POINT))
  179. {
  180. mkdir(DB_SHMEM_POINT, 0775); // S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH );
  181. chmod(DB_SHMEM_POINT, 0775);
  182. mkdir(m_pVideoScratchPath, 0775);
  183. chmod(m_pVideoScratchPath, 0775);
  184. }
  185. else
  186. {
  187. if (! fileExist((CSTR) m_pVideoScratchPath))
  188. {
  189. mkdir(m_pVideoScratchPath, 0775);
  190. chmod(m_pVideoScratchPath, 0775);
  191. }
  192. else
  193. {
  194. // Clean Video Scratch
  195. char tCMD[MAX_PATH];
  196. sprintf(tCMD, "rm -r -f -d %s/* ", m_pVideoScratchPath);
  197. system(tCMD);
  198. };
  199. };
  200. }
  201. kernelModuleEmbedVideo::~kernelModuleEmbedVideo()
  202. {
  203. detachEvents(); // stop event delivery before the members are destroyed (see basicEventHandler.h)
  204. #ifdef DEBUG
  205. LOG("Destructor");
  206. #endif
  207. if (! m_bDetached)
  208. {
  209. stopService(true);
  210. };
  211. stopLive(); // the WebRTC server uses this object (PathProvider): stop it before the members go
  212. // Sanity check
  213. LOG("Sanity check in Destructor!");
  214. #ifndef EVE_WORK_WITH_MEDIAMTX
  215. waitThreadAEnd(true);
  216. if (m_vHandlersPool.size())
  217. { // Kill-Wait Started Probes
  218. #ifdef DEBUG
  219. char tB[200];
  220. sprintf(tB, "Have to Wait Client Handlers[%lu]!", m_vHandlersPool.size());
  221. LOG(tB);
  222. #endif
  223. for (vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++)
  224. {
  225. pthread_cancel((*index)->m_hThreadHandle);
  226. }
  227. m_vHandlersPool.clear();
  228. };
  229. #ifdef DEBUG
  230. LOG("No More Clients Left");
  231. #endif
  232. waitThreadBEnd(true);
  233. if (m_vViewHandlersPool.size())
  234. { // Kill-Wait Started Viewers
  235. #ifdef DEBUG
  236. char tB[200];
  237. sprintf(tB, "Have to Wait View Handlers[%lu]!", m_vViewHandlersPool.size());
  238. LOG(tB);
  239. #endif
  240. for (vectorHANDLERS::iterator index = m_vViewHandlersPool.begin(); index < m_vViewHandlersPool.end(); index++)
  241. {
  242. pthread_cancel((*index)->m_hThreadHandle);
  243. }
  244. m_vViewHandlersPool.clear();
  245. };
  246. #ifdef DEBUG_EXTRA
  247. LOG("No More Viewers Left");
  248. #endif
  249. #ifdef DEBUG_EXTRA
  250. LOG("Deleting CAPS");
  251. #endif
  252. if (m_mapCAPTURES.size())
  253. {
  254. m_mapCAPTURES.clear();
  255. }
  256. #endif // !EVE_WORK_WITH_MEDIAMTX
  257. #ifdef DEBUG_EXTRA
  258. LOG("Deleting MATS");
  259. #endif
  260. if (m_mapMATS.size())
  261. {
  262. m_mapMATS.clear();
  263. }
  264. #ifdef DEBUG_EXTRA
  265. LOG("Deleting No Signal");
  266. #endif
  267. if (n_pNoSignalData)
  268. {
  269. free(n_pNoSignalData);
  270. }
  271. #ifdef HAVE_SMAL_PREVIEW_STREAMS
  272. if (n_pNoSignalSmallData)
  273. {
  274. free(n_pNoSignalSmallData);
  275. }
  276. #endif
  277. if (fileExist((CSTR) m_pVideoScratchPath))
  278. {
  279. // Clean Video Scratch
  280. char tCMD[MAX_PATH];
  281. sprintf(tCMD, "rm -r -f -d %s/* ", m_pVideoScratchPath);
  282. system(tCMD);
  283. };
  284. #ifdef DEBUG_EXTRA
  285. LOG("All Done!");
  286. #endif
  287. }
  288. static const char * ht_head =
  289. "HTTP/1.1 200 OK\r\n"
  290. "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n"
  291. "Pragma: no-cache\r\n"
  292. "Expires: 0\r\n"
  293. "MIME-version: 1.0\r\n"
  294. "Connection: close\r\n"
  295. //"Keep-Alive: timeout=5, max=1\r\n"
  296. //"Connection: Keep-Alive\r\n"
  297. //"Content-Type: video/mp4\r\n"
  298. "Content-Transfer-Encoding: BINARY\r\n"
  299. //"Transfer-Encoding: chunked\r\n"
  300. "Content-type: multipart/x-mixed-replace;boundary=MPFrame\r\n"
  301. "\r\n";
  302. static const char * ht_abort =
  303. "HTTP/1.1 404 OK\r\n"
  304. "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n"
  305. "Pragma: no-cache\r\n"
  306. "Expires: 0\r\n"
  307. "Connection: close\r\n\r\n";
  308. static const char * ht_no_signal =
  309. "HTTP/1.1 200 OK\r\n"
  310. "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n"
  311. "Pragma: no-cache\r\n"
  312. "Expires: 0\r\n"
  313. "MIME-version: 1.0\r\n"
  314. "Connection: close\r\n"
  315. "Content-Transfer-Encoding: BINARY\r\n"
  316. //"Content-type: multipart/x-mixed-replace;boundary=MPFrame\r\n\r\n"
  317. "Content-Type: image/jpeg\r\nContent-length: %d\r\n\r\n";
  318. void signal_pipe_handler(int SIG)
  319. {
  320. // Web Client Disconnected!
  321. if ( SIG ) SIG = SIG;
  322. #ifdef DEBUG_EXTRA
  323. basicLogCollection::getInstance()->Log("SIG_PIPE", NULL, _LOG_ERROR, "Sig Pipe Received Web Client Disconnected!");
  324. #endif
  325. }
  326. bool kernelModuleEmbedVideo::isProcessingVideoStream(){
  327. bool RV = false;
  328. m_mStreamHandlersProtector.lock();
  329. if (m_mapHANDLERS.size() ){
  330. for (mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++){
  331. if( (*idx).second->preservingCurrentRecording() ){
  332. RV = true;
  333. break;
  334. };
  335. };
  336. };
  337. m_mStreamHandlersProtector.unlock();
  338. if (! RV)
  339. {
  340. // recorder clips: an alarm whose clip is not handed over yet
  341. std::lock_guard<std::mutex> lock(m_mClips);
  342. for (auto & c : m_mapClips)
  343. {
  344. if (! c.second.alarms.empty())
  345. {
  346. RV = true;
  347. break;
  348. };
  349. };
  350. };
  351. return RV;
  352. };
  353. uint8_t kernelModuleEmbedVideo::getMediaMode(void)
  354. {
  355. return m_sEmbedVideoData.output_mode;
  356. }
  357. #ifndef EVE_WORK_WITH_MEDIAMTX
  358. void * kernelModuleEmbedVideo::webClientProc(void * ptr)
  359. {
  360. WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr;
  361. //kernelModuleEmbedVideo * MODULE = CTX->ModulePtr;
  362. uint32_t msgSize;
  363. uint8_t tBuf[FILESTREAMBUFFERSZ];
  364. //int retVal;
  365. bool w = true;
  366. #ifdef DEBUG_EXTRA
  367. TLOG("Start WebClient");
  368. #endif
  369. pthread_setname_np(pthread_self(), "LiveVideoCL");
  370. if (CTX)
  371. {
  372. char mesg[1024];
  373. //size_t RecvSize;
  374. struct pollfd pfd[1];
  375. char cGetURI[1024];
  376. //bool m_bDeflatePerMessage = false;
  377. //bool m_pInit;
  378. #ifdef DEBUG_EXTRA
  379. pid_t pid = gettid();
  380. char pidBuf[16];
  381. sprintf(pidBuf, "pid:%d", pid);
  382. TLOG(pidBuf);
  383. #endif
  384. signal(SIGPIPE, signal_pipe_handler);
  385. pfd->fd = CTX->m_iSocketFID;
  386. pfd->events = POLLIN | POLLHUP;
  387. while (CTX->bValid && w)
  388. {
  389. if (! CTX->initDone)
  390. {
  391. int RetVal;
  392. char * reqline[256];
  393. RetVal = poll(pfd, 1, 1000);
  394. if (RetVal <= 0)
  395. {
  396. if (EINTR == errno)
  397. {
  398. continue;
  399. }
  400. TLOG_ERROR("Unrecoverable error");
  401. w = false;
  402. continue;
  403. };
  404. memset(mesg, 0, sizeof(mesg));
  405. RetVal = recv(CTX->m_iSocketFID, mesg, sizeof(mesg), 0);
  406. if (RetVal <= 0)
  407. {
  408. sprintf(mesg, "web recv() error: %s", strerror(errno));
  409. TLOG_ERROR(mesg);
  410. w = false;
  411. continue;
  412. };
  413. #ifdef DEBUG_EXTRA
  414. TLOG(mesg);
  415. #endif
  416. uint32_t index = 0;
  417. reqline[index] = strtok(mesg, "\n");
  418. if (strncmp(reqline[index], "GET", 3) == 0)
  419. {
  420. char * pPartURI;
  421. char * pPartPROTO;
  422. pPartURI = strstr(reqline[index], " ");
  423. if (pPartURI != NULL)
  424. {
  425. pPartURI++;
  426. pPartPROTO = strstr(pPartURI, " ");
  427. pPartPROTO++;
  428. int URILen = pPartPROTO - pPartURI;
  429. strncpy(cGetURI, pPartURI, URILen);
  430. cGetURI[URILen] = (char) 0;
  431. if (strncmp(pPartPROTO, "HTTP/1.0", 8) != 0 && strncmp(pPartPROTO, "HTTP/1.1", 8) != 0)
  432. {
  433. TLOG_ERROR("No HTTP version supplied in request!");
  434. if (write(CTX->m_iSocketFID, "HTTP/1.1 400 Bad Request\r\n", 26) < 0)
  435. {
  436. sprintf(mesg, "Failed returning status 400 to client: %s", strerror(errno));
  437. TLOG_ERROR(mesg);
  438. };
  439. w = false;
  440. continue;
  441. };
  442. };
  443. #ifdef DEBUG_EXTRA
  444. TLOG("Req URI");
  445. TLOG(cGetURI);
  446. #endif
  447. };
  448. // if( ( strncmp( cGetURI, "/stream", 7 ) == 0 ) || ( strncmp( cGetURI, "/video_feed", 11 ) == 0 ) ) {
  449. if (strncmp(cGetURI, "/video_feed", 11) == 0)
  450. {
  451. uint32_t tStreamID = 0;
  452. CSTR tP;
  453. #ifdef HAVE_SMAL_PREVIEW_STREAMS
  454. if ((tP = strstr(cGetURI, "/preview")))
  455. {
  456. CTX->bPreviewMode = true;
  457. }
  458. #endif
  459. if ((tP = strstr(cGetURI, "?")))
  460. {
  461. CSTR tB;
  462. tP++;
  463. if ((tB = strstr(tP, "id=")))
  464. {
  465. tStreamID = atoi(tB + 3);
  466. };
  467. };
  468. if (tStreamID)
  469. {
  470. #ifdef DEBUG_EXTRA
  471. char tB[64];
  472. sprintf(tB, "StremID: %d", tStreamID);
  473. TLOG(tB);
  474. #endif
  475. if (CTX->ModulePtr->registerForMediaStream(tStreamID, CTX))
  476. {
  477. // Send Header
  478. if (send(CTX->m_iSocketFID, ht_head, strlen(ht_head), 0) < 0)
  479. {
  480. #ifdef DEBUG_EXTRA
  481. sprintf(mesg, "Failed sending file to client: %s", strerror(errno));
  482. TLOG_ERROR(mesg);
  483. #endif
  484. w = false;
  485. };
  486. CTX->initDone = true;
  487. continue;
  488. #ifdef DEBUG_EXTRA
  489. }
  490. else
  491. {
  492. TLOG("Stream id Not Online");
  493. #endif
  494. };
  495. #ifdef DEBUG_EXTRA
  496. }
  497. else
  498. {
  499. TLOG("No Stream ID");
  500. #endif
  501. };
  502. };
  503. if (CTX->ModulePtr->n_pNoSignalData)
  504. {
  505. // Send Dummy Picture
  506. #ifdef HAVE_SMAL_PREVIEW_STREAMS
  507. if (CTX->bPreviewMode)
  508. {
  509. sprintf(mesg, ht_no_signal, CTX->ModulePtr->m_nNoSignalSmallSize);
  510. send(CTX->m_iSocketFID, mesg, strlen(mesg), 0);
  511. send(CTX->m_iSocketFID, CTX->ModulePtr->n_pNoSignalSmallData, CTX->ModulePtr->m_nNoSignalSmallSize, 0);
  512. send(CTX->m_iSocketFID, "\r\n\r\n", 4, 0);
  513. }
  514. else
  515. {
  516. #endif
  517. sprintf(mesg, ht_no_signal, CTX->ModulePtr->m_nNoSignalSize);
  518. send(CTX->m_iSocketFID, mesg, strlen(mesg), 0);
  519. send(CTX->m_iSocketFID, CTX->ModulePtr->n_pNoSignalData, CTX->ModulePtr->m_nNoSignalSize, 0);
  520. send(CTX->m_iSocketFID, "\r\n\r\n", 4, 0);
  521. #ifdef HAVE_SMAL_PREVIEW_STREAMS
  522. };
  523. #endif
  524. #ifdef DEBUG_EXTRA_X
  525. TLOG("VFEED Sent No Signal Image!");
  526. #endif
  527. }
  528. else
  529. {
  530. // Send 404 Header
  531. send(CTX->m_iSocketFID, ht_abort, strlen(ht_abort), 0);
  532. #ifdef DEBUG_EXTRA
  533. TLOG("Aborted!");
  534. #endif
  535. };
  536. w = false;
  537. continue;
  538. }
  539. else
  540. {
  541. /*
  542. retVal = read( CTX->m_iEncoderPipe[0], &msgSize, sizeof(uint32_t));
  543. if( retVal == -1 ){
  544. if( errno == EAGAIN || errno == EWOULDBLOCK ){
  545. continue;
  546. };
  547. TLOG_ERROR("Pipe Communication Error[1]!");
  548. CTX->bValid = false;
  549. continue;
  550. };
  551. if( msgSize < FILESTREAMBUFFERSZ ) {
  552. retVal = read( CTX->m_iEncoderPipe[0], tBuf, msgSize );
  553. } else {
  554. TLOG_ERROR("Data too Big in Pipe Transfer!");
  555. CTX->bValid = false;
  556. continue;
  557. };
  558. if( retVal == -1 ){
  559. //free( tBuf );
  560. if( errno == EAGAIN || errno == EWOULDBLOCK ){
  561. continue;
  562. };
  563. TLOG_ERROR("Pipe Communication Error[2]!");
  564. CTX->bValid = false;
  565. continue;
  566. };
  567. */
  568. /**************/
  569. CTX->ModulePtr->m_mEncodedProtector.lock();
  570. #ifdef HAVE_SMAL_PREVIEW_STREAMS
  571. if (CTX->bPreviewMode)
  572. {
  573. if (CTX->ModulePtr->m_mapPREVIEWS[CTX->mediaStreamId].size())
  574. {
  575. msgSize = CTX->ModulePtr->m_mapPREVIEWS[CTX->mediaStreamId].size();
  576. if (msgSize < FILESTREAMBUFFERSZ)
  577. {
  578. memcpy(tBuf, CTX->ModulePtr->m_mapPREVIEWS[CTX->mediaStreamId].data(), msgSize);
  579. CTX->ModulePtr->m_mEncodedProtector.unlock();
  580. }
  581. else
  582. {
  583. CTX->ModulePtr->m_mEncodedProtector.unlock();
  584. TLOG_ERROR("Data too Big in Pipe Transfer!");
  585. w = false;
  586. continue;
  587. };
  588. }
  589. else
  590. {
  591. CTX->ModulePtr->m_mEncodedProtector.unlock();
  592. if (CTX->ModulePtr->n_pNoSignalSmallData)
  593. {
  594. msgSize = CTX->ModulePtr->m_nNoSignalSmallSize;
  595. memcpy(tBuf, CTX->ModulePtr->n_pNoSignalSmallData, msgSize);
  596. }
  597. else
  598. {
  599. TLOG_ERROR("Data too Big in Pipe Transfer!");
  600. w = false;
  601. continue;
  602. };
  603. };
  604. }
  605. else
  606. {
  607. #endif
  608. if (CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].size())
  609. {
  610. msgSize = CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].size();
  611. if (msgSize < FILESTREAMBUFFERSZ)
  612. {
  613. memcpy(tBuf, CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].data(), msgSize);
  614. CTX->ModulePtr->m_mEncodedProtector.unlock();
  615. }
  616. else
  617. {
  618. CTX->ModulePtr->m_mEncodedProtector.unlock();
  619. TLOG_ERROR("Data too Big in Pipe Transfer!");
  620. w = false;
  621. continue;
  622. };
  623. }
  624. else
  625. {
  626. #ifdef DEBUG_EXTRA
  627. TLOG("VFEED Sent No Signal Image!");
  628. #endif
  629. CTX->ModulePtr->m_mEncodedProtector.unlock();
  630. if (CTX->ModulePtr->n_pNoSignalData)
  631. {
  632. msgSize = CTX->ModulePtr->m_nNoSignalSize;
  633. memcpy(tBuf, CTX->ModulePtr->n_pNoSignalData, msgSize);
  634. }
  635. else
  636. {
  637. TLOG_ERROR("Data too Big in Pipe Transfer!");
  638. w = false;
  639. continue;
  640. };
  641. };
  642. #ifdef HAVE_SMAL_PREVIEW_STREAMS
  643. };
  644. #endif
  645. /*********/
  646. sprintf(mesg, "--MPFrame\r\nContent-type: image/jpeg\r\nContent-length: %d\r\n\r\n", msgSize);
  647. if (send(CTX->m_iSocketFID, mesg, strlen(mesg), 0) < 0)
  648. {
  649. #ifdef DEBUG_EXTRA
  650. sprintf(mesg, "[1]Failed sending file to client: %s", strerror(errno));
  651. TLOG_ERROR(mesg);
  652. #endif
  653. w = false;
  654. continue;
  655. };
  656. if (send(CTX->m_iSocketFID, tBuf, msgSize, 0) < 0)
  657. {
  658. #ifdef DEBUG_EXTRA
  659. sprintf(mesg, "[2]Failed sending file to client: %s", strerror(errno));
  660. TLOG_ERROR(mesg);
  661. #endif
  662. w = false;
  663. continue;
  664. };
  665. if (send(CTX->m_iSocketFID, "\r\n\r\n", 4, 0) < 0)
  666. {
  667. #ifdef DEBUG_EXTRA
  668. sprintf(mesg, "[3]Failed sending file to client: %s", strerror(errno));
  669. TLOG_ERROR(mesg);
  670. #endif
  671. w = false;
  672. continue;
  673. };
  674. usleep(66666);
  675. };
  676. };
  677. };
  678. close(CTX->m_iEncoderPipe[0]);
  679. shutdown(CTX->m_iSocketFID, SHUT_RDWR);
  680. SLEEP(3);
  681. close(CTX->m_iSocketFID);
  682. CTX->bValid = false;
  683. #ifdef DEBUG_EXTRA
  684. TLOG("WEB Client Handler Ended!");
  685. #endif
  686. pthread_exit(NULL);
  687. return NULL;
  688. }
  689. void * kernelModuleEmbedVideo::viewClientProc(void * ptr)
  690. {
  691. WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr;
  692. //kernelModuleEmbedVideo * MODULE = CTX->ModulePtr;
  693. //uint32_t tVideoID = 0;
  694. long int tDTS = 0;
  695. uint32_t tETS = 0;
  696. uint32_t msgSize;
  697. uint8_t tBuf[FILESTREAMBUFFERSZ];
  698. uint8_t rBuf[8192];
  699. int rSIZE;
  700. int cSIZE;
  701. //int retVal;
  702. bool w = true;
  703. char tBASE[11] = {0};
  704. char tID[33] = {0};
  705. char tFILE[PATH_MAX];
  706. uint32_t cFRAME = 0;
  707. void * sPtr = NULL;
  708. void * ePtr = NULL;
  709. uint8_t baba[2] = {0xff, 0xd8};
  710. uint8_t yaba[2] = {0xff, 0xd9};
  711. FILE * tFID = NULL;
  712. TLOG("Start ViewClient");
  713. pthread_setname_np(pthread_self(), "ReportVideoCL");
  714. if (CTX)
  715. {
  716. char mesg[1024];
  717. //size_t RecvSize;
  718. struct pollfd pfd[1];
  719. char cGetURI[1024];
  720. //bool m_bDeflatePerMessage = false;
  721. //bool m_pInit;
  722. #ifdef DEBUG_EXTRA
  723. pid_t pid = gettid();
  724. char pidBuf[16];
  725. sprintf(pidBuf, "pid:%d", pid);
  726. TLOG(pidBuf);
  727. #endif
  728. signal(SIGPIPE, signal_pipe_handler);
  729. pfd->fd = CTX->m_iSocketFID;
  730. pfd->events = POLLIN | POLLHUP;
  731. while (CTX->bValid && w)
  732. {
  733. if (! CTX->initDone)
  734. {
  735. int RetVal;
  736. char * reqline[256];
  737. RetVal = poll(pfd, 1, 1000);
  738. if (RetVal <= 0)
  739. {
  740. if (EINTR == errno)
  741. {
  742. continue;
  743. }
  744. TLOG_ERROR("Unrecoverable error");
  745. w = false;
  746. continue;
  747. };
  748. memset(mesg, 0, sizeof(mesg));
  749. RetVal = recv(CTX->m_iSocketFID, mesg, sizeof(mesg), 0);
  750. if (RetVal <= 0)
  751. {
  752. sprintf(mesg, "web recv() error: %s", strerror(errno));
  753. TLOG_ERROR(mesg);
  754. w = false;
  755. continue;
  756. };
  757. #ifdef DEBUG_EXTRA
  758. TLOG(mesg);
  759. #endif
  760. uint32_t index = 0;
  761. reqline[index] = strtok(mesg, "\n");
  762. if (strncmp(reqline[index], "GET", 3) == 0)
  763. {
  764. char * pPartURI;
  765. char * pPartPROTO;
  766. pPartURI = strstr(reqline[index], " ");
  767. if (pPartURI != NULL)
  768. {
  769. pPartURI++;
  770. pPartPROTO = strstr(pPartURI, " ");
  771. pPartPROTO++;
  772. int URILen = pPartPROTO - pPartURI;
  773. strncpy(cGetURI, pPartURI, URILen);
  774. cGetURI[URILen] = (char) 0;
  775. if (strncmp(pPartPROTO, "HTTP/1.0", 8) != 0 && strncmp(pPartPROTO, "HTTP/1.1", 8) != 0)
  776. {
  777. TLOG_ERROR("No HTTP version supplied in request!");
  778. if (write(CTX->m_iSocketFID, "HTTP/1.1 400 Bad Request\r\n", 26) < 0)
  779. {
  780. sprintf(mesg, "Failed returning status 400 to client: %s", strerror(errno));
  781. TLOG_ERROR(mesg);
  782. };
  783. w = false;
  784. continue;
  785. };
  786. };
  787. #ifdef DEBUG_EXTRA
  788. TLOG("Req URI");
  789. TLOG(cGetURI);
  790. #endif
  791. };
  792. if ((strncmp(cGetURI, "/stream", 7) == 0) || (strncmp(cGetURI, "/video_view", 11) == 0))
  793. {
  794. CSTR tP;
  795. if ((tP = strstr(cGetURI, "?")))
  796. {
  797. CSTR tB;
  798. tP++;
  799. if ((tB = strcasestr(tP, "id=")))
  800. {
  801. strncpy(tID, tB + 3, 32);
  802. tID[32] = (char) 0;
  803. };
  804. if ((tB = strcasestr(tP, "ts=")))
  805. {
  806. tDTS = atol(tB + 3);
  807. // struct tm * ptm = gmtime ( &tDTS );
  808. struct tm * ptm = localtime(&tDTS);
  809. if (ptm)
  810. {
  811. sprintf(tBASE, "%04d/%02d/%02d", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday);
  812. };
  813. };
  814. if ((tB = strcasestr(tP, "sf=")))
  815. {
  816. tETS = atoi(tB + 3);
  817. };
  818. sprintf(tFILE, "./data/reports/%s/%s.mjpeg", tBASE, tID);
  819. };
  820. #ifdef DEBUG_EXTRA
  821. char tB[64];
  822. sprintf(tB, "Requested Video: %s", tFILE);
  823. TLOG(tB);
  824. #endif
  825. if (fileExist(tFILE))
  826. {
  827. tFID = fopen(tFILE, "r");
  828. if (tFID)
  829. {
  830. // Send Header
  831. if (send(CTX->m_iSocketFID, ht_head, strlen(ht_head), 0) < 0)
  832. {
  833. #ifdef DEBUG
  834. sprintf(mesg, "Failed sending file to client: %s", strerror(errno));
  835. TLOG_ERROR(mesg);
  836. #endif
  837. w = false;
  838. };
  839. CTX->initDone = true;
  840. continue;
  841. #ifdef DEBUG
  842. }
  843. else
  844. {
  845. TLOG("Stream id Not Online");
  846. #endif
  847. };
  848. }
  849. else
  850. {
  851. TLOG_ERROR("VVIEW File Not Exists!");
  852. };
  853. };
  854. #ifdef DEBUG_EXTRA
  855. TLOG("VVIEW Catched in DeadEnd!");
  856. #endif
  857. if (1)
  858. {
  859. // Send Dummy Picture
  860. sprintf(mesg, ht_no_signal, CTX->ModulePtr->m_nNoSignalSize);
  861. send(CTX->m_iSocketFID, mesg, strlen(mesg), 0);
  862. send(CTX->m_iSocketFID, CTX->ModulePtr->n_pNoSignalData, CTX->ModulePtr->m_nNoSignalSize, 0);
  863. send(CTX->m_iSocketFID, "\r\n\r\n", 4, 0);
  864. #ifdef DEBUG_EXTRA
  865. TLOG("VVIEW Sent No Signal Image!");
  866. #endif
  867. }
  868. else
  869. {
  870. // Send 404 Header
  871. send(CTX->m_iSocketFID, ht_abort, strlen(ht_abort), 0);
  872. #ifdef DEBUG_EXTRA
  873. TLOG("Aborted!");
  874. #endif
  875. };
  876. w = false;
  877. continue;
  878. }
  879. else
  880. {
  881. cSIZE = 0;
  882. while (! feof(tFID) && CTX->bValid && w)
  883. {
  884. rSIZE = fread(rBuf, 1, 8192, tFID);
  885. if (rSIZE > 0)
  886. {
  887. memcpy(tBuf + cSIZE, rBuf, rSIZE);
  888. cSIZE += rSIZE;
  889. if (sPtr == NULL)
  890. {
  891. sPtr = memmem(tBuf, cSIZE, baba, 2);
  892. }
  893. if (sPtr)
  894. {
  895. if (sPtr != tBuf)
  896. {
  897. cSIZE -= ((uint64_t) sPtr - (uint64_t) tBuf);
  898. memcpy(tBuf, sPtr, cSIZE);
  899. sPtr = tBuf;
  900. };
  901. if (ePtr == NULL)
  902. {
  903. ePtr = memmem(sPtr, cSIZE, yaba, 2);
  904. }
  905. };
  906. };
  907. if (sPtr != NULL && ePtr != NULL)
  908. {
  909. if (feof(tFID))
  910. {
  911. TLOG("LAST FRAME");
  912. }
  913. cFRAME++;
  914. ePtr =(void *)(((uint64_t)ePtr) + 2);
  915. msgSize = ((uint64_t) ePtr - (uint64_t) sPtr);
  916. if (cFRAME > tETS || feof(tFID))
  917. { // or last chanse to send data
  918. if (feof(tFID))
  919. {
  920. TLOG("SEND HEADER");
  921. }
  922. sprintf(mesg, "--MPFrame\r\nContent-type: image/jpeg\r\nContent-length: %d\r\n\r\n", msgSize);
  923. if (send(CTX->m_iSocketFID, mesg, strlen(mesg), 0) < 0)
  924. {
  925. #ifdef DEBUG
  926. sprintf(mesg, "[1]Failed sending file to client: %s", strerror(errno));
  927. TLOG_ERROR(mesg);
  928. #endif
  929. w = false;
  930. continue;
  931. };
  932. if (feof(tFID))
  933. {
  934. TLOG("SEND BODY");
  935. }
  936. if (send(CTX->m_iSocketFID, tBuf, msgSize, 0) < 0)
  937. {
  938. #ifdef DEBUG
  939. sprintf(mesg, "[2]Failed sending file to client: %s", strerror(errno));
  940. TLOG_ERROR(mesg);
  941. #endif
  942. w = false;
  943. continue;
  944. };
  945. if (feof(tFID))
  946. {
  947. TLOG("SEND TAIL");
  948. }
  949. if (send(CTX->m_iSocketFID, "\r\n\r\n", 4, 0) < 0)
  950. {
  951. #ifdef DEBUG
  952. sprintf(mesg, "[3]Failed sending file to client: %s", strerror(errno));
  953. TLOG_ERROR(mesg);
  954. #endif
  955. w = false;
  956. continue;
  957. };
  958. SLEEP(66);
  959. };
  960. if (! feof(tFID))
  961. {
  962. cSIZE -= msgSize;
  963. memcpy(tBuf, ePtr, cSIZE);
  964. sPtr = ePtr = NULL;
  965. }
  966. #ifdef DEBUG
  967. else
  968. {
  969. TLOG("File is Finished!");
  970. }
  971. #endif
  972. };
  973. #ifdef DEBUG
  974. if (feof(tFID))
  975. {
  976. TLOG("LAST FRAME SENT");
  977. }
  978. #endif
  979. };
  980. #ifdef DEBUG_EXTRA
  981. TLOG("Close File");
  982. #endif
  983. fclose(tFID);
  984. w = false;
  985. };
  986. };
  987. };
  988. #ifdef DEBUG_EXTRA
  989. TLOG("Shut Down Socket");
  990. #endif
  991. shutdown(CTX->m_iSocketFID, SHUT_RDWR);
  992. #ifdef DEBUG_EXTRA
  993. TLOG("Close Socket");
  994. #endif
  995. close(CTX->m_iSocketFID);
  996. CTX->bValid = false;
  997. #ifdef DEBUG_EXTRA
  998. TLOG("View Client Handler Ended!");
  999. #endif
  1000. pthread_exit(NULL);
  1001. TLOG("After Pthread Exit");
  1002. return NULL;
  1003. }
  1004. // Start Thread To view Live Streams
  1005. void kernelModuleEmbedVideo::m_fThreadAProc(void)
  1006. {
  1007. if (! m_bEnabled)
  1008. {
  1009. #ifdef DEBUG_EXTRA
  1010. LOG("Module is Disabled!");
  1011. #endif
  1012. return;
  1013. };
  1014. #ifdef DEBUG_EXTRA
  1015. LOG("[LIVE] Module Started!");
  1016. #endif
  1017. pthread_setname_np(pthread_self(), "Live Video Stream");
  1018. struct pollfd pfd[1];
  1019. pfd->fd = m_nSocketDescriptor;
  1020. pfd->events = POLLIN | POLLHUP;
  1021. m_bThreadAStatus = TH_WORKING;
  1022. while (m_bThreadAStatus < TH_ENDED)
  1023. {
  1024. if (! m_bEnabled)
  1025. {
  1026. m_bThreadAStatus = TH_ENDED;
  1027. continue;
  1028. };
  1029. int RetVal = poll(pfd, 1, 1000);
  1030. if (RetVal < 0)
  1031. {
  1032. if (EINTR == errno)
  1033. {
  1034. continue;
  1035. }
  1036. LOG_ERROR("Unrecoverable error");
  1037. m_bThreadAStatus = TH_ENDED;
  1038. continue;
  1039. };
  1040. // Handle Connections
  1041. if (RetVal != 0)
  1042. {
  1043. if (pfd[0].revents & POLLIN)
  1044. {
  1045. #ifdef DEBUG_EXTRA
  1046. LOG("Handle New Client");
  1047. #endif
  1048. int tSID = accept(pfd[0].fd, NULL, NULL);
  1049. if (tSID < 0)
  1050. {
  1051. char tBuf[CTEXT];
  1052. sprintf(tBuf, "Accept() error: %s", strerror(errno));
  1053. LOG_ERROR(tBuf);
  1054. }
  1055. else
  1056. {
  1057. #ifdef DEBUG_EXTRA
  1058. LOG("Accept OK");
  1059. #endif
  1060. WEB_CLIENT_CTX * tCTX = (WEB_CLIENT_CTX *) malloc(sizeof(WEB_CLIENT_CTX));
  1061. if (tCTX)
  1062. {
  1063. #ifdef DEBUG_EXTRA
  1064. LOG("CTX OK");
  1065. #endif
  1066. WEB_HANDLER * tHANDLER = (WEB_HANDLER *) malloc(sizeof(WEB_HANDLER));
  1067. if (tHANDLER)
  1068. {
  1069. #ifdef DEBUG_EXTRA
  1070. LOG("HANDLER OK");
  1071. #endif
  1072. memset(tCTX, 0, sizeof(WEB_CLIENT_CTX));
  1073. memset(tHANDLER, 0, sizeof(WEB_HANDLER));
  1074. tCTX->m_iSocketFID = tSID;
  1075. tCTX->m_iEncoderPipe[0] = -1;
  1076. tCTX->m_iEncoderPipe[1] = -1;
  1077. tCTX->mediaStreamId = 0;
  1078. tCTX->bValid = true;
  1079. tCTX->ModulePtr = this;
  1080. #ifdef DEBUG_EXTRA
  1081. LOG("Before Thread Create");
  1082. #endif
  1083. int RetVal = pthread_create(&tHANDLER->m_hThreadHandle, NULL, webClientProc, (void *) tCTX);
  1084. if (RetVal == -1)
  1085. {
  1086. free(tCTX);
  1087. free(tHANDLER);
  1088. LOG_ERROR("Thread Creation Faled.");
  1089. shutdown(tSID, SHUT_RDWR);
  1090. close(tSID);
  1091. }
  1092. else
  1093. {
  1094. tHANDLER->CTX = tCTX;
  1095. m_mWebHandlersProtector.lock();
  1096. m_vHandlersPool.push_back(tHANDLER);
  1097. m_mWebHandlersProtector.unlock();
  1098. #ifdef DEBUG_EXTRA
  1099. LOG("Handler Pushed to a Pool");
  1100. #endif
  1101. };
  1102. }
  1103. else
  1104. { // https://stackoverflow.com/questions/18545077/image-fullscreen-on-click
  1105. free(tCTX);
  1106. LOG_ERROR("CL_HANDLER Mem Allocation Failure!");
  1107. shutdown(tSID, SHUT_RDWR);
  1108. close(tSID);
  1109. };
  1110. }
  1111. else
  1112. {
  1113. LOG_ERROR("CL_CTX Mem Allocation Failure!");
  1114. shutdown(tSID, SHUT_RDWR);
  1115. close(tSID);
  1116. };
  1117. };
  1118. };
  1119. };
  1120. // Handle Dead Clients
  1121. m_mWebHandlersProtector.lock();
  1122. if (m_vHandlersPool.size())
  1123. {
  1124. for (vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx != m_vHandlersPool.end();)
  1125. {
  1126. if (! ((*idx)->CTX->bValid))
  1127. {
  1128. #ifdef DEBUG_EXTRA
  1129. LOG("Have Dead Client!");
  1130. #endif
  1131. pthread_join((*idx)->m_hThreadHandle, NULL);
  1132. // close( (*idx)->CTX->m_iEncoderPipe[0] );
  1133. close((*idx)->CTX->m_iEncoderPipe[1]);
  1134. free((*idx)->CTX);
  1135. free(*idx);
  1136. m_vHandlersPool.erase(idx);
  1137. #ifdef DEBUG_EXTRA
  1138. LOG("Web Handler Ripped!");
  1139. #endif
  1140. }
  1141. else
  1142. {
  1143. idx++;
  1144. }
  1145. };
  1146. };
  1147. m_mWebHandlersProtector.unlock();
  1148. // validate active streams ?
  1149. SLEEP(50);
  1150. };
  1151. }
  1152. void kernelModuleEmbedVideo::m_fThreadBProc(void)
  1153. {
  1154. if (! m_bEnabled)
  1155. {
  1156. #ifdef DEBUG_EXTRA
  1157. LOG("Module is Disabled!");
  1158. #endif
  1159. return;
  1160. };
  1161. #ifdef DEBUG_EXTRA
  1162. LOG("[VIEW] Module Started!");
  1163. #endif
  1164. struct pollfd pfd[1];
  1165. pfd->fd = m_nViewSocketDescriptor;
  1166. pfd->events = POLLIN | POLLHUP;
  1167. m_bThreadBStatus = TH_WORKING;
  1168. pthread_setname_np(pthread_self(), "Report Video View");
  1169. while (m_bThreadBStatus < TH_ENDED)
  1170. {
  1171. if (! m_bEnabled)
  1172. {
  1173. m_bThreadBStatus = TH_ENDED;
  1174. continue;
  1175. };
  1176. int RetVal = poll(pfd, 1, 1000);
  1177. if (RetVal < 0)
  1178. {
  1179. if (EINTR == errno)
  1180. {
  1181. continue;
  1182. }
  1183. LOG_ERROR("Unrecoverable error");
  1184. m_bThreadBStatus = TH_ENDED;
  1185. continue;
  1186. };
  1187. // Handle Connections
  1188. if (RetVal != 0)
  1189. {
  1190. if (pfd[0].revents & POLLIN)
  1191. {
  1192. #ifdef DEBUG_EXTRA
  1193. LOG("Handle New View");
  1194. #endif
  1195. int tSID = accept(pfd[0].fd, NULL, NULL);
  1196. if (tSID < 0)
  1197. {
  1198. char tBuf[CTEXT];
  1199. sprintf(tBuf, "Accept() error: %s", strerror(errno));
  1200. LOG_ERROR(tBuf);
  1201. }
  1202. else
  1203. {
  1204. #ifdef DEBUG_EXTRA
  1205. LOG("Accept OK");
  1206. #endif
  1207. WEB_CLIENT_CTX * tCTX = (WEB_CLIENT_CTX *) malloc(sizeof(WEB_CLIENT_CTX));
  1208. if (tCTX)
  1209. {
  1210. #ifdef DEBUG_EXTRA
  1211. LOG("CTX OK");
  1212. #endif
  1213. WEB_HANDLER * tHANDLER = (WEB_HANDLER *) malloc(sizeof(WEB_HANDLER));
  1214. if (tHANDLER)
  1215. {
  1216. #ifdef DEBUG_EXTRA
  1217. LOG("HANDLER OK");
  1218. #endif
  1219. memset(tCTX, 0, sizeof(WEB_CLIENT_CTX));
  1220. memset(tHANDLER, 0, sizeof(WEB_HANDLER));
  1221. tCTX->m_iSocketFID = tSID;
  1222. tCTX->m_iEncoderPipe[0] = -1;
  1223. tCTX->m_iEncoderPipe[1] = -1;
  1224. tCTX->mediaStreamId = 0;
  1225. tCTX->bValid = true;
  1226. tCTX->ModulePtr = this;
  1227. #ifdef DEBUG_EXTRA
  1228. LOG("Before Thread Create");
  1229. #endif
  1230. int RetVal = pthread_create(&tHANDLER->m_hThreadHandle, NULL, viewClientProc, (void *) tCTX);
  1231. if (RetVal == -1)
  1232. {
  1233. free(tCTX);
  1234. free(tHANDLER);
  1235. LOG_ERROR("Thread Creation Faled.");
  1236. shutdown(tSID, SHUT_RDWR);
  1237. close(tSID);
  1238. }
  1239. else
  1240. {
  1241. tHANDLER->CTX = tCTX;
  1242. m_mViewHandlersProtector.lock();
  1243. m_vViewHandlersPool.push_back(tHANDLER);
  1244. m_mViewHandlersProtector.unlock();
  1245. #ifdef DEBUG_EXTRA
  1246. LOG("Handler Pushed to a Pool");
  1247. #endif
  1248. };
  1249. }
  1250. else
  1251. { // https://stackoverflow.com/questions/18545077/image-fullscreen-on-click
  1252. free(tCTX);
  1253. LOG_ERROR("CL_HANDLER Mem Allocation Failure!");
  1254. shutdown(tSID, SHUT_RDWR);
  1255. close(tSID);
  1256. };
  1257. }
  1258. else
  1259. {
  1260. LOG_ERROR("CL_CTX Mem Allocation Failure!");
  1261. shutdown(tSID, SHUT_RDWR);
  1262. close(tSID);
  1263. };
  1264. };
  1265. };
  1266. };
  1267. // Handle Dead Clients
  1268. m_mViewHandlersProtector.lock();
  1269. if (m_vViewHandlersPool.size())
  1270. {
  1271. for (vectorHANDLERS::iterator idx = m_vViewHandlersPool.begin(); idx != m_vViewHandlersPool.end();)
  1272. {
  1273. if (! ((*idx)->CTX->bValid))
  1274. {
  1275. #ifdef DEBUG_EXTRA
  1276. LOG("Have Dead Viewer!");
  1277. #endif
  1278. pthread_join((*idx)->m_hThreadHandle, NULL);
  1279. free((*idx)->CTX);
  1280. free(*idx);
  1281. m_vViewHandlersPool.erase(idx);
  1282. #ifdef DEBUG_EXTRA
  1283. LOG("View Handler Ripped!");
  1284. #endif
  1285. }
  1286. else
  1287. {
  1288. idx++;
  1289. }
  1290. };
  1291. };
  1292. m_mViewHandlersProtector.unlock();
  1293. // validate active streams ?
  1294. SLEEP(50);
  1295. };
  1296. }
  1297. #endif // !EVE_WORK_WITH_MEDIAMTX
  1298. #define ENABLE_SOCKOPT(sd, level, opt) \
  1299. do \
  1300. { \
  1301. int val = 1; \
  1302. if (setsockopt(sd, level, opt, &val, sizeof(val)) < 0) \
  1303. warn("Failed enabling %s for web service", #opt); \
  1304. } \
  1305. while (0);
  1306. bool kernelModuleEmbedVideo::startService()
  1307. {
  1308. m_bDetached = false;
  1309. // Create NoSignal Image
  1310. cv::Mat tMat(m_sEmbedVideoData.height, m_sEmbedVideoData.width, CV_8UC3);
  1311. cv::rectangle(tMat, cv::Point(0, 0), cv::Point(m_sEmbedVideoData.width, m_sEmbedVideoData.height), cv::Scalar(255, 0, 0), cv::FILLED);
  1312. cv::putText(tMat, "NO SIGNAL", cv::Point(10, 30), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(0, 255, 255), 3);
  1313. m_bLogoActive = false;
  1314. m_mLogoPic.release();
  1315. m_mLogoMask.release();
  1316. if (m_sEmbedVideoData.show_logo && m_sEmbedVideoData.logo_w > 0 && m_sEmbedVideoData.logo_h > 0 && m_sEmbedVideoData.logo_w <= m_sEmbedVideoData.width && m_sEmbedVideoData.logo_h <= m_sEmbedVideoData.height)
  1317. {
  1318. // Negative coordinates are measured from the right / bottom edge
  1319. int a_x = m_sEmbedVideoData.logo_x;
  1320. int a_y = m_sEmbedVideoData.logo_y;
  1321. if (a_x < 0)
  1322. {
  1323. a_x = m_sEmbedVideoData.width + a_x - m_sEmbedVideoData.logo_w;
  1324. }
  1325. if (a_y < 0)
  1326. {
  1327. a_y = m_sEmbedVideoData.height + a_y - m_sEmbedVideoData.logo_h;
  1328. }
  1329. a_x = std::max(0, std::min(a_x, (int) m_sEmbedVideoData.width - (int) m_sEmbedVideoData.logo_w));
  1330. a_y = std::max(0, std::min(a_y, (int) m_sEmbedVideoData.height - (int) m_sEmbedVideoData.logo_h));
  1331. char tName[256];
  1332. snprintf(tName, sizeof(tName), "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5);
  1333. cv::Mat T = cv::imread(tName, cv::IMREAD_UNCHANGED);
  1334. if (T.cols > 0 && T.rows > 0)
  1335. {
  1336. cv::Mat rgb, mask;
  1337. if (T.channels() == 4)
  1338. {
  1339. vector<cv::Mat> layers;
  1340. cv::split(T, layers);
  1341. mask = layers[3]; // png's alpha channel used as mask
  1342. layers.pop_back();
  1343. cv::merge(layers, rgb);
  1344. }
  1345. else
  1346. {
  1347. // No alpha channel: the whole picture is drawn
  1348. if (T.channels() == 1)
  1349. {
  1350. cv::cvtColor(T, rgb, cv::COLOR_GRAY2BGR);
  1351. }
  1352. else
  1353. {
  1354. rgb = T;
  1355. }
  1356. mask = cv::Mat(T.rows, T.cols, CV_8UC1, cv::Scalar(255));
  1357. }
  1358. if (rgb.depth() != CV_8U)
  1359. {
  1360. rgb.convertTo(rgb, CV_8U, 1.0 / 257.0);
  1361. mask.convertTo(mask, CV_8U, 1.0 / 257.0);
  1362. }
  1363. cv::resize(rgb, m_mLogoPic, cv::Size(m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h), 0, 0, cv::INTER_CUBIC);
  1364. cv::resize(mask, m_mLogoMask, cv::Size(m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h), 0, 0, cv::INTER_CUBIC);
  1365. m_nLogoX = a_x;
  1366. m_nLogoY = a_y;
  1367. m_bLogoActive = true;
  1368. cv::Mat destinationROI = tMat(cv::Rect(m_nLogoX, m_nLogoY, m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h));
  1369. m_mLogoPic.copyTo(destinationROI, m_mLogoMask);
  1370. }
  1371. else
  1372. {
  1373. LOG_ERROR("Logo Disabled - No Picture is Loaded");
  1374. };
  1375. };
  1376. try
  1377. {
  1378. vector<int> compression_params;
  1379. // compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
  1380. // compression_params.push_back(9);
  1381. compression_params.push_back(cv::IMWRITE_JPEG_QUALITY);
  1382. compression_params.push_back(m_sEmbedVideoData.compression_quality);
  1383. vector<uchar> buf;
  1384. cv::imencode(".jpg", tMat, buf, compression_params);
  1385. m_nNoSignalSize = buf.size();
  1386. n_pNoSignalData = (uint8_t *) malloc(m_nNoSignalSize);
  1387. if (n_pNoSignalData)
  1388. {
  1389. memcpy(n_pNoSignalData, buf.data(), m_nNoSignalSize);
  1390. }
  1391. else
  1392. {
  1393. m_nNoSignalSize = 0;
  1394. }
  1395. buf.clear();
  1396. #ifdef HAVE_SMAL_PREVIEW_STREAMS
  1397. // Make Small Preview Thumb
  1398. cv::Mat dst;
  1399. cv::resize(tMat, dst, cv::Size(PREVIEW_SIZE_WIDTH, PREVIEW_SIZE_HEIGHT));
  1400. cv::imencode(".jpg", dst, buf, compression_params);
  1401. m_nNoSignalSmallSize = buf.size();
  1402. n_pNoSignalSmallData = (uint8_t *) malloc(m_nNoSignalSmallSize);
  1403. if (n_pNoSignalSmallData)
  1404. {
  1405. memcpy(n_pNoSignalSmallData, buf.data(), m_nNoSignalSmallSize);
  1406. }
  1407. else
  1408. {
  1409. m_nNoSignalSmallSize = 0;
  1410. }
  1411. buf.clear();
  1412. #endif
  1413. }
  1414. catch (cv::Exception & e)
  1415. {
  1416. LOG_ERROR(e.msg.c_str());
  1417. };
  1418. #ifndef EVE_WORK_WITH_MEDIAMTX
  1419. // Socket Live
  1420. struct sockaddr sa;
  1421. struct sockaddr_in * sin;
  1422. memset(&sa, 0, sizeof(struct sockaddr));
  1423. sa.sa_family = AF_INET;
  1424. sin = (struct sockaddr_in *) &sa;
  1425. sin->sin_addr.s_addr = htonl(INADDR_ANY);
  1426. sin->sin_port = htons(m_sEmbedVideoData.port);
  1427. m_nSocketDescriptor = socket(sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0);
  1428. if (m_nSocketDescriptor == -1)
  1429. {
  1430. LOG_ERROR("Failed creating ACC socket");
  1431. return false;
  1432. };
  1433. ENABLE_SOCKOPT(m_nSocketDescriptor, SOL_SOCKET, SO_REUSEADDR);
  1434. #ifdef SO_REUSEPORT
  1435. ENABLE_SOCKOPT(m_nSocketDescriptor, SOL_SOCKET, SO_REUSEPORT);
  1436. #endif
  1437. if (bind(m_nSocketDescriptor, &sa, sizeof(sa)) < 0)
  1438. {
  1439. LOG_ERROR("Failed binding Socket");
  1440. close(m_nSocketDescriptor);
  1441. return false;
  1442. #ifdef DEBUG_EXTRA
  1443. }
  1444. else
  1445. {
  1446. LOG("Bind Socessfull");
  1447. #endif
  1448. };
  1449. if (listen(m_nSocketDescriptor, 10) != 0)
  1450. {
  1451. LOG_ERROR("Failed setting web listen backlog");
  1452. close(m_nSocketDescriptor);
  1453. return false;
  1454. #ifdef DEBUG_EXTRA
  1455. }
  1456. else
  1457. {
  1458. LOG("Listen OK");
  1459. #endif
  1460. };
  1461. // Socket Viewer
  1462. // struct sockaddr sa;
  1463. // struct sockaddr_in *sin;
  1464. memset(&sa, 0, sizeof(struct sockaddr));
  1465. sa.sa_family = AF_INET;
  1466. sin = (struct sockaddr_in *) &sa;
  1467. sin->sin_addr.s_addr = htonl(INADDR_ANY);
  1468. sin->sin_port = htons(8974);
  1469. m_nViewSocketDescriptor = socket(sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0);
  1470. if (m_nViewSocketDescriptor == -1)
  1471. {
  1472. LOG_ERROR("Failed creating ACC socket");
  1473. return false;
  1474. };
  1475. ENABLE_SOCKOPT(m_nViewSocketDescriptor, SOL_SOCKET, SO_REUSEADDR);
  1476. #ifdef SO_REUSEPORT
  1477. ENABLE_SOCKOPT(m_nViewSocketDescriptor, SOL_SOCKET, SO_REUSEPORT);
  1478. #endif
  1479. if (bind(m_nViewSocketDescriptor, &sa, sizeof(sa)) < 0)
  1480. {
  1481. LOG_ERROR("Failed binding Socket");
  1482. close(m_nViewSocketDescriptor);
  1483. return false;
  1484. #ifdef DEBUG_EXTRA
  1485. }
  1486. else
  1487. {
  1488. LOG("Bind Socessfull");
  1489. #endif
  1490. };
  1491. if (listen(m_nViewSocketDescriptor, 10) != 0)
  1492. {
  1493. LOG_ERROR("Failed setting web listen backlog");
  1494. close(m_nViewSocketDescriptor);
  1495. return false;
  1496. #ifdef DEBUG_EXTRA
  1497. }
  1498. else
  1499. {
  1500. LOG("Listen OK");
  1501. #endif
  1502. };
  1503. #ifdef DEBUG_EXTRA
  1504. LOG("Start Thread");
  1505. #endif
  1506. m_bEnabled = init();
  1507. #else // !EVE_WORK_WITH_MEDIAMTX
  1508. m_bEnabled = true;
  1509. #endif // !EVE_WORK_WITH_MEDIAMTX
  1510. applyLiveSettings();
  1511. startLive(); // a failure (port in use) is retried by validate()
  1512. return m_bEnabled;
  1513. }
  1514. bool kernelModuleEmbedVideo::stopService(bool force)
  1515. {
  1516. m_bEnabled = false;
  1517. #ifdef DEBUG_EXTRA
  1518. LOG("StopService!");
  1519. #endif
  1520. #ifndef EVE_WORK_WITH_MEDIAMTX
  1521. // Stop Conveyor
  1522. m_bDetached = uninit();
  1523. #else
  1524. m_bDetached = true; // no picture server to detach: stopping always succeeds (reloadSettings() depends on it)
  1525. #endif
  1526. m_mStreamHandlersProtector.lock();
  1527. if (m_mapHANDLERS.size())
  1528. {
  1529. #ifdef DEBUG
  1530. LOG("Deleting Stream Handlers!");
  1531. #endif
  1532. for (mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++)
  1533. {
  1534. #ifdef DEBUG
  1535. LOG("Deleting Stream Handler");
  1536. #endif
  1537. delete((*idx).second);
  1538. }
  1539. m_mapHANDLERS.clear();
  1540. };
  1541. m_mStreamHandlersProtector.unlock();
  1542. stopLive(); // after the handlers: they released their feeds
  1543. #ifndef EVE_WORK_WITH_MEDIAMTX
  1544. if (m_vHandlersPool.size())
  1545. { // Kill-Wait Started Probes
  1546. #ifdef DEBUG_EXTRA
  1547. char tB[200];
  1548. sprintf(tB, "Have to Wait Client Handlers[%d]!", m_vHandlersPool.size());
  1549. LOG(tB);
  1550. #endif
  1551. for (vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index != m_vHandlersPool.end(); index++)
  1552. {
  1553. if (force)
  1554. {
  1555. #ifdef DEBUG_EXTRA
  1556. LOG("Force Client Handler to Stop!");
  1557. #endif
  1558. pthread_cancel((*index)->m_hThreadHandle);
  1559. }
  1560. else
  1561. {
  1562. #ifdef DEBUG_EXTRA
  1563. LOG("Waiting Client Handler to End!");
  1564. #endif
  1565. pthread_join((*index)->m_hThreadHandle, NULL);
  1566. }
  1567. };
  1568. m_vHandlersPool.clear();
  1569. };
  1570. #ifdef DEBUG_EXTRA
  1571. LOG("No More Client Handlers!");
  1572. #endif
  1573. if (m_mapCAPTURES.size())
  1574. {
  1575. #ifdef DEBUG_EXTRA
  1576. LOG("Some Caps!");
  1577. #endif
  1578. for (mapSTREAMCAPS::iterator idx = m_mapCAPTURES.begin(); idx != m_mapCAPTURES.end(); idx++)
  1579. {
  1580. idx->second.clear();
  1581. }
  1582. m_mapCAPTURES.clear();
  1583. #ifdef DEBUG_EXTRA
  1584. LOG("No More Caps!");
  1585. #endif
  1586. };
  1587. #endif // !EVE_WORK_WITH_MEDIAMTX
  1588. if (m_mapMATS.size())
  1589. {
  1590. #ifdef DEBUG_EXTRA
  1591. LOG("Some Mats!");
  1592. #endif
  1593. for (mapSTREAMMAPS::iterator idx = m_mapMATS.begin(); idx != m_mapMATS.end(); idx++)
  1594. {
  1595. #ifdef DEBUG_EXTRA
  1596. LOG("Release Mat!");
  1597. #endif
  1598. idx->second.release();
  1599. };
  1600. #ifdef DEBUG_EXTRA
  1601. LOG("Clear Map Mats!");
  1602. #endif
  1603. m_mapMATS.clear();
  1604. #ifdef DEBUG_EXTRA
  1605. LOG("No More Mats!");
  1606. #endif
  1607. };
  1608. if (n_pNoSignalData)
  1609. {
  1610. #ifdef DEBUG_EXTRA
  1611. LOG("No Sig Data!");
  1612. #endif
  1613. free(n_pNoSignalData);
  1614. n_pNoSignalData = NULL;
  1615. m_nNoSignalSize = 0;
  1616. #ifdef DEBUG_EXTRA
  1617. LOG("No No Sig Data!");
  1618. #endif
  1619. };
  1620. return m_bDetached;
  1621. }
  1622. bool kernelModuleEmbedVideo::reloadSettings()
  1623. {
  1624. #ifdef DEBUG_EXTRA
  1625. LOG("Reload Service");
  1626. #endif
  1627. if (m_pDBC)
  1628. {
  1629. DBC_MODULE_EMBED_VIDEO_DATA * tDATA = m_pDBC->getEmbedVideoData(m_nDBAUXID);
  1630. if (tDATA)
  1631. {
  1632. if (stopService())
  1633. {
  1634. #ifdef DEBUG_EXTRA
  1635. LOG("Stoped!");
  1636. #endif
  1637. memcpy(&m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA));
  1638. free(tDATA);
  1639. #ifdef DEBUG_EXTRA
  1640. LOG("Starting...");
  1641. #endif
  1642. return startService();
  1643. }
  1644. else
  1645. {
  1646. free(tDATA);
  1647. };
  1648. };
  1649. };
  1650. return false;
  1651. }
  1652. #include "deviceNodeCamera.h"
  1653. #include "deviceNodeFactory.h"
  1654. bool kernelModuleEmbedVideo::validate()
  1655. {
  1656. bool RetVal = true;
  1657. // Settings changed in the DB (Mojo_Web module settings): restart the service with them.
  1658. // m_sEmbedVideoData must stay equal to the DB row, runtime state lives in other members.
  1659. if (m_pDBC)
  1660. {
  1661. DBC_MODULE_EMBED_VIDEO_DATA * tDATA = m_pDBC->getEmbedVideoData(m_nDBAUXID);
  1662. if (tDATA)
  1663. {
  1664. bool tChanged = (memcmp(&m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA)) != 0);
  1665. free(tDATA);
  1666. if (tChanged)
  1667. {
  1668. LOG("Module Settings Changed, reloading");
  1669. return reloadSettings();
  1670. };
  1671. };
  1672. };
  1673. sweepClips(); // old recorded segments, alarms whose clip is overdue
  1674. // The WebRTC server could not start (e.g. the port was still used by the MediaMTX service): retry
  1675. if (m_bEnabled && m_sEmbedVideoData.live_mode != EVE_LIVE_OFF && ! m_pWebrtc && time(NULL) >= m_tLiveRetry)
  1676. {
  1677. startLive();
  1678. };
  1679. deviceNode ** tA = NULL;
  1680. uint32_t tCNT = deviceNodeFactory::getInstance()->fetchNodes(ARGUS_ANALOG_STATIC_CAMERA, tA);
  1681. if( tCNT ){
  1682. for (uint32_t i = 0; i < tCNT; i++){
  1683. deviceNodeCamera * tCAM = (deviceNodeCamera *) tA[i];
  1684. if (! registerStream(tCAM->getCamStream(), tCAM->getFlipMode())){
  1685. RetVal = false;
  1686. // tCAM->set
  1687. continue;
  1688. };
  1689. };
  1690. free(tA);
  1691. tA = NULL;
  1692. #ifdef DEBUG_EXTRA
  1693. } else {
  1694. LOG("No Static Camera Defined/Enabled In the system!");
  1695. #endif
  1696. };
  1697. tCNT = deviceNodeFactory::getInstance()->fetchNodes(ARGUS_ANALOG_PTZ_CAMERA, tA);
  1698. if( tCNT ){
  1699. for (uint32_t i = 0; i < tCNT; i++){
  1700. deviceNodeCamera * tCAM = (deviceNodeCamera *) tA[i];
  1701. if (! registerStream(tCAM->getCamStream(), tCAM->getFlipMode())){
  1702. RetVal = false;
  1703. // tCAM->set
  1704. continue;
  1705. };
  1706. };
  1707. free(tA);
  1708. tA = NULL;
  1709. #ifdef DEBUG_EXTRA
  1710. } else {
  1711. LOG("No Analog Static Camera Defined/Enabled In the system!");
  1712. #endif
  1713. };
  1714. tCNT = deviceNodeFactory::getInstance()->fetchNodes(ARGUS_IP_STATIC_CAMERA, tA);
  1715. if( tCNT ){
  1716. for (uint32_t i = 0; i < tCNT; i++){
  1717. deviceNodeCamera * tCAM = (deviceNodeCamera *) tA[i];
  1718. if (! registerStream(tCAM->getCamStream(), tCAM->getFlipMode())){
  1719. RetVal = false;
  1720. // tCAM->set
  1721. continue;
  1722. };
  1723. };
  1724. free(tA);
  1725. tA = NULL;
  1726. #ifdef DEBUG_EXTRA
  1727. } else {
  1728. LOG("No IP Static Camera Defined/Enabled In the system!");
  1729. #endif
  1730. };
  1731. tCNT = deviceNodeFactory::getInstance()->fetchNodes(ARGUS_IP_PTZ_CAMERA, tA);
  1732. if( tCNT ){
  1733. for (uint32_t i = 0; i < tCNT; i++){
  1734. deviceNodeCamera * tCAM = (deviceNodeCamera *) tA[i];
  1735. #ifdef DEBUG_EXTRA
  1736. LOG("Registering Stream!");
  1737. #endif
  1738. if (! registerStream(tCAM->getCamStream(), tCAM->getFlipMode())){
  1739. RetVal = false;
  1740. // tCAM->set
  1741. continue;
  1742. };
  1743. };
  1744. free(tA);
  1745. tA = NULL;
  1746. #ifdef DEBUG_EXTRA
  1747. } else {
  1748. LOG("No IP PTZ Camera Defined/Enabled In the system!");
  1749. #endif
  1750. };
  1751. tCNT = deviceNodeFactory::getInstance()->fetchNodes(ARGUS_IP_PRESET_CAMERA, tA);
  1752. if( tCNT ){
  1753. for (uint32_t i = 0; i < tCNT; i++){
  1754. deviceNodeCamera * tCAM = (deviceNodeCamera *) tA[i];
  1755. if (! registerStream(tCAM->getCamStream(), tCAM->getFlipMode())){
  1756. RetVal = false;
  1757. // tCAM->set
  1758. continue;
  1759. };
  1760. };
  1761. free(tA);
  1762. tA = NULL;
  1763. #ifdef DEBUG_EXTRA
  1764. } else {
  1765. LOG("No IP Preset Camera Defined/Enabled In the system!");
  1766. #endif
  1767. };
  1768. tCNT = deviceNodeFactory::getInstance()->fetchNodes(ARGUS_ANALOG_PRESET_CAMERA, tA);
  1769. if( tCNT ){
  1770. for (uint32_t i = 0; i < tCNT; i++){
  1771. deviceNodeCamera * tCAM = (deviceNodeCamera *) tA[i];
  1772. if (! registerStream(tCAM->getCamStream(), tCAM->getFlipMode())){
  1773. RetVal = false;
  1774. // tCAM->set
  1775. continue;
  1776. };
  1777. };
  1778. free(tA);
  1779. tA = NULL;
  1780. #ifdef DEBUG_EXTRA
  1781. } else {
  1782. LOG("No Analog Preset Camera Defined/Enabled In the system!");
  1783. #endif
  1784. };
  1785. if (RetVal){
  1786. DBC_INT_LIST tInvalidList;
  1787. m_mStreamHandlersProtector.lock();
  1788. for (mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++) {
  1789. if ((*idx).second != NULL){
  1790. if (! (*idx).second->validate()){
  1791. tInvalidList.push_back((*idx).first);
  1792. };
  1793. };
  1794. };
  1795. m_mStreamHandlersProtector.unlock();
  1796. if (tInvalidList.size()){
  1797. for (DBC_INT_LIST::iterator idx = tInvalidList.begin(); idx != tInvalidList.end(); idx++){
  1798. if (unregisterStream(*idx)){
  1799. registerStream(*idx);
  1800. };
  1801. };
  1802. tInvalidList.clear();
  1803. };
  1804. };
  1805. return RetVal;
  1806. if (m_pDBC)
  1807. {
  1808. DBC_MODULE_EMBED_VIDEO_DATA * tDATA = m_pDBC->getEmbedVideoData(m_nDBAUXID);
  1809. if (tDATA)
  1810. {
  1811. if (memcmp(&m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA)) != 0)
  1812. {
  1813. free(tDATA);
  1814. #ifdef DEBUG_EXTRA
  1815. LOG("Module Settings Changed!");
  1816. #endif
  1817. return reloadSettings();
  1818. };
  1819. free(tDATA);
  1820. }
  1821. else
  1822. {
  1823. LOG_ERROR("No Fetched EVE Data");
  1824. RetVal = false;
  1825. };
  1826. if (RetVal)
  1827. {
  1828. DBC_INT_LIST * tList = m_pDBC->listMediaStreams(0, LIST_VALID_RECORDS);
  1829. if (tList != NULL)
  1830. {
  1831. for (DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++)
  1832. {
  1833. #ifdef DEBUG_EXTRA
  1834. LOG("REG STREAM");
  1835. #endif
  1836. if (! registerStream(*idx))
  1837. {
  1838. RetVal = false;
  1839. continue;
  1840. };
  1841. };
  1842. delete(tList);
  1843. #ifdef DEBUG_EXTRA
  1844. }
  1845. else
  1846. {
  1847. LOG("- No Valid Streams -");
  1848. #endif
  1849. };
  1850. };
  1851. if (RetVal)
  1852. {
  1853. DBC_INT_LIST tInvalidList;
  1854. m_mStreamHandlersProtector.lock();
  1855. for (mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++)
  1856. {
  1857. if ((*idx).second != NULL)
  1858. {
  1859. if (! (*idx).second->validate())
  1860. {
  1861. tInvalidList.push_back((*idx).first);
  1862. }
  1863. }
  1864. };
  1865. m_mStreamHandlersProtector.unlock();
  1866. if (tInvalidList.size())
  1867. {
  1868. for (DBC_INT_LIST::iterator idx = tInvalidList.begin(); idx != tInvalidList.end(); idx++)
  1869. {
  1870. if (unregisterStream(*idx))
  1871. {
  1872. registerStream(*idx);
  1873. }
  1874. };
  1875. tInvalidList.clear();
  1876. };
  1877. };
  1878. }
  1879. else
  1880. {
  1881. LOG_ERROR("DB Error!");
  1882. RetVal = false;
  1883. };
  1884. return RetVal;
  1885. }
  1886. #ifndef EVE_WORK_WITH_MEDIAMTX
  1887. bool kernelModuleEmbedVideo::registerForMediaStream(uint32_t id, WEB_CLIENT_CTX *& CTX)
  1888. {
  1889. if (CTX)
  1890. {
  1891. if (id)
  1892. {
  1893. // Check if its Valid!
  1894. DBC_MEDIA_STREAM_DATA * tSD = m_pDBC->getMediaStreamData(id);
  1895. if (tSD)
  1896. {
  1897. // if( !tSD->valid ) {
  1898. // free( tSD );
  1899. // return false;
  1900. // };
  1901. free(tSD);
  1902. // if( pipe( CTX->m_iEncoderPipe ) == -1 ){
  1903. // CTX->bValid = false;
  1904. // return false;
  1905. // };
  1906. CTX->mediaStreamId = id;
  1907. return true;
  1908. };
  1909. };
  1910. }
  1911. else
  1912. {
  1913. LOG_ERROR("Client Context error!");
  1914. }
  1915. return false;
  1916. }
  1917. #endif // !EVE_WORK_WITH_MEDIAMTX
  1918. bool kernelModuleEmbedVideo::dispatchEvent(EVENT_CONTAINER * Evt)
  1919. {
  1920. if (Evt)
  1921. {
  1922. #ifdef DEBUG_EXTRA
  1923. LOG("Dispatch EVT");
  1924. #endif
  1925. switch (Evt->m_eClass)
  1926. {
  1927. case EVT_CLASS_IMAGE:
  1928. case EVT_CLASS_VIDEO:
  1929. {
  1930. switch (Evt->m_eType)
  1931. {
  1932. case EVT_CAPTURE_START:
  1933. {
  1934. #ifdef DEBUG
  1935. LOG("Capture Event");
  1936. #endif
  1937. if (Evt->m_ref_id && Evt->m_db_id)
  1938. {
  1939. uint32_t tPicID = saveStreamPicture(Evt->m_ref_id);
  1940. if (tPicID)
  1941. {
  1942. //
  1943. // m_pDBC->addPictureEvent( Evt->m_db_id, tPicID );
  1944. }
  1945. else
  1946. {
  1947. #ifdef DEBUG
  1948. LOG_ERROR("No Picture is Saved!");
  1949. #endif
  1950. };
  1951. }
  1952. else
  1953. {
  1954. #ifdef DEBUG
  1955. LOG_ERROR("No Stream ID or Event ID in Event Data!");
  1956. #endif
  1957. };
  1958. break;
  1959. };
  1960. default: break;
  1961. };
  1962. break;
  1963. };
  1964. case EVT_CLASS_CAMERA_CTRL:
  1965. {
  1966. switch (Evt->m_eType)
  1967. {
  1968. case EVT_CAMERA_MOVE_TO:
  1969. {
  1970. #ifdef DEBUG_EXTRA
  1971. LOG("Cam OnMove After Event -> Register SourceID");
  1972. #endif
  1973. uint32_t sid = m_pDBC->getNodeAuxParam(Evt->m_nSourceNodeID);
  1974. if (sid)
  1975. {
  1976. #ifdef DEBUG_EXTRA
  1977. LOG("Source ID found!");
  1978. #endif
  1979. m_mStreamHandlersProtector.lock();
  1980. #ifdef DEBUG_EXTRA
  1981. LOG("Mutex Locked!");
  1982. #endif
  1983. mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find(sid);
  1984. if (hnd != m_mapHANDLERS.end())
  1985. #ifdef DEBUG_EXTRA
  1986. {
  1987. LOG("Handler found!");
  1988. #endif
  1989. (*hnd).second->triggerCamMove();
  1990. #ifdef DEBUG_EXTRA
  1991. LOG("Triggered!");
  1992. }
  1993. else
  1994. {
  1995. LOG("No Stream Found!");
  1996. }
  1997. #endif
  1998. m_mStreamHandlersProtector.unlock();
  1999. #ifdef DEBUG_EXTRA
  2000. LOG("Mutex Unlocked!");
  2001. #endif
  2002. }
  2003. else
  2004. {
  2005. LOG("No Stream ID Found!");
  2006. }
  2007. break;
  2008. };
  2009. case EVT_CAMERA_ON_POSITION:
  2010. {
  2011. #ifdef DEBUG_EXTRA
  2012. LOG("Cam On Position After Event -> Capture Picture");
  2013. #endif
  2014. DBC_SNAPSHOT_DATA * tData = (DBC_SNAPSHOT_DATA *) Evt->m_pEvtData;
  2015. if (tData)
  2016. {
  2017. if (! saveStreamPicture(tData))
  2018. {
  2019. LOG_ERROR("Save Error!");
  2020. }
  2021. tData->assoc_event_ids.clear();
  2022. //free(tData);
  2023. delete( tData );
  2024. Evt->m_pEvtData = NULL;
  2025. #ifdef DEBUG_EXTRA
  2026. LOG("Event Data Saved!");
  2027. #endif
  2028. }
  2029. else
  2030. {
  2031. LOG_ERROR("No Evt Data!");
  2032. }
  2033. break;
  2034. };
  2035. default: break;
  2036. };
  2037. break;
  2038. };
  2039. default: break;
  2040. };
  2041. return true;
  2042. };
  2043. return false;
  2044. }
  2045. // https://www.ps2-home.com/forum/viewtopic.php?t=98
  2046. // https://www.mikekohn.net/software/playstation2.php
  2047. bool kernelModuleEmbedVideo::saveStreamPicture(DBC_SNAPSHOT_DATA * ptr)
  2048. {
  2049. if (ptr == NULL)
  2050. {
  2051. return false;
  2052. }
  2053. if ((m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES) == EVE_OUTPUT_PICTURES)
  2054. {
  2055. #ifdef DEBUG_EXTRA
  2056. LOG("Saving Picture!");
  2057. #endif
  2058. // saveStreamPicture( ptr->stream_id );
  2059. //*
  2060. if (ptr->assoc_event_ids.size())
  2061. {
  2062. #ifndef EVE_WORK_WITH_MEDIAMTX
  2063. if (m_mapCAPTURES.find(ptr->stream_id) != m_mapCAPTURES.end())
  2064. {
  2065. m_mPictureProtector.lock();
  2066. ptr->data = (uint8_t *) malloc(m_mapCAPTURES[ptr->stream_id].size());
  2067. if (ptr->data)
  2068. {
  2069. ptr->data_size = m_mapCAPTURES[ptr->stream_id].size();
  2070. memcpy(ptr->data, m_mapCAPTURES[ptr->stream_id].data(), ptr->data_size);
  2071. m_mPictureProtector.unlock();
  2072. CSTR MD5 = MD5Binary(ptr->data, ptr->data_size);
  2073. if (MD5)
  2074. {
  2075. strncpy(ptr->md5, MD5, 32);
  2076. free(MD5);
  2077. if (! m_pDBC->addPicture(ptr, "jpg"))
  2078. {
  2079. LOG_ERROR("Database Error to consume capture!");
  2080. }
  2081. }
  2082. else
  2083. {
  2084. LOG_ERROR("no MD5 Hash!");
  2085. }
  2086. free(ptr->data);
  2087. }
  2088. else
  2089. {
  2090. m_mPictureProtector.unlock();
  2091. LOG_ERROR("No memory to allocate!");
  2092. };
  2093. #ifdef DEBUG_EXTRA
  2094. }
  2095. else
  2096. {
  2097. LOG("No apropriate Stream Found!");
  2098. #endif
  2099. };
  2100. #endif // !EVE_WORK_WITH_MEDIAMTX
  2101. };
  2102. //*/
  2103. #ifdef DEBUG_EXTRA
  2104. }
  2105. else
  2106. {
  2107. LOG("No Pic Mode!");
  2108. #endif
  2109. }
  2110. if ((m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO) == EVE_OUTPUT_VIDEO)
  2111. {
  2112. #ifdef DEBUG
  2113. LOG("Saving Video!");
  2114. #endif
  2115. if (ptr->assoc_event_ids.size() && liveClipsActive())
  2116. {
  2117. for (DBC_INT_LIST::iterator idx = ptr->assoc_event_ids.begin(); idx < ptr->assoc_event_ids.end(); idx++)
  2118. {
  2119. clipAlarm(ptr->stream_id, *idx);
  2120. };
  2121. }
  2122. else if (ptr->assoc_event_ids.size())
  2123. {
  2124. m_mStreamHandlersProtector.lock();
  2125. mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find(ptr->stream_id);
  2126. if (hnd != m_mapHANDLERS.end())
  2127. {
  2128. uint32_t db_id;
  2129. uint32_t cfrm;
  2130. for (DBC_INT_LIST::iterator idx = ptr->assoc_event_ids.begin(); idx < ptr->assoc_event_ids.end(); idx++)
  2131. {
  2132. (*hnd).second->triggerEvent(*idx, db_id, cfrm);
  2133. }
  2134. #ifdef DEBUG
  2135. }
  2136. else
  2137. {
  2138. LOG("No Stream Found!");
  2139. #endif
  2140. };
  2141. m_mStreamHandlersProtector.unlock();
  2142. #ifdef DEBUG_EXTRA
  2143. }
  2144. else
  2145. {
  2146. LOG("No Assoc EVTIDS!");
  2147. #endif
  2148. };
  2149. #ifdef DEBUG
  2150. }
  2151. else
  2152. {
  2153. LOG("No Video Mode!");
  2154. #endif
  2155. };
  2156. return true;
  2157. }
  2158. bool kernelModuleEmbedVideo::saveStreamPicture(uint32_t id)
  2159. {
  2160. if (! id)
  2161. {
  2162. return false;
  2163. }
  2164. if (m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES)
  2165. {
  2166. #ifndef EVE_WORK_WITH_MEDIAMTX
  2167. if (m_mapCAPTURES.find(id) != m_mapCAPTURES.end())
  2168. {
  2169. //FILE * tFD;
  2170. m_mPictureProtector.lock();
  2171. size_t tBufferSize = m_mapCAPTURES[id].size();
  2172. uint8_t * tBuffer = (uint8_t *) malloc(tBufferSize);
  2173. if (tBuffer)
  2174. {
  2175. memcpy(tBuffer, m_mapCAPTURES[id].data(), tBufferSize);
  2176. m_mPictureProtector.unlock();
  2177. CSTR MD5 = MD5Binary(tBuffer, tBufferSize);
  2178. if (MD5)
  2179. {
  2180. char tFileName[MAX_PATH];
  2181. if (generateSavePicPath(MD5, tFileName))
  2182. {
  2183. FILE * fd = fopen(tFileName, "wb+");
  2184. if (fd)
  2185. {
  2186. fwrite(tBuffer, 1, tBufferSize, fd);
  2187. fclose(fd);
  2188. ch_chown(tFileName, "nobody", "nogroup");
  2189. // retVal = m_pDBC->addPicture( id, MD5, "jpg" );
  2190. }
  2191. else
  2192. {
  2193. LOG_ERROR("Can not open picture file!");
  2194. }
  2195. }
  2196. else
  2197. {
  2198. LOG_ERROR("Can not generate file name!");
  2199. }
  2200. free(MD5);
  2201. }
  2202. else
  2203. {
  2204. LOG_ERROR("no MD5 Hash!");
  2205. }
  2206. free(tBuffer);
  2207. }
  2208. else
  2209. {
  2210. m_mPictureProtector.unlock();
  2211. LOG_ERROR("no memory to allocate!");
  2212. };
  2213. };
  2214. #endif // !EVE_WORK_WITH_MEDIAMTX
  2215. }
  2216. return true;
  2217. }
  2218. int kernelModuleEmbedVideo::getWidh(void)
  2219. {
  2220. if (m_sEmbedVideoData.width)
  2221. {
  2222. return m_sEmbedVideoData.width;
  2223. }
  2224. return -1;
  2225. }
  2226. int kernelModuleEmbedVideo::getHeight(void)
  2227. {
  2228. if (m_sEmbedVideoData.height)
  2229. {
  2230. return m_sEmbedVideoData.height;
  2231. }
  2232. return -1;
  2233. }
  2234. bool kernelModuleEmbedVideo::generateSavePicPath(CSTR MD5, CSTR Output)
  2235. {
  2236. if (MD5 == NULL)
  2237. {
  2238. return false;
  2239. }
  2240. if (Output == NULL)
  2241. {
  2242. return false;
  2243. }
  2244. if (! fileExist(m_pBaseSavePath))
  2245. {
  2246. LOG_ERROR("No Base Picture Save Path Defined!");
  2247. return false;
  2248. };
  2249. if (strlen(MD5) < 4)
  2250. {
  2251. return false;
  2252. }
  2253. char test[5000];
  2254. sprintf(test, "%s/%c%c", m_pBaseSavePath, MD5[0], MD5[1]);
  2255. if (! fileExist(test))
  2256. {
  2257. #ifdef __linux__
  2258. mkdir(test, STORAGE_DIR_MODE);
  2259. #else
  2260. _mkdir(test);
  2261. #endif
  2262. ch_chown(test, "nobody", "nogroup");
  2263. };
  2264. sprintf(test, "%s/%c%c/%c%c", m_pBaseSavePath, MD5[0], MD5[1], MD5[2], MD5[3]);
  2265. if (! fileExist(test))
  2266. {
  2267. #ifdef __linux__
  2268. mkdir(test, STORAGE_DIR_MODE);
  2269. #else
  2270. _mkdir(test);
  2271. #endif
  2272. ch_chown(test, "nobody", "nogroup");
  2273. };
  2274. sprintf(Output, "%s/%c%c/%c%c/%s.jpg", m_pBaseSavePath, MD5[0], MD5[1], MD5[2], MD5[3], MD5);
  2275. return true;
  2276. }
  2277. bool kernelModuleEmbedVideo::registerStream(uint32_t streamID, uint8_t flip_mode)
  2278. {
  2279. // return true;
  2280. try
  2281. {
  2282. m_mStreamHandlersProtector.lock();
  2283. streamHandler * tData = m_mapHANDLERS.at(streamID);
  2284. // If SH allready exists
  2285. if (tData != NULL)
  2286. {
  2287. #ifdef DEBUG_EXTRA
  2288. LOG("Stream Exists!");
  2289. #endif
  2290. m_mStreamHandlersProtector.unlock();
  2291. return true;
  2292. };
  2293. #ifdef DEBUG_EXTRA
  2294. LOG( "Create New Stream Handler!" );
  2295. #endif
  2296. // Alarm clips: from the recorder segments when it records (liveClipsActive), else the old encoder
  2297. if ((m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO) != EVE_OUTPUT_VIDEO || liveClipsActive())
  2298. {
  2299. tData = new streamHandler(this, MS_MODE_DECODE_FRAMES, flip_mode);
  2300. }
  2301. else
  2302. {
  2303. tData = new streamHandler(this, MS_MODE_ENCODE_FRAMES, flip_mode);
  2304. };
  2305. if (tData != NULL)
  2306. {
  2307. if (tData->create(m_pDBC, streamID))
  2308. {
  2309. m_mapHANDLERS[streamID] = tData;
  2310. m_mStreamHandlersProtector.unlock();
  2311. return true;
  2312. }
  2313. else
  2314. {
  2315. LOG_ERROR("Error Creating new Stream Handler[t]!");
  2316. delete(tData);
  2317. m_mapHANDLERS[streamID] = NULL;
  2318. };
  2319. }
  2320. else
  2321. {
  2322. LOG_ERROR("Error Constructing new Stream Handler[t]!");
  2323. };
  2324. m_mStreamHandlersProtector.unlock();
  2325. }
  2326. catch (const std::out_of_range & oor)
  2327. {
  2328. #ifdef DEBUG_EXTRA
  2329. LOG("Exception Catched - Stream Handler not found in collection!");
  2330. #endif
  2331. streamHandler * tSH = NULL;
  2332. // Create New One
  2333. if ((m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO) != EVE_OUTPUT_VIDEO || liveClipsActive())
  2334. {
  2335. #ifdef DEBUG_EXTRA
  2336. LOG("New 1");
  2337. #endif
  2338. tSH = new streamHandler(this, MS_MODE_DECODE_FRAMES, flip_mode);
  2339. }
  2340. else
  2341. {
  2342. #ifdef DEBUG_EXTRA
  2343. LOG("New 2");
  2344. #endif
  2345. tSH = new streamHandler(this, MS_MODE_ENCODE_FRAMES, flip_mode);
  2346. #ifdef DEBUG_EXTRA
  2347. LOG("A C");
  2348. #endif
  2349. };
  2350. if (tSH != NULL)
  2351. {
  2352. #ifdef DEBUG_EXTRA
  2353. LOG("Constructed Ok");
  2354. #endif
  2355. if (tSH->create(m_pDBC, streamID))
  2356. {
  2357. #ifdef DEBUG_EXTRA
  2358. LOG("Put to map");
  2359. #endif
  2360. m_mapHANDLERS[streamID] = tSH;
  2361. m_mStreamHandlersProtector.unlock();
  2362. return true;
  2363. }
  2364. else
  2365. {
  2366. LOG_ERROR("Error Creating new Stream Handler[c]!");
  2367. delete(tSH);
  2368. m_mapHANDLERS[streamID] = NULL;
  2369. };
  2370. }
  2371. else
  2372. {
  2373. LOG_ERROR("Error Constructing new Stream Handler[c]!");
  2374. };
  2375. m_mStreamHandlersProtector.unlock();
  2376. };
  2377. return false;
  2378. }
  2379. bool kernelModuleEmbedVideo::unregisterStream(uint32_t streamID)
  2380. {
  2381. try
  2382. {
  2383. m_mStreamHandlersProtector.lock();
  2384. streamHandler * tData = m_mapHANDLERS.at(streamID);
  2385. if (tData != NULL)
  2386. {
  2387. delete(tData);
  2388. // ToDo: Remove Stream Mats and Clients Connected to a Stream ( or Push them No Signal Image )
  2389. m_mapHANDLERS[streamID] = NULL;
  2390. m_mStreamHandlersProtector.unlock();
  2391. return true;
  2392. };
  2393. m_mStreamHandlersProtector.unlock();
  2394. LOG_ERROR("Registered Stream is Empty!");
  2395. }
  2396. catch (const std::out_of_range & oor)
  2397. {
  2398. m_mStreamHandlersProtector.unlock();
  2399. LOG_ERROR("No Such Stream Registered!");
  2400. };
  2401. return false;
  2402. }
  2403. cv::Mat *kernelModuleEmbedVideo::getCurrentFrame( uint32_t streamID ){
  2404. cv::Mat *retVal = NULL;
  2405. return retVal;
  2406. }
  2407. /* ---------------------------------------------------------------- live view (WebRTC) and recording */
  2408. void kernelModuleEmbedVideo::applyLiveSettings()
  2409. {
  2410. m_sLiveConf = mtx::ServerConf();
  2411. m_sLiveConf.webrtcAddress = ":" + std::to_string(m_sEmbedVideoData.live_port ? m_sEmbedVideoData.live_port : 8889);
  2412. // next to the module's own clips; kernelHelperMediaMTX indexes <scratch>/stream_<node>/*.mp4
  2413. m_sLiveConf.recordPath = std::string(m_pVideoScratchPath) + "/%path/%Y-%m-%d_%H-%M-%S-%f";
  2414. m_sLiveConf.recordSegmentDurationMs = (int64_t) (m_sEmbedVideoData.live_record_segment ? m_sEmbedVideoData.live_record_segment : 60) * 1000;
  2415. m_sLiveConf.recordPartDurationMs = 1000;
  2416. m_sLiveConf.onSegmentDone = [this](const mtx::SegmentInfo & info) { onLiveSegment(info); };
  2417. {
  2418. std::lock_guard<std::mutex> lock(m_mClips);
  2419. m_nClipWaitUs = m_sLiveConf.recordSegmentDurationMs * 1000LL + 60000000LL; // + the post-alarm time
  2420. }
  2421. m_sLiveConf.webrtcICEServers.clear();
  2422. std::string tIce(m_sEmbedVideoData.live_ice_servers);
  2423. size_t tPos = 0;
  2424. while (tPos < tIce.size())
  2425. {
  2426. size_t tEnd = tIce.find_first_of(", ", tPos);
  2427. std::string tOne = tIce.substr(tPos, tEnd == std::string::npos ? std::string::npos : tEnd - tPos);
  2428. if (! tOne.empty())
  2429. {
  2430. m_sLiveConf.webrtcICEServers.push_back(tOne);
  2431. };
  2432. if (tEnd == std::string::npos)
  2433. {
  2434. break;
  2435. };
  2436. tPos = tEnd + 1;
  2437. };
  2438. }
  2439. bool kernelModuleEmbedVideo::startLive()
  2440. {
  2441. if (m_sEmbedVideoData.live_mode == EVE_LIVE_OFF)
  2442. {
  2443. return true;
  2444. };
  2445. if (m_pWebrtc)
  2446. {
  2447. return true;
  2448. };
  2449. std::unique_ptr<mtx::WebrtcServer> tServer(new mtx::WebrtcServer(m_sLiveConf, this));
  2450. std::string tErr;
  2451. if (! tServer->start(tErr))
  2452. {
  2453. char tB[512];
  2454. snprintf(tB, sizeof(tB), "Live view: the WebRTC server cannot listen on %s (%s) - retry in 10 s", m_sLiveConf.webrtcAddress.c_str(), tErr.c_str());
  2455. LOG_ERROR(tB);
  2456. m_tLiveRetry = time(NULL) + 10;
  2457. return false;
  2458. };
  2459. m_pWebrtc = std::move(tServer);
  2460. char tB[256];
  2461. snprintf(tB, sizeof(tB), "Live view: WebRTC (WHEP) on %s, %s, recording %s", m_sLiveConf.webrtcAddress.c_str(),
  2462. m_sEmbedVideoData.live_mode == EVE_LIVE_ENCODE ? "processed frames (encoded)" : "camera H264 (passthrough)", m_sEmbedVideoData.live_record ? "on" : "off");
  2463. LOG(tB);
  2464. return true;
  2465. }
  2466. void kernelModuleEmbedVideo::stopLive()
  2467. {
  2468. if (m_pWebrtc)
  2469. {
  2470. m_pWebrtc->stop(); // closes the sessions (they hold their paths)
  2471. m_pWebrtc.reset();
  2472. };
  2473. std::map<std::string, std::shared_ptr<mtx::MediaPath>> tPaths;
  2474. {
  2475. std::lock_guard<std::mutex> lock(m_mLivePaths);
  2476. tPaths.swap(m_mapLivePaths);
  2477. }
  2478. for (auto & p : tPaths)
  2479. {
  2480. p.second->sourceSetNotReady(); // closes the recording
  2481. };
  2482. purgeClips(); // nothing records now: no segment is wanted any more
  2483. }
  2484. std::shared_ptr<mtx::MediaPath> kernelModuleEmbedVideo::livePath(uint32_t nodeID)
  2485. {
  2486. if (m_sEmbedVideoData.live_mode == EVE_LIVE_OFF || nodeID == 0)
  2487. {
  2488. return nullptr;
  2489. };
  2490. std::string tName = "stream_" + std::to_string(nodeID);
  2491. std::lock_guard<std::mutex> lock(m_mLivePaths);
  2492. auto it = m_mapLivePaths.find(tName);
  2493. if (it != m_mapLivePaths.end())
  2494. {
  2495. return it->second;
  2496. };
  2497. auto tPath = std::make_shared<mtx::MediaPath>(tName, m_sEmbedVideoData.live_record, m_sLiveConf);
  2498. m_mapLivePaths[tName] = tPath;
  2499. return tPath;
  2500. }
  2501. std::shared_ptr<mtx::MediaPath> kernelModuleEmbedVideo::findPath(const std::string & name) const
  2502. {
  2503. std::lock_guard<std::mutex> lock(m_mLivePaths);
  2504. auto it = m_mapLivePaths.find(name);
  2505. return (it == m_mapLivePaths.end()) ? nullptr : it->second;
  2506. }
  2507. /* ---------------------------------------------------------------- alarm clips from the recorder
  2508. When the recorder writes segments (live_record), the alarm clips come from them and the old encoder
  2509. (MS_MODE_ENCODE_FRAMES) is not started, so the video is no longer encoded and written twice.
  2510. The scratch is in shared memory (/dev/shm), so it holds as little as possible:
  2511. - an alarm (saveStreamPicture -> clipAlarm) wants the segments within EVE_CLIP_PRE_ALARM_MS before
  2512. and EVE_CLIP_POST_ALARM_MS after it. Those segments are handed to the kernel like the old encoder's
  2513. clips: moved (renamed) to <scratch>/<md5>.mp4 in a VIDEO_SEGMENT_INFO with EVT_CAPTURE_DONE. The
  2514. alarm is bound (eventIDS / eventFrames) to the segment it happened in;
  2515. - mojoKernel::handleVideo copies the clip into the report folder and deletes it from the scratch
  2516. (or the remote server keeps it until sent);
  2517. - a closed segment no alarm wants is deleted once its end is EVE_CLIP_PRE_ALARM_MS (+ EVE_CLIP_LAG_MS)
  2518. in the past: a later alarm cannot want it any more. So only the segment being recorded and the
  2519. last closed one (for a few seconds) are in <scratch>/stream_<node>;
  2520. - left-overs (a crash, a previous run) are deleted by the scan in sweepClips(), and everything
  2521. when the recording stops (purgeClips()).
  2522. */
  2523. #ifndef EVE_CLIP_PRE_ALARM_MS
  2524. #define EVE_CLIP_PRE_ALARM_MS 5000
  2525. #endif
  2526. #ifndef EVE_CLIP_POST_ALARM_MS
  2527. #define EVE_CLIP_POST_ALARM_MS 5000
  2528. #endif
  2529. #ifndef EVE_CLIP_LAG_MS
  2530. #define EVE_CLIP_LAG_MS 2000 // an alarm reaches clipAlarm() at most this late (event dispatch)
  2531. #endif
  2532. #ifndef EVE_CLIP_LEFTOVER_S
  2533. #define EVE_CLIP_LEFTOVER_S 30 // a file in <scratch>/stream_* not written for this long is not recorded any more
  2534. #endif
  2535. bool kernelModuleEmbedVideo::liveClipsActive(void) const
  2536. {
  2537. return m_sEmbedVideoData.live_mode != EVE_LIVE_OFF && m_sEmbedVideoData.live_record;
  2538. }
  2539. void kernelModuleEmbedVideo::registerClipStream(const std::string & path, uint32_t streamID, uint64_t sourceID, uint8_t fps)
  2540. {
  2541. std::lock_guard<std::mutex> lock(m_mClips);
  2542. EveClipStream & tS = m_mapClips[path];
  2543. tS.streamID = streamID;
  2544. tS.sourceID = sourceID;
  2545. tS.fps = fps ? fps : 25;
  2546. }
  2547. void kernelModuleEmbedVideo::clipAlarm(uint32_t streamID, uint32_t eventID)
  2548. {
  2549. int64_t tNow = mtx::nowUs();
  2550. std::lock_guard<std::mutex> lock(m_mClips);
  2551. for (auto & c : m_mapClips)
  2552. {
  2553. if (c.second.streamID == streamID)
  2554. {
  2555. c.second.alarms.push_back({eventID, tNow, false});
  2556. matchClipsLocked(c.second, tNow); // the pre-alarm part may be recorded already
  2557. return;
  2558. };
  2559. };
  2560. char tB[128];
  2561. snprintf(tB, sizeof(tB), "Alarm clip: stream %u is not recorded - no clip for event %u", streamID, eventID);
  2562. LOG_ERROR(tB);
  2563. }
  2564. // Recorder thread: a segment is complete
  2565. void kernelModuleEmbedVideo::onLiveSegment(const mtx::SegmentInfo & info)
  2566. {
  2567. std::lock_guard<std::mutex> lock(m_mClips);
  2568. EveClipStream & tS = m_mapClips[info.path];
  2569. int64_t tNow = mtx::nowUs();
  2570. tS.segments.push_back({info.file, info.startUs, info.startUs + info.durationUs, info.width, info.height, false});
  2571. matchClipsLocked(tS, tNow);
  2572. pruneClipsLocked(tS, tNow);
  2573. }
  2574. // Drops the segments that are handed over (the file is moved) or that no alarm can want any more (deleted)
  2575. void kernelModuleEmbedVideo::pruneClipsLocked(EveClipStream & stream, int64_t nowUs)
  2576. {
  2577. for (auto it = stream.segments.begin(); it != stream.segments.end();)
  2578. {
  2579. if (it->handed)
  2580. {
  2581. it = stream.segments.erase(it);
  2582. }
  2583. else if (nowUs - it->endUs > (EVE_CLIP_PRE_ALARM_MS + EVE_CLIP_LAG_MS) * 1000LL)
  2584. {
  2585. unlink(it->file.c_str());
  2586. it = stream.segments.erase(it);
  2587. }
  2588. else
  2589. {
  2590. ++it;
  2591. };
  2592. };
  2593. }
  2594. void kernelModuleEmbedVideo::matchClipsLocked(EveClipStream & stream, int64_t nowUs)
  2595. {
  2596. if (stream.alarms.empty())
  2597. {
  2598. return;
  2599. };
  2600. for (EveClipSegment & tSeg : stream.segments)
  2601. {
  2602. if (tSeg.handed)
  2603. {
  2604. continue;
  2605. };
  2606. for (const EveClipAlarm & a : stream.alarms)
  2607. {
  2608. if (a.timeUs - EVE_CLIP_PRE_ALARM_MS * 1000LL < tSeg.endUs && a.timeUs + EVE_CLIP_POST_ALARM_MS * 1000LL > tSeg.startUs)
  2609. {
  2610. handOffClipLocked(stream, tSeg);
  2611. break;
  2612. };
  2613. };
  2614. };
  2615. // An alarm is done when its segment is handed over and the post-alarm time is recorded
  2616. int64_t tRecordedUntil = stream.segments.empty() ? 0 : stream.segments.back().endUs;
  2617. int64_t tWaitUs = (m_nClipWaitUs > 0 ? m_nClipWaitUs : 120000000LL) + EVE_CLIP_POST_ALARM_MS * 1000LL;
  2618. for (auto it = stream.alarms.begin(); it != stream.alarms.end();)
  2619. {
  2620. bool tDone = it->bound && tRecordedUntil >= it->timeUs + EVE_CLIP_POST_ALARM_MS * 1000LL;
  2621. // nothing recorded for it (stream down): give up after a while
  2622. bool tLost = ! it->bound && nowUs - it->timeUs > tWaitUs;
  2623. if (tLost)
  2624. {
  2625. char tB[128];
  2626. snprintf(tB, sizeof(tB), "Alarm clip: nothing recorded for event %u - no clip", it->eventID);
  2627. LOG_ERROR(tB);
  2628. };
  2629. if (tDone || tLost || (it->bound && nowUs - it->timeUs > tWaitUs))
  2630. {
  2631. it = stream.alarms.erase(it);
  2632. }
  2633. else
  2634. {
  2635. ++it;
  2636. };
  2637. };
  2638. }
  2639. bool kernelModuleEmbedVideo::handOffClipLocked(EveClipStream & stream, EveClipSegment & seg)
  2640. {
  2641. seg.handed = true; // also on failure: do not retry every time
  2642. if (stream.streamID == 0)
  2643. {
  2644. return false; // a path no stream handler registered (cannot happen: initLive registers it)
  2645. };
  2646. CSTR tMD5 = getUniqID_MD5();
  2647. if (tMD5 == NULL)
  2648. {
  2649. LOG_ERROR("Alarm clip: no MD5");
  2650. return false;
  2651. };
  2652. VIDEO_SEGMENT_INFO * tSI = new VIDEO_SEGMENT_INFO(); // owned by the receiver (mojoKernel deletes it)
  2653. snprintf(tSI->scratchPath, sizeof(tSI->scratchPath), "%s/%s.mp4", m_pVideoScratchPath, tMD5);
  2654. strncpy(tSI->recordMD5, tMD5, 32);
  2655. tSI->recordMD5[32] = (char) 0;
  2656. free(tMD5);
  2657. // moved: the kernel copies it into the report folder and deletes it (no copy left in the scratch)
  2658. if (rename(seg.file.c_str(), tSI->scratchPath) != 0 && (fileCopy(seg.file.c_str(), tSI->scratchPath) != 0 || unlink(seg.file.c_str()) != 0))
  2659. {
  2660. char tB[PATH_MAX + 64];
  2661. snprintf(tB, sizeof(tB), "Alarm clip: cannot move %s (%s)", seg.file.c_str(), strerror(errno));
  2662. LOG_ERROR(tB);
  2663. unlink(seg.file.c_str());
  2664. delete tSI;
  2665. return false;
  2666. };
  2667. strncpy(tSI->recordEXT, "mp4", sizeof(tSI->recordEXT));
  2668. tSI->stream_id = stream.streamID;
  2669. tSI->streamTSS = (uint32_t) (seg.startUs / 1000000);
  2670. tSI->streamTMS = (uint32_t) ((seg.startUs / 1000) % 1000);
  2671. tSI->streamFPS = stream.fps;
  2672. tSI->streamWidth = (uint16_t) seg.width;
  2673. tSI->streamHeight = (uint16_t) seg.height;
  2674. struct stat tSt;
  2675. tSI->dataSize = (stat(tSI->scratchPath, &tSt) == 0) ? (uint32_t) tSt.st_size : 0;
  2676. for (EveClipAlarm & a : stream.alarms)
  2677. {
  2678. // the segment the alarm happened in (or the first one after it: nothing recorded at its time)
  2679. if (! a.bound && a.timeUs < seg.endUs)
  2680. {
  2681. a.bound = true;
  2682. int64_t tOffset = a.timeUs > seg.startUs ? a.timeUs - seg.startUs : 0;
  2683. tSI->eventIDS.push_back(a.eventID);
  2684. tSI->eventTSS.push_back((uint32_t) (a.timeUs / 1000000));
  2685. tSI->eventTMS.push_back((uint32_t) ((a.timeUs / 1000) % 1000));
  2686. tSI->eventFrames.push_back((uint32_t) (tOffset * stream.fps / 1000000));
  2687. };
  2688. };
  2689. EVENT_CONTAINER * bEVT = createBasicEvent(stream.sourceID, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, tSI);
  2690. if (bEVT == NULL)
  2691. {
  2692. LOG_ERROR("Alarm clip: event creation failure!");
  2693. unlink(tSI->scratchPath);
  2694. delete tSI;
  2695. return false;
  2696. };
  2697. char tB[PATH_MAX + 96];
  2698. snprintf(tB, sizeof(tB), "Alarm clip: %s (%u event(s))", seg.file.c_str(), (unsigned) tSI->eventIDS.size());
  2699. LOG(tB);
  2700. basicEventHeap::getInstance()->broadcast(bEVT);
  2701. return true;
  2702. }
  2703. // validate(): deletes segments no alarm wants, checks the alarms; every minute also left-overs (a previous run)
  2704. void kernelModuleEmbedVideo::sweepClips(void)
  2705. {
  2706. int64_t tNow = mtx::nowUs();
  2707. {
  2708. std::lock_guard<std::mutex> lock(m_mClips);
  2709. for (auto & c : m_mapClips)
  2710. {
  2711. matchClipsLocked(c.second, tNow);
  2712. pruneClipsLocked(c.second, tNow);
  2713. };
  2714. }
  2715. time_t tSec = time(NULL);
  2716. if (tSec - m_tClipsScan < 60)
  2717. {
  2718. return;
  2719. };
  2720. m_tClipsScan = tSec;
  2721. // <scratch>/stream_*/*.mp4 not written for a while and not tracked: left-overs (crash, previous run)
  2722. DIR * tDir = opendir(m_pVideoScratchPath);
  2723. if (tDir == NULL)
  2724. {
  2725. return;
  2726. };
  2727. struct dirent * tE;
  2728. while ((tE = readdir(tDir)) != NULL)
  2729. {
  2730. if (strncmp(tE->d_name, "stream_", 7) != 0)
  2731. {
  2732. continue;
  2733. };
  2734. std::string tSub = std::string(m_pVideoScratchPath) + "/" + tE->d_name;
  2735. DIR * tD = opendir(tSub.c_str());
  2736. if (tD == NULL)
  2737. {
  2738. continue;
  2739. };
  2740. struct dirent * tF;
  2741. while ((tF = readdir(tD)) != NULL)
  2742. {
  2743. size_t tLen = strlen(tF->d_name);
  2744. if (tLen < 4 || strcmp(tF->d_name + tLen - 4, ".mp4") != 0)
  2745. {
  2746. continue;
  2747. };
  2748. std::string tFile = tSub + "/" + tF->d_name;
  2749. struct stat tSt;
  2750. if (stat(tFile.c_str(), &tSt) == 0 && S_ISREG(tSt.st_mode) && tSec - tSt.st_mtime > EVE_CLIP_LEFTOVER_S)
  2751. {
  2752. std::lock_guard<std::mutex> lock(m_mClips);
  2753. bool tTracked = false;
  2754. for (auto & c : m_mapClips)
  2755. {
  2756. for (const EveClipSegment & tSeg : c.second.segments)
  2757. {
  2758. tTracked = tTracked || tSeg.file == tFile;
  2759. };
  2760. };
  2761. if (! tTracked)
  2762. {
  2763. unlink(tFile.c_str());
  2764. };
  2765. };
  2766. };
  2767. closedir(tD);
  2768. };
  2769. closedir(tDir);
  2770. }
  2771. // stopLive(): the recording is closed (its last segment was handed over if an alarm wanted it),
  2772. // so the remaining segments and the stream folders go; alarms still waiting get no clip
  2773. void kernelModuleEmbedVideo::purgeClips(void)
  2774. {
  2775. std::lock_guard<std::mutex> lock(m_mClips);
  2776. for (auto & c : m_mapClips)
  2777. {
  2778. for (const EveClipSegment & tSeg : c.second.segments)
  2779. {
  2780. if (! tSeg.handed)
  2781. {
  2782. unlink(tSeg.file.c_str());
  2783. };
  2784. };
  2785. c.second.segments.clear();
  2786. for (const EveClipAlarm & a : c.second.alarms)
  2787. {
  2788. if (! a.bound)
  2789. {
  2790. char tB[128];
  2791. snprintf(tB, sizeof(tB), "Alarm clip: recording stopped - no clip for event %u", a.eventID);
  2792. LOG_ERROR(tB);
  2793. };
  2794. };
  2795. c.second.alarms.clear();
  2796. rmdir((std::string(m_pVideoScratchPath) + "/" + c.first).c_str()); // only if empty
  2797. };
  2798. }
  2799. #undef TLOG
  2800. #undef TLOG_ERROR
  2801. #else //LRF_PROXY_ONLY
  2802. kernelModuleEmbedVideo::kernelModuleEmbedVideo(uint32_t moduleID) :
  2803. kernelModule(moduleID, KERNEL_MODULE_EMBED_VIDEO)
  2804. {
  2805. }
  2806. kernelModuleEmbedVideo::~kernelModuleEmbedVideo()
  2807. {
  2808. detachEvents(); // stop event delivery before the members are destroyed (see basicEventHandler.h)
  2809. }
  2810. #endif //LRF_PROXY_ONLY
  2811. #undef LOG
  2812. #undef LOG_ERROR
  2813. //#undef DEBUG_EXTRA