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.

3788 lines
145 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
la_mojo: fix memory leaks and heap corruption Continuous leaks: - protocolParser: on package-pool overflow the oldest package was removed but never freed while the newest (still pooled) one was freed. Every packet a handler does not consume (e.g. other sensors on a shared bus) leaked once the pool was full. Free the removed package, free pooled packages in the destructor and getPackage(), use memmove for the overlapping buffer shifts. - SQLite_Connector::Query: loop only while sqlite3_step() returns SQLITE_ROW. Looping until SQLITE_DONE spun forever allocating rows on SQLITE_BUSY/ERROR. Set a busy timeout, close handles after a failed open, fix escapeBinary() writing into uninitialised buffers. - basicThread/basicDualThread: threads that ended by themselves were never joined, leaking their stacks on every stream drop/restart. Always join once (detach when called from the thread itself); check pthread_create result correctly. - curlRequest: free the header list; initialise m_pPostData and the content type; curlRequestsManager deletes requests it cannot queue. - kernelModuleModemManager: free the phonebook ID list on every reload. - deviceNodeFactory: do not append the same pending node every cycle. - streamHandler: free frames left in the encoding queue on destruction. Heap corruption: - kernelModuleFactory: module that failed to start was deleted twice. - mojoRemoteClient: basicRing::push() returns an ID (may be 0), not a bool; compare with -1. Fix packetExtractor and destructor leaks. - utilizeBasicEvent: payloads are malloc'ed, release with free(). - videoAVLIBSource: avoid sws context double free, NULL check order. - trim(): memmove for overlapping copy. Smaller leaks: dropSession duplicate query, LRF upload data, report backupper / fly hunter settings, Kafka consumer handle, BVMS uniq ID. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
23 hours ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "streamHandler.h"
  2. //#define DEBUG_EXTRA
  3. #ifndef LRF_PROXY_ONLY
  4. // #include "rgooseHardwareResourceNetworkProvider.h"
  5. // #include "mojoKernel.h"
  6. #include "../alg/generic/base64.h"
  7. #include "../data/media/video/videoAVLIBSource.h"
  8. #include "../data/media/video/videoLive555AVLibSource.h"
  9. #include <arpa/inet.h>
  10. #include <ctype.h>
  11. #include <err.h>
  12. #include <errno.h>
  13. #include <getopt.h>
  14. #include <ifaddrs.h>
  15. #include <netdb.h>
  16. #include <netinet/ip.h>
  17. #include <netinet/udp.h>
  18. #include <openssl/sha.h>
  19. #include <paths.h>
  20. #include <poll.h>
  21. #include <signal.h>
  22. #include <stdint.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <sys/param.h> /* MIN() */
  27. #include <sys/socket.h>
  28. #include <time.h>
  29. #include <unistd.h>
  30. // #define DEBUG
  31. // #undef DEBUG_EXTRA
  32. #ifndef STORAGE_DIR_MODE
  33. #define STORAGE_DIR_MODE 0x1FF
  34. #endif
  35. #ifndef STORAGE_FILE_MODE
  36. #define STORAGE_FILE_MODE 0x1B6
  37. #endif
  38. #define LOG(X) m_pLog->Log("MEV_STR", this, X)
  39. #ifdef DEBUG
  40. #define LOG_ERROR(X) \
  41. { \
  42. char _tBfrErrMSG2w34[256]; \
  43. sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \
  44. m_pLog->Log("MEV_STR", this, _LOG_ERROR, _tBfrErrMSG2w34); \
  45. }
  46. #else
  47. #define LOG_ERROR(X) m_pLog->Log("MEV_STR", this, _LOG_ERROR, X);
  48. #endif
  49. streamHandler::streamHandler(kernelModuleEmbedVideo * ptr, MS_WORK_MODE M, uint8_t flip_mode) :
  50. basicMediaDestination()
  51. #ifdef EVE_ENABLE_VIDEO
  52. , basicThread()
  53. #endif
  54. {
  55. m_pMaster = ptr;
  56. m_eWM = M;
  57. m_pLog = basicLogCollection::getInstance();
  58. LOG("Constructor Begin!");
  59. memset(&m_sStreamData, 0, sizeof(DBC_MEDIA_STREAM_DATA));
  60. m_pSource = NULL;
  61. m_bEvtMarkerCounter = 0;
  62. m_bCamMoveCounter = 0;
  63. m_bFlipMode = flip_mode;
  64. #ifdef EVE_ENABLE_VIDEO
  65. #ifdef EVE_SEQUENTAL_OUTPUT
  66. m_nSegFrameCounter = 0;
  67. m_nGlobalFrameCounter = 0;
  68. m_nSegShiftFrames = 0;
  69. m_nSegSkippedFrames = 0;
  70. m_bSegActive = false;
  71. m_bSegDelete = true;
  72. m_bNSegDelete = true;
  73. #else
  74. m_nPreAlarmFrames = 0;
  75. m_nPostAlarmFrames = 0;
  76. m_nSegmentLimitFrames = 0;
  77. m_nHardLimitFrames = 0;
  78. m_nSegAFrameCounter = 0;
  79. m_nSegBFrameCounter = 0;
  80. m_nGlobalFrameCounter = 0;
  81. m_nSegAShiftFrames = 0;
  82. m_nSegBShiftFrames = 0;
  83. m_nSegASkippedFrames = m_nSegBSkippedFrames = 0;
  84. m_bActiveEncoderStream = 0;
  85. m_bSegAActive = false;
  86. m_bSegADelete = true;
  87. m_bSegBActive = false;
  88. m_bSegBDelete = true;
  89. #endif // !EVE_SEQUENTAL_OUTPUT
  90. m_bCOP = 0;
  91. m_cSourceType = 'A';
  92. //todo: must be writen helper function to clean VIDEO_SEGMENT_INFO
  93. //that is not dynamicaly created by NEW operator
  94. //memset(&m_sStreamSegmentInfo[0], 0, sizeof(VIDEO_SEGMENT_INFO));
  95. //memset(&m_sStreamSegmentInfo[1], 0, sizeof(VIDEO_SEGMENT_INFO));
  96. #ifdef DIRECT_MJPEG_COMPOSING
  97. #ifndef EVE_SEQUENTAL_OUTPUT
  98. m_pOutputFD[0] = NULL;
  99. m_pOutputFD[1] = NULL;
  100. #else
  101. m_pOutputFD = NULL;
  102. #endif
  103. #else // !DIRECT_MJPEG_COMPOSING
  104. #ifdef OPENCV_VIDEO_OUTPUT
  105. #ifndef EVE_SEQUENTAL_OUTPUT
  106. m_pEncoderA = NULL;
  107. m_pEncoderB = NULL;
  108. #else
  109. m_pEncoder = NULL;
  110. #endif
  111. #endif
  112. #endif
  113. #endif // EVE_ENABLE_VIDEO
  114. // if( M == MS_MODE_DECODE_FRAMES ) 1=1;
  115. #ifdef DEBUG_EXTRA
  116. LOG("Constructor Done!");
  117. #endif
  118. }
  119. streamHandler::~streamHandler()
  120. {
  121. if (m_sStreamData.id)
  122. {
  123. if (m_pSource != NULL)
  124. {
  125. switch (m_cSourceType)
  126. { // m_sStreamData.source_type[0] ) {
  127. case 'D': delete((videoLIVE555Source *) m_pSource); break;
  128. case 'A': delete((videoAVLIBSource *) m_pSource); break;
  129. };
  130. };
  131. #ifdef EVE_ENABLE_VIDEO
  132. closeAll();
  133. #endif // EVE_ENABLE_VIDEO
  134. };
  135. #ifdef EVE_ENABLE_VIDEO
  136. // Encoder thread is stopped at this point - release frames still waiting in the queue
  137. waitThreadEnd(true);
  138. m_mEncodingQueueProtector.lock();
  139. while (! m_qEncodingQueue.empty())
  140. {
  141. ENCODING_BUFFER * tData = m_qEncodingQueue.front();
  142. m_qEncodingQueue.pop();
  143. if (tData)
  144. {
  145. #if defined(DIRECT_MJPEG_COMPOSING) || defined(OPENCV_VIDEO_OUTPUT)
  146. if (tData->data)
  147. {
  148. free(tData->data);
  149. }
  150. #else
  151. if (tData->data[0])
  152. {
  153. free(tData->data[0]);
  154. }
  155. #endif
  156. free(tData);
  157. };
  158. };
  159. m_mEncodingQueueProtector.unlock();
  160. #endif // EVE_ENABLE_VIDEO
  161. }
  162. bool streamHandler::create(dataBinder * ptr, uint32_t stremID)
  163. {
  164. if (ptr == NULL)
  165. {
  166. return false;
  167. }
  168. m_pDBC = ptr;
  169. if (stremID)
  170. {
  171. DBC_MEDIA_STREAM_DATA * tData = m_pDBC->getMediaStreamData(stremID);
  172. if (tData)
  173. {
  174. #ifdef DEBUG_EXTRA
  175. LOG("Have Stream Info");
  176. #endif
  177. memcpy(&m_sStreamData, tData, sizeof(DBC_MEDIA_STREAM_DATA));
  178. free(tData);
  179. DBC_CAM_DATA * tCAM = m_pDBC->getCamData(m_sStreamData.source_id);
  180. if (tCAM)
  181. {
  182. #ifdef DEBUG_EXTRA
  183. LOG("Have Cam Info");
  184. #endif
  185. m_sSourceDesc.mediaStreamId = stremID;
  186. m_sSourceDesc.mediaSourceId = m_sStreamData.source_id;
  187. uint32_t tNID = m_pDBC->getNodeIdByTypeAndAux(tCAM->type, m_sStreamData.source_id);
  188. // ToDo: Check Camera Addition
  189. // Just Work around to handle Wrong tyoe 12 instead of 13
  190. if (tNID == 0)
  191. {
  192. tNID = m_pDBC->getNodeIdByTypeAndAux(13, m_sStreamData.source_id);
  193. };
  194. if (tNID)
  195. {
  196. CSTR tNAM = m_pDBC->getNodeName(tNID);
  197. if (tNAM != NULL)
  198. {
  199. strncpy(m_sSourceDesc.mediaName, tNAM, 127);
  200. m_sSourceDesc.mediaName[127] = (char) 0;
  201. free(tNAM);
  202. }
  203. else
  204. {
  205. sprintf(m_sSourceDesc.mediaName, "No Name Cam");
  206. };
  207. }
  208. else
  209. {
  210. sprintf(m_sSourceDesc.mediaName, "No-Name-Cam");
  211. };
  212. m_cSourceType = m_sStreamData.source_type[0];
  213. switch (m_cSourceType)
  214. {
  215. case 'A': m_pSource = (basicMediaSource *) new videoAVLIBSource(&m_sSourceDesc); break;
  216. case 'D':
  217. {
  218. // Check Auth mode if basic - Override and use AVLIB
  219. // To Debug LIVE555 ONLY
  220. if( tCAM->auth_mode == 0){
  221. m_cSourceType = 'A';
  222. m_pSource = (basicMediaSource *) new videoAVLIBSource(&m_sSourceDesc);
  223. break;
  224. } else{
  225. m_pSource = (basicMediaSource *) new videoLIVE555Source(&m_sSourceDesc);
  226. break;
  227. };
  228. //m_pSource = (basicMediaSource *) new videoLIVE555Source(&m_sSourceDesc);
  229. //m_cSourceType = 'A'; // To use corect Destructor!
  230. //m_pSource = (basicMediaSource *) new videoAVLIBSource(&m_sSourceDesc);
  231. break;
  232. };
  233. };
  234. if (m_pSource != NULL)
  235. {
  236. char tMRL[1024];
  237. #ifdef DEBUG_EXTRA
  238. LOG("Source OK");
  239. #endif
  240. int tW = m_pMaster->getWidh();
  241. int tH = m_pMaster->getHeight();
  242. int pix = -1;
  243. bool in_16_9 = (((m_sStreamData.width * 100) / m_sStreamData.height) > 140);
  244. bool out_16_9 = (((tW * 100) / tH) > 140);
  245. // if( tW > 0 ){
  246. // //m_pSource->setProportionalByWidth( tW );
  247. // m_pSource->setSize( tW, tH );
  248. // };
  249. if (in_16_9 != out_16_9)
  250. {
  251. if (in_16_9)
  252. {
  253. tH = (((tW * 1000) / 16) * 9) / 1000;
  254. }
  255. else
  256. {
  257. tW = (((tH * 1000) / 3) * 4) / 1000;
  258. };
  259. };
  260. // export PATH=/usr/sbin:$PATH
  261. if (strncmp(m_sStreamData.mrl_proto, "v4l2", 4) == 0)
  262. {
  263. sprintf(tMRL, m_sStreamData.mrl);
  264. pix = atoi(m_sStreamData.c_type);
  265. }
  266. else
  267. {
  268. sprintf(tMRL, "%s://%s:%s@%s:%d%s", m_sStreamData.mrl_proto, tCAM->username, tCAM->password, tCAM->ip, m_sStreamData.mrl_port, m_sStreamData.mrl);
  269. };
  270. #ifdef DEBUG_EXTRA
  271. LOG( tMRL );
  272. #endif
  273. if (m_pSource->_open(tMRL, false, -1.0f, pix, m_sStreamData.width, m_sStreamData.height, tW, tH)){
  274. if (! m_pSource->attachDestination(this)){
  275. switch (m_cSourceType){
  276. case 'D': delete((videoLIVE555Source *) m_pSource); break;
  277. case 'A': delete((videoAVLIBSource *) m_pSource); break;
  278. };
  279. m_pSource = NULL;
  280. } else {
  281. #ifdef DEBUG_EXTRA
  282. LOG("Source is Connected to Output.");
  283. #endif
  284. };
  285. } else {
  286. LOG_ERROR("Can not Open Video Source!");
  287. switch (m_cSourceType) {
  288. case 'D': delete((videoLIVE555Source *) m_pSource); break;
  289. case 'A': delete((videoAVLIBSource *) m_pSource); break;
  290. };
  291. m_pSource = NULL;
  292. };
  293. } else {
  294. LOG_ERROR("Video Source Stream Failure!");
  295. };
  296. free(tCAM);
  297. } else {
  298. LOG_ERROR("Error Getting CAM Data!");
  299. m_pSource = NULL;
  300. return false;
  301. };
  302. };
  303. };
  304. if ( m_pSource ){
  305. #ifdef EVE_ENABLE_VIDEO
  306. return initVideoOutput();
  307. #else
  308. return true;
  309. #endif // EVE_ENABLE_VIDEO
  310. };
  311. return false;
  312. }
  313. bool streamHandler::pushFrame(AVFrame * Frame, void * src)
  314. {
  315. if( !Frame ) return false;
  316. if( !m_pMaster )return false;
  317. MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src;
  318. if (tMD)
  319. {
  320. };
  321. return true;
  322. }
  323. bool streamHandler::pushFrame(cv::Mat & Frame, void * src)
  324. {
  325. /// @todo Valgrind is reporting an important memory leak in this method.
  326. if (m_pMaster == NULL)
  327. {
  328. return false;
  329. }
  330. MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src;
  331. char tBuffer[512];
  332. if (tMD)
  333. {
  334. float mK, oK;
  335. cv::Rect ROI;
  336. m_pMaster->m_mPictureProtector.lock();
  337. if (m_pMaster->m_mapMATS[tMD->mediaStreamId].cols == 0)
  338. {
  339. LOG("First Frame Enqueued");
  340. sprintf(tBuffer, "INP: [%dx%d] SrcID:%d StreamID:%d", Frame.cols, Frame.rows, tMD->mediaSourceId, tMD->mediaStreamId);
  341. LOG(tBuffer);
  342. m_pMaster->m_mapMATS[tMD->mediaStreamId].create(m_pMaster->m_sEmbedVideoData.height, m_pMaster->m_sEmbedVideoData.width, CV_8UC3);
  343. cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Point(0, 0), cv::Point(m_pMaster->m_sEmbedVideoData.height, m_pMaster->m_sEmbedVideoData.width), cv::Scalar(0, 0, 0), cv::FILLED);
  344. };
  345. #ifdef USE_SCALING_IN
  346. oK = ((float) m_pMaster->m_sEmbedVideoData.height) / ((float) m_pMaster->m_sEmbedVideoData.width);
  347. mK = ((float) Frame.rows) / ((float) Frame.cols);
  348. // sprintf( tBuffer, "INP: [%dx%d] IK:%0.3f OK:%0.3f", Frame.cols, Frame.rows, mK, oK );
  349. if ((fabsf(mK - oK) < 0.1f) || (fabsf(oK - mK) < 0.1f))
  350. {
  351. ROI.width = (int) m_pMaster->m_sEmbedVideoData.width;
  352. ROI.height = (int) m_pMaster->m_sEmbedVideoData.height;
  353. ROI.x = (int) 0;
  354. ROI.y = (int) 0;
  355. }
  356. else
  357. {
  358. if (mK < oK)
  359. {
  360. ROI.width = (int) m_pMaster->m_sEmbedVideoData.width;
  361. ROI.height = (int) (((float) m_pMaster->m_sEmbedVideoData.width) * mK);
  362. ROI.x = (int) 0;
  363. ROI.y = (int) (m_pMaster->m_sEmbedVideoData.height - ROI.height) >> 1;
  364. }
  365. else
  366. {
  367. ROI.height = (int) m_pMaster->m_sEmbedVideoData.height;
  368. ROI.width = (int) (((float) m_pMaster->m_sEmbedVideoData.height) / mK);
  369. ROI.y = (int) 0;
  370. ROI.x = (int) (m_pMaster->m_sEmbedVideoData.width - ROI.width) >> 1;
  371. };
  372. };
  373. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId](ROI);
  374. #ifndef USE_CV_DENOISE
  375. cv::resize(Frame, mROI, mROI.size(), 0, 0, cv::INTER_LINEAR);
  376. #else
  377. cv::Mat mDenoiser;
  378. cv::resize(Frame, mDenoiser, mROI.size(), 0, 0, cv::INTER_LINEAR);
  379. cv::fastNlMeansDenoisingColored(mDenoiser, mROI, 10, 10, 7, 17);
  380. #endif
  381. #ifdef USE_CV_TONEMAP
  382. cv::Mat ldrReinhard;
  383. cv::Ptr<cv::TonemapReinhard> tonemapReinhard = cv::createTonemapReinhard(1.5, 0, 0, 0);
  384. tonemapReinhard->process(mROI, ldrReinhard);
  385. ldrReinhard = ldrReinhard * 255;
  386. ldrReinhard.copyTo(mROI);
  387. #endif
  388. #else
  389. if ((m_pMaster->m_sEmbedVideoData.height == Frame.rows) && (m_pMaster->m_sEmbedVideoData.width == Frame.cols))
  390. {
  391. Frame.copyTo(m_pMaster->m_mapMATS[tMD->mediaStreamId]);
  392. }
  393. else
  394. {
  395. // Mat dst_roi = dst(Rect(left, top, src.cols, src.rows));
  396. // src.copyTo(dst_roi);
  397. if (m_pMaster->m_sEmbedVideoData.width == Frame.cols)
  398. {
  399. ROI.width = Frame.cols;
  400. ROI.height = Frame.rows;
  401. ROI.x = 0;
  402. ROI.y = (m_pMaster->m_sEmbedVideoData.height - Frame.rows) >> 1;
  403. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId](ROI);
  404. #ifdef USE_CV_DENOISE
  405. cv::fastNlMeansDenoisingColored(Frame, mROI, 10, 10, 7, 17);
  406. #else
  407. Frame.copyTo(mROI);
  408. #endif
  409. #ifdef USE_CV_TONEMAP
  410. cv::Mat ldrReinhard;
  411. cv::Ptr<cv::TonemapReinhard> tonemapReinhard = cv::createTonemapReinhard(1.5, 0, 0, 0);
  412. tonemapReinhard->process(mROI, ldrReinhard);
  413. ldrReinhard = ldrReinhard * 255;
  414. ldrReinhard.copyTo(mROI);
  415. #endif
  416. }
  417. else
  418. {
  419. ROI.width = Frame.cols;
  420. ROI.height = Frame.rows;
  421. ROI.x = (m_pMaster->m_sEmbedVideoData.width - Frame.cols) >> 1;
  422. ROI.y = 0;
  423. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId](ROI);
  424. #ifdef USE_CV_DENOISE
  425. cv::fastNlMeansDenoisingColored(Frame, mROI, 10, 10, 7, 17);
  426. #else
  427. Frame.copyTo(mROI);
  428. #endif
  429. #ifdef USE_CV_TONEMAP
  430. cv::Mat ldrReinhard;
  431. cv::Ptr<cv::TonemapReinhard> tonemapReinhard = cv::createTonemapReinhard(1.5, 0, 0, 0);
  432. tonemapReinhard->process(mROI, ldrReinhard);
  433. ldrReinhard = ldrReinhard * 255;
  434. ldrReinhard.copyTo(mROI);
  435. #endif
  436. };
  437. };
  438. #endif
  439. // 0 - dis .. 1 - Hor ... 2 - vert 3 - both
  440. if (m_bFlipMode)
  441. {
  442. // Flip Horizontally = 1 vertically = 0 both = -1
  443. cv::Mat mirroredImage;
  444. cv::flip(m_pMaster->m_mapMATS[tMD->mediaStreamId], mirroredImage, 2 - m_bFlipMode);
  445. mirroredImage.copyTo(m_pMaster->m_mapMATS[tMD->mediaStreamId]);
  446. };
  447. #ifdef EVE_ENABLE_DROP_OUTPUT_FPS
  448. // LOG("T");
  449. m_mEncodingQueueProtector.lock();
  450. if (m_qEncodingQueue.size() > 10)
  451. {
  452. m_mEncodingQueueProtector.unlock();
  453. m_pMaster->m_mPictureProtector.unlock();
  454. // LOG("D");
  455. return true;
  456. };
  457. m_mEncodingQueueProtector.unlock();
  458. // LOG("Q");
  459. #endif
  460. if (m_bCamMoveCounter > m_bEvtMarkerCounter)
  461. {
  462. cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Rect(10, 10, 20, 20), cv::Scalar(m_bCamMoveCounter, 0, 0), cv::FILLED);
  463. m_bCamMoveCounter -= 4;
  464. if (m_bCamMoveCounter < 4)
  465. {
  466. m_bCamMoveCounter = 0;
  467. }
  468. }
  469. else
  470. {
  471. if (m_bEvtMarkerCounter)
  472. {
  473. m_bCamMoveCounter = 0;
  474. cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Rect(10, 10, 20, 20), cv::Scalar(0, 0, m_bEvtMarkerCounter), cv::FILLED);
  475. m_bEvtMarkerCounter -= 4;
  476. if (m_bEvtMarkerCounter < 4)
  477. {
  478. m_bEvtMarkerCounter = 0;
  479. }
  480. };
  481. };
  482. if (m_pMaster->m_sEmbedVideoData.show_label)
  483. {
  484. time_t t = time(NULL);
  485. // struct tm * tmp = gmtime( &t );
  486. struct tm * tmp = localtime(&t);
  487. if (tmp)
  488. {
  489. char tsb[64];
  490. // if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){
  491. if (strftime(tsb, sizeof(tsb), "%F %T", tmp) != 0)
  492. {
  493. // sprintf( tBuffer, ">>%d>%d>%s>%s>", tMD->mediaSourceId, tMD->mediaStreamId, tMD->mediaName, tsb );
  494. sprintf(tBuffer, ">>>%s>%s>", tMD->mediaName, tsb);
  495. int baseline = 0;
  496. cv::Size textSize = cv::getTextSize(tBuffer, m_pMaster->m_sEmbedVideoData.label_font_face, m_pMaster->m_sEmbedVideoData.label_font_scale, m_pMaster->m_sEmbedVideoData.label_font_thickness, &baseline);
  497. int x = m_pMaster->m_sEmbedVideoData.label_x;
  498. int y = m_pMaster->m_sEmbedVideoData.label_y;
  499. if (x < 0)
  500. {
  501. x = m_pMaster->m_sEmbedVideoData.width + x - textSize.width;
  502. };
  503. if (y < 0)
  504. {
  505. y = m_pMaster->m_sEmbedVideoData.height + y - baseline; //
  506. };
  507. if (! m_pMaster->m_sEmbedVideoData.label_transperant)
  508. {
  509. cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Rect(x, y - textSize.height - 4, textSize.width, textSize.height + baseline + 4), cv::Scalar(0, 0, 0), cv::FILLED);
  510. };
  511. cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(x, y), (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.label_font_face, m_pMaster->m_sEmbedVideoData.label_font_scale, cv::Scalar(0, 255, 0),
  512. m_pMaster->m_sEmbedVideoData.label_font_thickness, m_pMaster->m_sEmbedVideoData.label_line_type);
  513. };
  514. };
  515. }
  516. else
  517. {
  518. if (m_pMaster->m_sEmbedVideoData.show_ts)
  519. {
  520. time_t t = time(NULL);
  521. // struct tm * tmp = gmtime( &t );
  522. struct tm * tmp = localtime(&t);
  523. if (tmp)
  524. {
  525. if (strftime(tBuffer, sizeof(tBuffer), "%F %T GMT", tmp) != 0)
  526. {
  527. uint8_t shift_x = 0;
  528. uint8_t shift_y = 15;
  529. if (! m_pMaster->m_sEmbedVideoData.ts_transperant)
  530. {
  531. if (m_pMaster->m_sEmbedVideoData.ts_font_face)
  532. {
  533. shift_y = 15;
  534. cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Point(m_pMaster->m_sEmbedVideoData.ts_x, m_pMaster->m_sEmbedVideoData.ts_y), cv::Point(490, 60), cv::Scalar(0, 0, 0), cv::FILLED);
  535. }
  536. else
  537. {
  538. shift_y = 23;
  539. cv::rectangle(m_pMaster->m_mapMATS[tMD->mediaStreamId], cv::Point(m_pMaster->m_sEmbedVideoData.ts_x, m_pMaster->m_sEmbedVideoData.ts_y), cv::Point(490, 60), cv::Scalar(0, 0, 0), cv::FILLED);
  540. };
  541. cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x, m_pMaster->m_sEmbedVideoData.ts_y + shift_y),
  542. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 255, 255), m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  543. m_pMaster->m_sEmbedVideoData.ts_line_type);
  544. }
  545. else
  546. {
  547. if (m_pMaster->m_sEmbedVideoData.ts_font_face)
  548. {
  549. shift_y = 15;
  550. }
  551. else
  552. {
  553. shift_y = 23;
  554. };
  555. cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1),
  556. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 0, 0), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type);
  557. cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x + 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1),
  558. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 0, 0), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type);
  559. cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 1),
  560. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 0, 0), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type);
  561. cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 2),
  562. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 0, 0), m_pMaster->m_sEmbedVideoData.ts_font_thickness, m_pMaster->m_sEmbedVideoData.ts_line_type);
  563. cv::putText(m_pMaster->m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point(m_pMaster->m_sEmbedVideoData.ts_x + shift_x, m_pMaster->m_sEmbedVideoData.ts_y + shift_y),
  564. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, m_pMaster->m_sEmbedVideoData.ts_font_scale, cv::Scalar(0, 255, 255), m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  565. m_pMaster->m_sEmbedVideoData.ts_line_type);
  566. }
  567. };
  568. };
  569. };
  570. };
  571. if (m_pMaster->m_sEmbedVideoData.show_logo)
  572. {
  573. cv::Rect roi(cv::Point(m_pMaster->m_sEmbedVideoData.logo_x, m_pMaster->m_sEmbedVideoData.logo_y), cv::Size(m_pMaster->m_sEmbedVideoData.logo_w, m_pMaster->m_sEmbedVideoData.logo_h));
  574. cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId](roi);
  575. m_pMaster->m_mLogoPic.copyTo(destinationROI, m_pMaster->m_mLogoMask);
  576. };
  577. #ifndef EVE_WORK_WITH_MEDIAMTX
  578. vector<int> compression_params;
  579. // compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
  580. // compression_params.push_back(9);
  581. compression_params.push_back(cv::IMWRITE_JPEG_QUALITY);
  582. compression_params.push_back(50); // m_pMaster->m_sEmbedVideoData.compression_quality );
  583. m_pMaster->m_mEncodedProtector.lock();
  584. m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].clear();
  585. cv::imencode(".jpg", m_pMaster->m_mapMATS[tMD->mediaStreamId], m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params);
  586. // cv::Mat bw_dst;
  587. // cv::cvtColor( m_pMaster->m_mapMATS[tMD->mediaStreamId], bw_dst, cv::COLOR_BGR2GRAY );
  588. // cv::imencode( ".jpg", bw_dst, m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params );
  589. #ifdef HAVE_SMAL_PREVIEW_STREAMS
  590. // Make Small Preview Thumb
  591. cv::Mat dst;
  592. cv::resize(m_pMaster->m_mapMATS[tMD->mediaStreamId], dst, cv::Size(PREVIEW_SIZE_WIDTH, PREVIEW_SIZE_HEIGHT));
  593. // cv::resize( bw_dst, dst, cv::Size( PREVIEW_SIZE_WIDTH, PREVIEW_SIZE_HEIGHT ));
  594. m_pMaster->m_mapPREVIEWS[tMD->mediaStreamId].clear();
  595. cv::imencode(".jpg", dst, m_pMaster->m_mapPREVIEWS[tMD->mediaStreamId], compression_params);
  596. #endif
  597. #endif // !EVE_WORK_WITH_MEDIAMTX
  598. m_pMaster->m_mEncodedProtector.unlock();
  599. #ifdef EVE_ENABLE_VIDEO
  600. // if only decode Video Stream -> Exit
  601. // To handle video recording elsewhere (For Steph)
  602. if (m_eWM == MS_MODE_DECODE_FRAMES)
  603. {
  604. m_pMaster->m_mPictureProtector.unlock();
  605. return true;
  606. };
  607. // encode Video Stream
  608. // m_nPreAlarmFrames
  609. // m_nPostAlarmFrames
  610. // m_nNoAlarmSegmentFrames
  611. // m_nSegmentLimitFrames
  612. // m_nHardLimitFrames
  613. #ifdef EVE_SEQUENTAL_OUTPUT
  614. if ( m_bSegActive )
  615. { // The Open/Close is management ath Encoder Thread Procedure
  616. #else // !EVE_SEQUENTAL_OUTPUT
  617. if (m_bSegAActive || m_bSegBActive)
  618. {
  619. m_mFrameCounterProtector.lock();
  620. if( m_bSegAActive ) {
  621. if (m_nSegAFrameCounter > m_nHardLimitFrames) {
  622. #ifdef DEBUG_EXTRA
  623. LOG("HardLimit Reached!(A)");
  624. #endif
  625. closeSegmentA();
  626. // break;
  627. };
  628. if (m_nSegAFrameCounter > (m_nSegmentLimitFrames - (m_nPostAlarmFrames + m_nPreAlarmFrames))){
  629. if (! m_bSegBActive){
  630. #ifdef DEBUG_EXTRA
  631. LOG("Start Alt!(A)");
  632. #endif
  633. openSegmentB();
  634. };
  635. };
  636. if (m_nSegAFrameCounter > (m_nSegmentLimitFrames - m_nPostAlarmFrames) && ! m_bActiveEncoderStream){
  637. #ifdef DEBUG_EXTRA
  638. LOG("Swap Active!(A)");
  639. #endif
  640. swapActiveStreams();
  641. };
  642. };
  643. if( m_bSegBActive ){
  644. if (m_nSegBFrameCounter > m_nBHardLimitFrames){
  645. #ifdef DEBUG_EXTRA
  646. LOG("HardLimit Reached!(B)");
  647. #endif
  648. closeSegmentB();
  649. };
  650. if (m_nSegBFrameCounter > (m_nBSegmentLimitFrames - (m_nBPostAlarmFrames + m_nAPreAlarmFrames))){
  651. if (! m_bSegAActive){
  652. #ifdef DEBUG_EXTRA
  653. LOG("Start Alt!(B)");
  654. #endif
  655. openSegmentA();
  656. };
  657. };
  658. if (m_nSegBFrameCounter > (m_nBSegmentLimitFrames - m_nBPostAlarmFrames) && m_bActiveEncoderStream){
  659. #ifdef DEBUG_EXTRA
  660. LOG("Swap Active!(B)");
  661. #endif
  662. swapActiveStreams();
  663. };
  664. };
  665. m_mFrameCounterProtector.unlock();
  666. #endif // !EVE_SEQUENTAL_OUTPUT
  667. // Transfer Data to Encoder Thread
  668. ENCODING_BUFFER * tData = (ENCODING_BUFFER *) malloc(sizeof(ENCODING_BUFFER));
  669. if (tData)
  670. {
  671. #ifdef DIRECT_MJPEG_COMPOSING
  672. tData->size = m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].size();
  673. tData->data = (uint8_t *) malloc(tData->size);
  674. if (tData->data)
  675. {
  676. memcpy(tData->data, m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].data(), tData->size);
  677. // Aproach to reference and not copy data ... was not such a good idea
  678. // tData->data = m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].data();
  679. // if ( tData->data ) {
  680. #else
  681. #ifdef OPENCV_VIDEO_OUTPUT
  682. tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows;
  683. tData->cols = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols;
  684. tData->size = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols * m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize() * tData->rows;
  685. tData->data = (uint8_t *) malloc(tData->size);
  686. if (tData->data)
  687. {
  688. memcpy(tData->data, m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size);
  689. #else // OPENCV_VIDEO_OUTPUT
  690. tData->linesize[0] = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols * m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize();
  691. tData->linesize[1] = 0;
  692. tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows;
  693. tData->size = tData->linesize[0] * tData->rows;
  694. tData->data[1] = NULL;
  695. tData->data[0] = (uint8_t *) malloc(tData->size);
  696. if (tData->data[0])
  697. {
  698. memcpy(tData->data[0], m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size);
  699. #endif // OPENCV_VIDEO_OUTPUT
  700. #endif //! DIRECT_MJPEG_COMPOSING
  701. m_mEncodingQueueProtector.lock();
  702. m_qEncodingQueue.push(tData);
  703. m_mEncodingQueueProtector.unlock();
  704. }
  705. else
  706. {
  707. LOG_ERROR("MAT_CPY malloc Error!");
  708. free(tData);
  709. };
  710. }
  711. else
  712. {
  713. LOG_ERROR("ENC_BUF malloc Error!");
  714. }
  715. };
  716. #endif // EVE_ENABLE_VIDEO
  717. m_pMaster->m_mPictureProtector.unlock();
  718. }
  719. else
  720. {
  721. LOG_ERROR("No PayLoad!");
  722. };
  723. return true;
  724. }
  725. #ifdef EVE_ENABLE_VIDEO
  726. #ifdef EVE_SEQUENTAL_OUTPUT
  727. /*
  728. bool streamHandler::openSegment(void){
  729. if (!m_bSegActive)
  730. {
  731. CSTR tAM = getUniqID_MD5();
  732. if(tAM)
  733. {
  734. sprintf(m_sStreamSegmentInfo.scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER);
  735. strncpy(m_sStreamSegmentInfo.recordMD5, tAM, 32);
  736. m_sStreamSegmentInfo.recordMD5[32] = (char) 0;
  737. free(tAM);
  738. m_sStreamSegmentInfo.stream_id = m_sStreamData.id;
  739. PF_TIMESTAMP ts;
  740. getPFTS(&ts);
  741. m_sStreamSegmentInfo.streamTSS = ts.seconds;
  742. m_sStreamSegmentInfo.streamTMS = ts.milliseconds;
  743. #ifdef DEBUG_EXTRA
  744. char tB[128];
  745. sprintf(tB, "A opened %d.%d", m_sStreamSegmentInfo.streamTSS, m_sStreamSegmentInfo.streamTMS);
  746. LOG(tB);
  747. #endif
  748. strncpy(m_sStreamSegmentInfo.recordEXT, VIDEO_OUTPUT_CONTAINER, 6);
  749. m_sStreamSegmentInfo.streamFPS = m_sStreamData.fps;
  750. m_sStreamSegmentInfo.streamWidth = m_pMaster->getWidh();
  751. m_sStreamSegmentInfo.streamHeight = m_pMaster->getHeight();
  752. m_sStreamSegmentInfo.eventIDS.clear();
  753. m_sStreamSegmentInfo.eventTSS.clear();
  754. m_sStreamSegmentInfo.eventTMS.clear();
  755. m_sStreamSegmentInfo.eventFrames.clear();
  756. m_sStreamSegmentInfo.dataSize = 0;
  757. m_sStreamSegmentInfo.db_id = 0;
  758. #ifdef DIRECT_MJPEG_COMPOSING
  759. m_pOutputFD = fopen(m_sStreamSegmentInfo.scratchPath, "wb+");
  760. m_nSegFrameCounter = 0;
  761. m_nSegShiftFrames = 0;
  762. m_bSegActive = true;
  763. m_bSegDelete = m_bNSegDelete;
  764. m_bNSegDelete = true;
  765. #else // !DIRECT_MJPEG_COMPOSING
  766. #ifdef OPENCV_VIDEO_OUTPUT
  767. if (m_pEncoderA)
  768. {
  769. // int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4');
  770. int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G');
  771. double fps = m_sStreamData.fps;
  772. cv::String mn(m_sStreamSegmentInfo.scratchPath);
  773. cv::Size fz(m_sStreamData.width, m_sStreamData.height);
  774. // open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
  775. if (! m_pEncoder->open(mn, fourcc, fps, fz))
  776. {
  777. LOG_ERROR("Cannot Open Output Segment A!");
  778. return false;
  779. #ifdef DEBUG_EXTRA
  780. }
  781. else
  782. {
  783. char tB[256];
  784. sprintf(tB, "VideoStream A is Created [%s] %.2f fps", m_sStreamSegmentInfo.scratchPath, fps);
  785. LOG(tB);
  786. #endif
  787. };
  788. m_bSegActive = true;
  789. m_bSegDelete = m_bNSegDelete;
  790. m_bNSegDelete = true;
  791. m_nSegFrameCounter = 0;
  792. m_nSegShiftFrames = 0;
  793. }
  794. else
  795. {
  796. LOG_ERROR("No Encoder(A) Object!");
  797. return false;
  798. };
  799. #else // !OPENCV_VIDEO_OUTPUT
  800. // Check if Encoder is Ready
  801. if (m_pFormat == NULL)
  802. {
  803. return false;
  804. }
  805. #ifdef SEPARATED_VIDEO_ENCODERS
  806. if (avformat_alloc_output_context2(&m_pFormatCtx, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0)
  807. {
  808. LOG_ERROR("Format CTX A alloc error!");
  809. return false;
  810. }
  811. else
  812. {
  813. av_dict_set(&m_pFormatCtx->metadata, "Author", "Argus Sec. System", 0);
  814. m_pFormatCtx->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  815. };
  816. m_pVideoStr = avformat_new_stream(m_pFormatCtx, m_pVideoACodec);
  817. if (m_pVideoStr == NULL)
  818. {
  819. avformat_free_context(m_pFormatCtx);
  820. return false;
  821. #ifdef DEBUG_EXTRA
  822. }
  823. else
  824. {
  825. LOG("VideoStream A is Created");
  826. #endif
  827. };
  828. const AVRational dst_fps = {m_sStreamData.fps, 1};
  829. m_pVideoStr->r_frame_rate = m_pVideoStrA->avg_frame_rate = dst_fps;
  830. m_pVideoStr->time_base = m_pCodecCtx->time_base;
  831. avcodec_parameters_from_context(m_pVideoStr->codecpar, m_pCodecACtx);
  832. #ifdef DEBUG_EXTRA
  833. LOG("Opening Stream A");
  834. LOG(m_cSegName);
  835. char tB[128];
  836. sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStr->start_time, m_pVideoStr->nb_frames, m_pVideoStr->first_dts);
  837. LOG(tB);
  838. sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtx->start_time, m_pFormatCtx->duration);
  839. LOG(tB);
  840. #endif
  841. // if (avio_open(&m_pFormatCtx->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) {
  842. if (avio_open(&m_pFormatCtx->pb, m_sStreamSegmentInfo.scratchPath, AVIO_FLAG_WRITE) < 0)
  843. {
  844. LOG_ERROR("Could not open output file.");
  845. return m_bSegActive;
  846. };
  847. if (avformat_write_header(m_pFormatCtx, &m_pFormatOpts) < 0)
  848. {
  849. LOG_ERROR("Error occurred when writing header to output file.");
  850. return m_bSegActive;
  851. };
  852. // m_mFrameCounterProtector.lock();
  853. m_nSegFrameCounter = 0;
  854. m_nSegShiftFrames = 0;
  855. m_bSegActive = true;
  856. m_bSegDelete = m_bNSegDelete;
  857. m_bNSegDelete = true;
  858. // m_mFrameCounterProtector.unlock();
  859. #else // SEPARATED_VIDEO_ENCODERS
  860. m_nSegSkippedFrames = m_pVideoStr->nb_frames + 1;
  861. if (m_pVideoStr->nb_frames)
  862. {
  863. m_pVideoStr->nb_frames = 0;
  864. m_pVideoStr->start_time = 0;
  865. m_pVideoStr->first_dts = 0;
  866. m_pFormatCtx->start_time = 0;
  867. };
  868. #ifdef DEBUG_EXTRA
  869. LOG("Opening Stream");
  870. LOG(m_cSegName);
  871. char tB[128];
  872. sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStr->start_time, m_pVideoStr->nb_frames, m_pVideoStr->first_dts);
  873. LOG(tB);
  874. sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtx->start_time, m_pFormatCtx->duration);
  875. LOG(tB);
  876. #endif
  877. if (avio_open(&m_pFormatCtx->pb, m_cSegName, AVIO_FLAG_WRITE) < 0)
  878. {
  879. LOG_ERROR("Could not open output file.");
  880. return m_bSegActive;
  881. };
  882. if (avformat_write_header(m_pFormatCtx, &m_pFormatOpts) < 0)
  883. {
  884. LOG_ERROR("Error occurred when writing header to output file.");
  885. return m_bSegActive;
  886. };
  887. // m_mFrameCounterProtector.lock();
  888. m_nSegFrameCounter = 0;
  889. m_nSegShiftFrames = 0;
  890. m_bSegActive = true;
  891. m_bSegDelete = m_bNSegDelete;
  892. m_bNSegDelete = true;
  893. // m_mFrameCounterProtector.unlock();
  894. #endif // SEPARATED_VIDEO_ENCODERS
  895. #ifdef DEBUG_EXTRA
  896. LOG("Stream Opened");
  897. #endif
  898. #endif // !OPENCV_VIDEO_OUTPUT
  899. #endif // !DIRECT_MJPEG_COMPOSING
  900. };
  901. };
  902. return m_bSegActive;
  903. }
  904. void streamHandler::closeSegment(void){
  905. #ifdef DEBUG
  906. LOG("Closing Stream");
  907. #endif
  908. #ifdef DEBUG_EXTRA
  909. LOG("Actual Closing Video Stream");
  910. LOG(m_sStreamSegmentInfo.scratchPath);
  911. #endif
  912. m_bSegActive = false;
  913. if( !m_bSegDelete ){
  914. #ifdef DIRECT_MJPEG_COMPOSING
  915. if (m_pOutputFD){
  916. fclose(m_pOutputFD);
  917. m_pOutputFD = NULL;
  918. };
  919. #else // !DIRECT_MJPEG_COMPOSING
  920. #ifdef OPENCV_VIDEO_OUTPUT
  921. if (m_pEncoder->isOpened()){
  922. m_pEncoder->release();
  923. #ifdef DEBUG_EXTRA
  924. }else{
  925. LOG(" Encoder is NOT Opened!");
  926. #endif
  927. };
  928. #else // !OpenCV
  929. av_write_trailer(m_pFormatCtx);
  930. avio_close(m_pFormatCtx->pb);
  931. #endif // !OPENCV_VIDEO_OUTPUT
  932. #endif // !DIRECT_MJPEG_COMPOSING
  933. EVENT_CONTAINER * bEVT = createBasicEvent(m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo);
  934. if (bEVT){
  935. basicEventHeap::getInstance()->broadcast(bEVT);
  936. }else{
  937. LOG_ERROR("Event Creation failure!");
  938. }
  939. #ifdef DEBUG_EXTRA
  940. LOG("Stream is Saved");
  941. #endif
  942. } else {
  943. #ifdef DIRECT_MJPEG_COMPOSING
  944. if ( m_pOutputFD ){
  945. fclose(m_pOutputFD);
  946. m_pOutputFD = NULL;
  947. };
  948. #else
  949. #ifdef OPENCV_VIDEO_OUTPUT
  950. if (m_pEncoder->isOpened()) {
  951. m_pEncoder->release();
  952. #ifdef DEBUG_EXTRA
  953. } else {
  954. LOG(" Encoder is NOT Opened!");
  955. #endif
  956. };
  957. #else // !OPenCV
  958. #ifdef EVE_DONT_DELETE_SEGMENTS
  959. av_write_trailer(m_pFormatCtx);
  960. #endif
  961. avio_close(m_pFormatCtx->pb);
  962. #endif // !OPENCV_VIDEO_OUTPUT
  963. #endif // !DIRECT_MJPEG_COMPOSING
  964. #ifndef EVE_DONT_DELETE_SEGMENTS
  965. unlink(m_sStreamSegmentInfo.scratchPath);
  966. #endif
  967. #ifdef DEBUG_EXTRA
  968. LOG("Stream is Closed!");
  969. #endif
  970. };
  971. }
  972. */
  973. // Final Closing All + Thread
  974. void streamHandler::closeAll()
  975. {
  976. waitThreadEnd(true);
  977. #ifdef OPENCV_VIDEO_OUTPUT
  978. if (m_pEncoder){
  979. if (m_pEncoder->isOpened()){
  980. m_pEncoder->release();
  981. };
  982. delete(m_pEncoder);
  983. };
  984. #else // !OPENCV_VIDEO_OUTPUT
  985. #ifdef DIRECT_MJPEG_COMPOSING
  986. if (m_pOutputFD ){
  987. fclose(m_pOutputFD);
  988. m_pOutputFD = NULL;
  989. };
  990. #else // ! DIRECT_MJPEG_COMPOSING
  991. if(( m_pCodecCtx != NULL ) && m_bSegActive ){
  992. if (m_pCodecCtx != NULL){
  993. avcodec_send_frame(m_pCodecCtx, NULL);
  994. int ret = 0;
  995. AVPacket * avp = av_packet_alloc();
  996. if (avp){
  997. do{
  998. av_packet_unref(avp);
  999. ret = avcodec_receive_packet(m_pCodecACtx, avp);
  1000. if (! ret){
  1001. if (m_bSegActive){
  1002. av_write_frame(m_pFormatCtxA, avp);
  1003. };
  1004. };
  1005. } while (! ret);
  1006. av_packet_unref(avp);
  1007. av_packet_free(&avp);
  1008. };
  1009. };
  1010. if (m_bSegActive){
  1011. av_write_trailer(m_pFormatCtx);
  1012. avformat_close_input(&m_pFormatCtx);
  1013. m_bSegActive = false;
  1014. };
  1015. };
  1016. #endif // !DIRECT_MJPEG_COMPOSING
  1017. #endif // !OPENCV_VIDEO_OUTPUT
  1018. }
  1019. bool streamHandler::initVideoOutput()
  1020. {
  1021. m_nPreAlarmFrames = (PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps) / 1000;
  1022. m_nPostAlarmFrames = (POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps) / 1000;
  1023. m_nSegmentLimitFrames = (ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps) / 1000;
  1024. m_nHardLimitFrames = (ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps) / 1000;
  1025. #ifndef DIRECT_MJPEG_COMPOSING
  1026. #ifdef OPENCV_VIDEO_OUTPUT
  1027. //cv::VideoWriter out( m_sEncoderVS.m_pFileName, cv::VideoWriter::fourcc('a', 'v', 'c', '1'), 15.0, mat.size() );
  1028. m_pEncoder = new cv::VideoWriter();
  1029. if (m_pEncoder == NULL)
  1030. {
  1031. LOG_ERROR("Encoder A Create Failure!");
  1032. return false;
  1033. };
  1034. //m_pEncoder->set(cv::VIDEOWRITER_PROP_QUALITY, 10.0);
  1035. //m_pEncoder->set(cv::VIDEOWRITER_PROP_NSTRIPES, -1.0);
  1036. #else
  1037. if (! initLibAV())
  1038. {
  1039. return false;
  1040. }
  1041. m_pFormat = av_guess_format(VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL);
  1042. if (m_pFormat == NULL)
  1043. {
  1044. LOG_ERROR("Out VideoFormat Not Found!");
  1045. return false;
  1046. #ifdef DEBUG_EXTRA
  1047. } else {
  1048. LOG("Output video Format");
  1049. LOG(VIDEO_OUTPUT_CONTAINER);
  1050. #endif
  1051. };
  1052. #ifdef SEPARATED_VIDEO_ENCODERS
  1053. /* Stream A */
  1054. m_pVideoCodec = avcodec_find_encoder(VIDEO_OUTPUT_CODEC);
  1055. if (m_pVideoCodec == NULL)
  1056. {
  1057. LOG_ERROR("Encoder Video Codec Not Found!");
  1058. return false;
  1059. #ifdef DEBUG_EXTRA
  1060. } else {
  1061. LOG("Video Encoder Created");
  1062. #endif
  1063. };
  1064. m_pCodecCtx = avcodec_alloc_context3(m_pVideoACodec);
  1065. if (m_pCodecCtx == NULL)
  1066. {
  1067. LOG_ERROR("Video Encoder Context Memory Allocation Error!");
  1068. av_free(m_pVideoCodec);
  1069. avformat_free_context(m_pFormatCtx);
  1070. return false;
  1071. #ifdef DEBUG_EXTRA
  1072. } else {
  1073. LOG("Video Encoder Context A Allocated");
  1074. #endif
  1075. };
  1076. m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC;
  1077. m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  1078. m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1079. m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  1080. m_pCodecCtx->max_b_frames = 1;
  1081. m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width;
  1082. m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height;
  1083. m_pCodecCtx->time_base.num = 1;
  1084. m_pCodecCtx->time_base.den = m_sStreamData.fps;
  1085. m_pCodecCtx->framerate.num = m_sStreamData.fps;
  1086. m_pCodecCtx->framerate.den = 1;
  1087. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  1088. // m_pCodecACtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  1089. #endif
  1090. m_pFormatOpts = NULL;
  1091. if ((m_pCodecCtx->codec_id == AV_CODEC_ID_H264) || (m_pCodecCtx->codec_id == AV_CODEC_ID_H265))
  1092. {
  1093. #ifdef DEBUG_EXTRA
  1094. LOG("Begin Options!");
  1095. #endif
  1096. if (av_dict_set(&m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0) < 0)
  1097. {
  1098. LOG_ERROR("av_dict_set movflags!");
  1099. #ifdef DEBUG_EXTRA
  1100. } else {
  1101. LOG("MOV FLAG SET!");
  1102. #endif
  1103. };
  1104. // if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
  1105. // LOG_ERROR( "av_dict_set live!" );
  1106. // };
  1107. // default brand is "isom", which fails on some devices
  1108. if (av_dict_set(&m_pFormatOpts, "brand", "mp42", 0) < 0)
  1109. {
  1110. LOG_ERROR("av_dict_set brand!");
  1111. };
  1112. // m_pCodecCtx->max_b_frames = 1;
  1113. // m_pCodecCtx->level = 31;
  1114. m_pCodecCtx->gop_size = m_sStreamData.fps << 1; // VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  1115. // P-frames, generated by referencing data from prev and future frames.
  1116. // [Compression up, CPU usage up]
  1117. // [use 3/gop]
  1118. m_pCodecCtx->max_b_frames = 5;
  1119. // Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  1120. // [use 3?5 ref per P]
  1121. m_pCodecCtx->refs = 3;
  1122. // Compression efficiency (slower -> better quality + higher cpu%)
  1123. // [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  1124. // Set this option to "ultrafast" is critical for realtime encoding
  1125. av_opt_set(m_pCodecCtx->priv_data, "preset", "ultrafast", 0);
  1126. // av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  1127. // av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  1128. // Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  1129. // Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  1130. av_opt_set(m_pCodecCtx->priv_data, "crf", "32", 0);
  1131. // Change settings based upon the specifics of input
  1132. // [psnr, ssim, grain, zerolatency, fastdecode, animation]
  1133. // This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  1134. av_opt_set(m_pCodecCtx->priv_data, "tune", "zerolatency", 0);
  1135. // Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  1136. // Because Quicktime (ie. iOS) doesn't support this option
  1137. av_opt_set(m_pCodecACtx->priv_data, "b-pyramid", "0", 0);
  1138. #ifdef DEBUG_EXTRA
  1139. LOG("End Options!");
  1140. #endif
  1141. } else { // codec is not AV_CODEC_ID_H264 || AV_CODEC_ID_H265
  1142. if( m_pFormat->flags & AVFMT_GLOBALHEADER )
  1143. {
  1144. m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  1145. }
  1146. };
  1147. const AVRational dst_fps = {m_sStreamData.fps, 1};
  1148. #ifdef DEBUG_EXTRA
  1149. char TB[129];
  1150. sprintf(TB, "TimeBaseA: num[%d]/den[%d]", m_pCodecACtx->time_base.num, m_pCodecACtx->time_base.den);
  1151. LOG(TB);
  1152. sprintf(TB, "TimeBaseB: num[%d]/den[%d]", m_pCodecBCtx->time_base.num, m_pCodecBCtx->time_base.den);
  1153. LOG(TB);
  1154. #endif
  1155. ////m_pVideoStr->time_base = m_pCodecCtx->time_base;
  1156. // avcodec_get_context_defaults3( m_pVideoStr->codec, m_pVideoCodec );
  1157. // m_pVideoStr->codec->width = m_pMaster->m_sEmbedVideoData.width;
  1158. // m_pVideoStr->codec->height = m_pMaster->m_sEmbedVideoData.height;
  1159. // m_pVideoStr->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1160. // m_pVideoStr->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  1161. //// m_pVideoStr->r_frame_rate = m_pVideoStrA->avg_frame_rate =
  1162. ////dst_fps;
  1163. // if ( m_pFormatCtx->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  1164. //// avcodec_parameters_from_context( m_pVideoStr->codecpar,
  1165. ////m_pCodecCtx );
  1166. // m_pVideoStr->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  1167. // m_pVideoStr->codecpar->extradata = m_pCodecCtx->extradata;
  1168. // m_pVideoStr->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  1169. if (avcodec_is_open(m_pCodecCtx) == 0)
  1170. {
  1171. LOG("output codec context is closed, opening");
  1172. if (avcodec_open2(m_pCodecCtx, m_pVideoCodec, NULL) < 0)
  1173. {
  1174. LOG_ERROR("Error opening2 encoder");
  1175. return false;
  1176. #ifdef DEBUG_EXTRA
  1177. } else {
  1178. LOG("output codec context is opened");
  1179. #endif
  1180. };
  1181. #ifdef DEBUG_EXTRA
  1182. } else {
  1183. LOG("output codec context is already opened");
  1184. #endif
  1185. };
  1186. #else // !SEPARATED_VIDEO_ENCODERS
  1187. if (avformat_alloc_output_context2(&m_pFormatCtx, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0)
  1188. {
  1189. LOG_ERROR("Format CTX alloc error!");
  1190. return false;
  1191. } else {
  1192. av_dict_set(&m_pFormatCtx->metadata, "Author", "Argus Sec. System", 0);
  1193. m_pFormatCtx->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  1194. };
  1195. m_pVideoCodec = avcodec_find_encoder(VIDEO_OUTPUT_CODEC);
  1196. if (m_pVideoCodec == NULL)
  1197. {
  1198. LOG_ERROR("Output VideoCodec Not Found!");
  1199. avformat_free_context(m_pFormatCtxA);
  1200. avformat_free_context(m_pFormatCtxB);
  1201. return false;
  1202. #ifdef DEBUG_EXTRA
  1203. } else {
  1204. LOG("Output Video Codec Found");
  1205. #endif
  1206. };
  1207. m_pCodecCtx = avcodec_alloc_context3(m_pVideoCodec);
  1208. if (m_pCodecCtx == NULL)
  1209. {
  1210. LOG_ERROR("Out VideoCodec Context Memory Allocation Error");
  1211. av_free(m_pVideoCodec);
  1212. avformat_free_context(m_pFormatCtx);
  1213. return false;
  1214. #ifdef DEBUG_EXTRA
  1215. } else {
  1216. LOG("Out Codec Context3 Allocated");
  1217. #endif
  1218. };
  1219. m_pVideoStr = avformat_new_stream(m_pFormatCtx, m_pVideoCodec);
  1220. if (m_pVideoStr == NULL)
  1221. {
  1222. LOG_ERROR("VideoStream A Not Created!");
  1223. avcodec_free_context(&m_pCodecCtx);
  1224. av_free(m_pCodecCtx);
  1225. av_free(m_pVideoCodec);
  1226. // avformat_close_input ( &m_pFormatCtx );
  1227. avformat_free_context(m_pFormatCtx);
  1228. return false;
  1229. #ifdef DEBUG_EXTRA
  1230. } else {
  1231. LOG("VideoStream A is Created");
  1232. #endif
  1233. };
  1234. m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC;
  1235. m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  1236. m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1237. m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  1238. // m_pCodecCtx->thread_count = 1;
  1239. // m_pCodecCtx->bit_rate_tolerance = 1;
  1240. // m_pCodecCtx->global_quality = 100;
  1241. // m_pCodecCtx->compression_level = 2;
  1242. m_pCodecCtx->max_b_frames = 1;
  1243. m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width;
  1244. m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height;
  1245. m_pCodecCtx->time_base.num = 1;
  1246. m_pCodecCtx->time_base.den = m_sStreamData.fps;
  1247. m_pCodecCtx->framerate.num = m_sStreamData.fps;
  1248. m_pCodecCtx->framerate.den = 1;
  1249. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  1250. m_pCodecCtx->codec_tag = av_codec_get_tag(m_pFormatCtx->oformat->codec_tag, VIDEO_OUTPUT_CODEC);
  1251. #endif
  1252. m_pFormatOpts = NULL;
  1253. if ((m_pCodecCtx->codec_id == AV_CODEC_ID_H264) || (m_pCodecCtx->codec_id == AV_CODEC_ID_H265))
  1254. {
  1255. #ifdef DEBUG_EXTRA
  1256. LOG("Begin Options!");
  1257. #endif
  1258. if (av_dict_set(&m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0) < 0)
  1259. {
  1260. LOG_ERROR("av_dict_set movflags!");
  1261. #ifdef DEBUG_EXTRA
  1262. } else {
  1263. LOG("MOV FLAG SET!");
  1264. #endif
  1265. };
  1266. // if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
  1267. // LOG_ERROR( "av_dict_set live!" );
  1268. // };
  1269. // default brand is "isom", which fails on some devices
  1270. if (av_dict_set(&m_pFormatOpts, "brand", "mp42", 0) < 0)
  1271. {
  1272. LOG_ERROR("av_dict_set brand!");
  1273. };
  1274. // m_pCodecCtx->max_b_frames = 1;
  1275. // m_pCodecCtx->level = 31;
  1276. m_pCodecCtx->gop_size = m_sStreamData.fps << 1; // VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  1277. /// P-frames, generated by referencing data from prev and future frames.
  1278. /// [Compression up, CPU usage up]
  1279. /// [use 3/gop]
  1280. m_pCodecCtx->max_b_frames = 5;
  1281. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  1282. /// [use 3?5 ref per P]
  1283. m_pCodecCtx->refs = 3;
  1284. /// Compression efficiency (slower -> better quality + higher cpu%)
  1285. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  1286. /// Set this option to "ultrafast" is critical for realtime encoding
  1287. av_opt_set(m_pCodecCtx->priv_data, "preset", "ultrafast", 0);
  1288. // av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  1289. // av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  1290. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  1291. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  1292. av_opt_set(m_pCodecCtx->priv_data, "crf", "32", 0);
  1293. /// Change settings based upon the specifics of input
  1294. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  1295. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  1296. av_opt_set(m_pCodecCtx->priv_data, "tune", "zerolatency", 0);
  1297. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  1298. /// Because Quicktime (ie. iOS) doesn't support this option
  1299. av_opt_set(m_pCodecCtx->priv_data, "b-pyramid", "0", 0);
  1300. #ifdef DEBUG_EXTRA
  1301. LOG("End Options!");
  1302. #endif
  1303. } else {
  1304. if (m_pFormat->flags & AVFMT_GLOBALHEADER)
  1305. {
  1306. m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  1307. }
  1308. };
  1309. const AVRational dst_fps = {m_sStreamData.fps, 1};
  1310. #ifdef DEBUG_EXTRA
  1311. char TB[129];
  1312. sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den);
  1313. LOG(TB);
  1314. #endif
  1315. m_pVideoStr->time_base = m_pCodecCtx->time_base;
  1316. // avcodec_get_context_defaults3( m_pVideoStr->codec, m_pVideoCodec );
  1317. // m_pVideoStr->codec->width = m_pMaster->m_sEmbedVideoData.width;
  1318. // m_pVideoStr->codec->height = m_pMaster->m_sEmbedVideoData.height;
  1319. // m_pVideoStr->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1320. // m_pVideoStr->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  1321. m_pVideoStr->r_frame_rate = dst_fps;
  1322. // if ( m_pFormatCtx->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStr->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  1323. avcodec_parameters_from_context(m_pVideoStr->codecpar, m_pCodecCtx);
  1324. // m_pVideoStr->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  1325. // m_pVideoStr->codecpar->extradata = m_pCodecCtx->extradata;
  1326. // m_pVideoStr->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  1327. if (avcodec_is_open(m_pCodecCtx) == 0)
  1328. {
  1329. LOG("output codec context is closed, opening");
  1330. if (avcodec_open2(m_pCodecCtx, m_pVideoCodec, NULL) < 0)
  1331. {
  1332. LOG_ERROR("Error opening2 encoder");
  1333. return false;
  1334. #ifdef DEBUG_EXTRA
  1335. } else {
  1336. LOG("output codec context is opened");
  1337. #endif
  1338. };
  1339. #ifdef DEBUG_EXTRA
  1340. } else {
  1341. LOG("output codec context is already opened");
  1342. #endif
  1343. };
  1344. #endif // SEPARATED_VIDEO_ENCODERS
  1345. m_pConvertCtx =
  1346. sws_getContext(m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, AV_PIX_FMT_BGR24, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, VIDEO_OUTPUT_PIX_FMT, SWS_FAST_BILINEAR, NULL, NULL, NULL);
  1347. if (m_pConvertCtx == NULL)
  1348. {
  1349. return false;
  1350. }
  1351. m_pAVFrame = av_frame_alloc();
  1352. if (m_pAVFrame == NULL)
  1353. {
  1354. return false;
  1355. };
  1356. m_pOutBuffer = (uint8_t *) av_malloc(av_image_get_buffer_size(VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, BUFFER_ALIGN));
  1357. if (m_pOutBuffer == NULL)
  1358. {
  1359. return false;
  1360. };
  1361. m_pAVFrame->width = m_pMaster->m_sEmbedVideoData.width;
  1362. m_pAVFrame->height = m_pMaster->m_sEmbedVideoData.height;
  1363. m_pAVFrame->format = VIDEO_OUTPUT_PIX_FMT;
  1364. // av_frame_get_buffer( m_pAVFrame, 0 );
  1365. av_image_fill_arrays(m_pAVFrame->data, m_pAVFrame->linesize, m_pOutBuffer, VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, 1);
  1366. // av_frame_make_writable( m_pAVFrame );
  1367. #endif // !OPENCV_VIDEO_OUTPUT
  1368. #endif // !DIRECT_MJPEG_COMPOSING
  1369. return init();
  1370. }
  1371. #else // !EVE_SEQUENTAL_OUTPUT
  1372. void streamHandler::closeSegmentA(void)
  1373. {
  1374. m_mCurrentOperationProtector.lock();
  1375. if (m_bCOP == 0)
  1376. {
  1377. m_bCOP = 0x01;
  1378. }
  1379. m_mCurrentOperationProtector.unlock();
  1380. #ifdef DEBUG_EXTRA
  1381. LOG("Closing Stream A");
  1382. #endif
  1383. }
  1384. void streamHandler::closeSegmentB(void)
  1385. {
  1386. m_mCurrentOperationProtector.lock();
  1387. if (m_bCOP == 0)
  1388. {
  1389. m_bCOP = 0x02;
  1390. }
  1391. m_mCurrentOperationProtector.unlock();
  1392. #ifdef DEBUG_EXTRA
  1393. LOG("Closing Stream B");
  1394. #endif
  1395. }
  1396. void streamHandler::closeAll()
  1397. {
  1398. waitThreadEnd(true);
  1399. #ifdef OPENCV_VIDEO_OUTPUT
  1400. if (m_pEncoderA)
  1401. {
  1402. if (m_pEncoderA->isOpened())
  1403. {
  1404. m_pEncoderA->release();
  1405. };
  1406. delete(m_pEncoderA);
  1407. };
  1408. if (m_pEncoderB)
  1409. {
  1410. if (m_pEncoderB->isOpened())
  1411. {
  1412. m_pEncoderB->release();
  1413. };
  1414. delete(m_pEncoderB);
  1415. };
  1416. #else // !OPENCV_VIDEO_OUTPUT
  1417. #ifdef DIRECT_MJPEG_COMPOSING
  1418. if (m_pOutputFD[0])
  1419. {
  1420. fclose(m_pOutputFD[0]);
  1421. m_pOutputFD[0] = NULL;
  1422. };
  1423. if (m_pOutputFD[1])
  1424. {
  1425. fclose(m_pOutputFD[1]);
  1426. m_pOutputFD[1] = NULL;
  1427. };
  1428. #else // ! DIRECT_MJPEG_COMPOSING
  1429. #ifdef SEPARATED_VIDEO_ENCODERS
  1430. if ((m_pCodecACtx != NULL || m_pCodecBCtx != NULL) && (m_bSegAActive || m_bSegBActive))
  1431. {
  1432. if (m_pCodecACtx != NULL)
  1433. {
  1434. avcodec_send_frame(m_pCodecACtx, NULL);
  1435. int ret = 0;
  1436. AVPacket * avp = av_packet_alloc();
  1437. if (avp)
  1438. {
  1439. do
  1440. {
  1441. av_packet_unref(avp);
  1442. ret = avcodec_receive_packet(m_pCodecACtx, avp);
  1443. if (! ret)
  1444. {
  1445. if (m_bSegAActive)
  1446. {
  1447. av_write_frame(m_pFormatCtxA, avp);
  1448. }
  1449. };
  1450. }
  1451. while (! ret);
  1452. av_packet_unref(avp);
  1453. av_packet_free(&avp);
  1454. };
  1455. };
  1456. if (m_pCodecBCtx != NULL)
  1457. {
  1458. avcodec_send_frame(m_pCodecBCtx, NULL);
  1459. int ret = 0;
  1460. AVPacket * avp = av_packet_alloc();
  1461. if (avp)
  1462. {
  1463. do
  1464. {
  1465. av_packet_unref(avp);
  1466. ret = avcodec_receive_packet(m_pCodecBCtx, avp);
  1467. if (! ret)
  1468. {
  1469. if (m_bSegBActive)
  1470. {
  1471. av_write_frame(m_pFormatCtxB, avp);
  1472. }
  1473. };
  1474. }
  1475. while (! ret);
  1476. av_packet_unref(avp);
  1477. av_packet_free(&avp);
  1478. };
  1479. };
  1480. if (m_bSegAActive)
  1481. {
  1482. av_write_trailer(m_pFormatCtxA);
  1483. avformat_close_input(&m_pFormatCtxA);
  1484. m_bSegAActive = false;
  1485. };
  1486. if (m_bSegBActive)
  1487. {
  1488. av_write_trailer(m_pFormatCtxB);
  1489. avformat_close_input(&m_pFormatCtxB);
  1490. m_bSegBActive = false;
  1491. };
  1492. };
  1493. #else // !SEPARATED_VIDEO_ENCODERS
  1494. if (m_pCodecCtx != NULL && (m_bSegAActive || m_bSegBActive))
  1495. {
  1496. avcodec_send_frame(m_pCodecCtx, NULL);
  1497. int ret = 0;
  1498. AVPacket * avp = av_packet_alloc();
  1499. if (avp)
  1500. {
  1501. do
  1502. {
  1503. av_packet_unref(avp);
  1504. ret = avcodec_receive_packet(m_pCodecCtx, avp);
  1505. if (! ret)
  1506. {
  1507. if (m_bSegAActive)
  1508. {
  1509. av_write_frame(m_pFormatCtxA, avp);
  1510. }
  1511. if (m_bSegBActive)
  1512. {
  1513. av_write_frame(m_pFormatCtxB, avp);
  1514. }
  1515. };
  1516. }
  1517. while (! ret);
  1518. av_packet_unref(avp);
  1519. av_packet_free(&avp);
  1520. };
  1521. if (m_bSegAActive)
  1522. {
  1523. av_write_trailer(m_pFormatCtxA);
  1524. avformat_close_input(&m_pFormatCtxA);
  1525. m_bSegAActive = false;
  1526. };
  1527. if (m_bSegBActive)
  1528. {
  1529. av_write_trailer(m_pFormatCtxB);
  1530. avformat_close_input(&m_pFormatCtxB);
  1531. m_bSegBActive = false;
  1532. };
  1533. };
  1534. #endif // !SEPARATED_VIDEO_ENCODERS
  1535. #endif // !DIRECT_MJPEG_COMPOSING
  1536. // if( m_pFormat != NULL ) {
  1537. // av_free( m_pFormat );
  1538. //};
  1539. #endif // OPENCV_VIDEO_OUTPUT
  1540. }
  1541. bool streamHandler::openSegmentA(void)
  1542. {
  1543. if (! m_bSegAActive)
  1544. {
  1545. CSTR tAM = getUniqID_MD5();
  1546. if (tAM)
  1547. {
  1548. sprintf(m_sStreamSegmentInfo[0].scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER);
  1549. strncpy(m_sStreamSegmentInfo[0].recordMD5, tAM, 32);
  1550. m_sStreamSegmentInfo[0].recordMD5[32] = (char) 0;
  1551. free(tAM);
  1552. m_sStreamSegmentInfo[0].stream_id = m_sStreamData.id;
  1553. PF_TIMESTAMP ts;
  1554. getPFTS(&ts);
  1555. m_sStreamSegmentInfo[0].streamTSS = ts.seconds;
  1556. m_sStreamSegmentInfo[0].streamTMS = ts.milliseconds;
  1557. #ifdef DEBUG_EXTRA
  1558. char tB[128];
  1559. sprintf(tB, "A opened %d.%d", m_sStreamSegmentInfo[0].streamTSS, m_sStreamSegmentInfo[0].streamTMS);
  1560. LOG(tB);
  1561. #endif
  1562. strncpy(m_sStreamSegmentInfo[0].recordEXT, VIDEO_OUTPUT_CONTAINER, 6);
  1563. m_sStreamSegmentInfo[0].streamFPS = m_sStreamData.fps;
  1564. m_sStreamSegmentInfo[0].streamWidth = m_pMaster->getWidh();
  1565. m_sStreamSegmentInfo[0].streamHeight = m_pMaster->getHeight();
  1566. m_sStreamSegmentInfo[0].eventIDS.clear();
  1567. m_sStreamSegmentInfo[0].eventTSS.clear();
  1568. m_sStreamSegmentInfo[0].eventTMS.clear();
  1569. m_sStreamSegmentInfo[0].eventFrames.clear();
  1570. m_sStreamSegmentInfo[0].dataSize = 0;
  1571. m_sStreamSegmentInfo[0].db_id = 0;
  1572. #ifdef DIRECT_MJPEG_COMPOSING
  1573. m_pOutputFD[0] = fopen(m_sStreamSegmentInfo[0].scratchPath, "wb+");
  1574. m_nSegAFrameCounter = 0;
  1575. m_nSegAShiftFrames = 0;
  1576. m_bSegAActive = true;
  1577. m_bSegADelete = true;
  1578. #else // !DIRECT_MJPEG_COMPOSING
  1579. #ifdef OPENCV_VIDEO_OUTPUT
  1580. if (m_pEncoderA)
  1581. {
  1582. // int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4');
  1583. int fourcc =cv::VideoWriter::fourcc('a', 'v', 'c', '1');
  1584. // int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G');
  1585. double fps = m_sStreamData.fps;
  1586. cv::String mn(m_sStreamSegmentInfo[0].scratchPath);
  1587. cv::Size fz(m_sStreamData.width, m_sStreamData.height);
  1588. // open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
  1589. if (! m_pEncoderA->open(mn, fourcc, fps, fz))
  1590. {
  1591. LOG_ERROR("Cannot Open Output Segment A!");
  1592. return false;
  1593. #ifdef DEBUG_EXTRA
  1594. }
  1595. else
  1596. {
  1597. char tB[256];
  1598. sprintf(tB, "VideoStream A is Created [%s] %.2f fps", m_sStreamSegmentInfo[0].scratchPath, fps);
  1599. LOG(tB);
  1600. #endif
  1601. };
  1602. m_bSegAActive = true;
  1603. m_bSegADelete = true;
  1604. m_nSegAFrameCounter = 0;
  1605. m_nSegAShiftFrames = 0;
  1606. }
  1607. else
  1608. {
  1609. LOG_ERROR("No Encoder(A) Object!");
  1610. return false;
  1611. };
  1612. #else // !OPENCV_VIDEO_OUTPUT
  1613. // Check if Encoder is Ready
  1614. if (m_pFormat == NULL)
  1615. {
  1616. return false;
  1617. }
  1618. #ifdef SEPARATED_VIDEO_ENCODERS
  1619. if (avformat_alloc_output_context2(&m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0)
  1620. {
  1621. LOG_ERROR("Format CTX A alloc error!");
  1622. return false;
  1623. }
  1624. else
  1625. {
  1626. av_dict_set(&m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0);
  1627. m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  1628. };
  1629. m_pVideoStrA = avformat_new_stream(m_pFormatCtxA, m_pVideoACodec);
  1630. if (m_pVideoStrA == NULL)
  1631. {
  1632. avformat_free_context(m_pFormatCtxA);
  1633. return false;
  1634. #ifdef DEBUG_EXTRA
  1635. }
  1636. else
  1637. {
  1638. LOG("VideoStream A is Created");
  1639. #endif
  1640. };
  1641. const AVRational dst_fps = {m_sStreamData.fps, 1};
  1642. m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate = dst_fps;
  1643. m_pVideoStrA->time_base = m_pCodecACtx->time_base;
  1644. avcodec_parameters_from_context(m_pVideoStrA->codecpar, m_pCodecACtx);
  1645. #ifdef DEBUG_EXTRA
  1646. LOG("Opening Stream A");
  1647. LOG(m_cSegNameA);
  1648. char tB[128];
  1649. sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts);
  1650. LOG(tB);
  1651. sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration);
  1652. LOG(tB);
  1653. #endif
  1654. // if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) {
  1655. if (avio_open(&m_pFormatCtxA->pb, m_sStreamSegmentInfo[0].scratchPath, AVIO_FLAG_WRITE) < 0)
  1656. {
  1657. LOG_ERROR("Could not open output file.");
  1658. return m_bSegAActive;
  1659. };
  1660. if (avformat_write_header(m_pFormatCtxA, &m_pFormatOpts) < 0)
  1661. {
  1662. LOG_ERROR("Error occurred when writing header to output file.");
  1663. return m_bSegAActive;
  1664. };
  1665. // m_mFrameCounterProtector.lock();
  1666. m_nSegAFrameCounter = 0;
  1667. m_nSegAShiftFrames = 0;
  1668. m_bSegAActive = true;
  1669. m_bSegADelete = true;
  1670. // m_mFrameCounterProtector.unlock();
  1671. #else // SEPARATED_VIDEO_ENCODERS
  1672. m_nSegASkippedFrames = m_pVideoStrA->nb_frames + 1;
  1673. if (m_pVideoStrA->nb_frames)
  1674. {
  1675. m_pVideoStrA->nb_frames = 0;
  1676. m_pVideoStrA->start_time = 0;
  1677. m_pVideoStrA->first_dts = 0;
  1678. m_pFormatCtxA->start_time = 0;
  1679. };
  1680. #ifdef DEBUG_EXTRA
  1681. LOG("Opening Stream A");
  1682. LOG(m_cSegNameA);
  1683. char tB[128];
  1684. sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts);
  1685. LOG(tB);
  1686. sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration);
  1687. LOG(tB);
  1688. #endif
  1689. if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0)
  1690. {
  1691. LOG_ERROR("Could not open output file.");
  1692. return m_bSegAActive;
  1693. };
  1694. if (avformat_write_header(m_pFormatCtxA, &m_pFormatOpts) < 0)
  1695. {
  1696. LOG_ERROR("Error occurred when writing header to output file.");
  1697. return m_bSegAActive;
  1698. };
  1699. // m_mFrameCounterProtector.lock();
  1700. m_nSegAFrameCounter = 0;
  1701. m_nSegAShiftFrames = 0;
  1702. m_bSegAActive = true;
  1703. m_bSegADelete = true;
  1704. // m_mFrameCounterProtector.unlock();
  1705. #endif // SEPARATED_VIDEO_ENCODERS
  1706. #ifdef DEBUG_EXTRA
  1707. LOG("Stream A Opened");
  1708. #endif
  1709. #endif // !OPENCV_VIDEO_OUTPUT
  1710. #endif // !DIRECT_MJPEG_COMPOSING
  1711. };
  1712. };
  1713. return m_bSegAActive;
  1714. }
  1715. bool streamHandler::openSegmentB(void)
  1716. {
  1717. if (! m_bSegBActive)
  1718. {
  1719. CSTR tAM = getUniqID_MD5();
  1720. if (tAM)
  1721. {
  1722. sprintf(m_sStreamSegmentInfo[1].scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER);
  1723. strncpy(m_sStreamSegmentInfo[1].recordMD5, tAM, 32);
  1724. m_sStreamSegmentInfo[1].recordMD5[32] = (char) 0;
  1725. free(tAM);
  1726. m_sStreamSegmentInfo[1].stream_id = m_sStreamData.id;
  1727. PF_TIMESTAMP ts;
  1728. getPFTS(&ts);
  1729. m_sStreamSegmentInfo[1].streamTSS = ts.seconds;
  1730. m_sStreamSegmentInfo[1].streamTMS = ts.milliseconds;
  1731. #ifdef DEBUG_EXTRA
  1732. char tB[128];
  1733. sprintf(tB, "B opened %d.%d", m_sStreamSegmentInfo[1].streamTSS, m_sStreamSegmentInfo[1].streamTMS);
  1734. LOG(tB);
  1735. #endif
  1736. strncpy(m_sStreamSegmentInfo[1].recordEXT, VIDEO_OUTPUT_CONTAINER, 6);
  1737. m_sStreamSegmentInfo[1].streamFPS = m_sStreamData.fps;
  1738. m_sStreamSegmentInfo[1].streamWidth = m_pMaster->getWidh();
  1739. m_sStreamSegmentInfo[1].streamHeight = m_pMaster->getHeight();
  1740. m_sStreamSegmentInfo[1].eventIDS.clear();
  1741. m_sStreamSegmentInfo[1].eventTSS.clear();
  1742. m_sStreamSegmentInfo[1].eventTMS.clear();
  1743. m_sStreamSegmentInfo[1].eventFrames.clear();
  1744. m_sStreamSegmentInfo[1].dataSize = 0;
  1745. m_sStreamSegmentInfo[1].db_id = 0;
  1746. #ifdef DIRECT_MJPEG_COMPOSING
  1747. m_pOutputFD[1] = fopen(m_sStreamSegmentInfo[1].scratchPath, "wb+");
  1748. m_nSegBFrameCounter = 0;
  1749. m_nSegBShiftFrames = 0;
  1750. m_bSegBActive = true;
  1751. m_bSegBDelete = true;
  1752. #else // !DIRECT_MJPEG_COMPOSING
  1753. #ifdef OPENCV_VIDEO_OUTPUT
  1754. if (m_pEncoderB)
  1755. {
  1756. // int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4');
  1757. int fourcc =cv::VideoWriter::fourcc('a', 'v', 'c', '1');
  1758. //int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G');
  1759. double fps = m_sStreamData.fps;
  1760. cv::String mn(m_sStreamSegmentInfo[1].scratchPath);
  1761. cv::Size fz(m_sStreamData.width, m_sStreamData.height);
  1762. // open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
  1763. if (! m_pEncoderB->open(mn, fourcc, fps, fz))
  1764. {
  1765. LOG_ERROR("Cannot Open Output Segment B!");
  1766. return false;
  1767. #ifdef DEBUG_EXTRA
  1768. }
  1769. else
  1770. {
  1771. char tB[256];
  1772. sprintf(tB, "VideoStream B is Created [%s] %.2f fps", m_sStreamSegmentInfo[1].scratchPath, fps);
  1773. LOG(tB);
  1774. #endif
  1775. };
  1776. m_bSegBActive = true;
  1777. m_bSegBDelete = true;
  1778. m_nSegBFrameCounter = 0;
  1779. m_nSegBShiftFrames = 0;
  1780. }
  1781. else
  1782. {
  1783. LOG_ERROR("No Encoder(B) Object!");
  1784. return false;
  1785. };
  1786. #else // !OPENCV
  1787. // Check if Encoder is Ready
  1788. if (m_pFormat == NULL)
  1789. {
  1790. return false;
  1791. }
  1792. #ifdef SEPARATED_VIDEO_ENCODERS
  1793. if (avformat_alloc_output_context2(&m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0)
  1794. {
  1795. LOG_ERROR("Format CTX B alloc error!");
  1796. return false;
  1797. }
  1798. else
  1799. {
  1800. av_dict_set(&m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0);
  1801. m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  1802. };
  1803. m_pVideoStrB = avformat_new_stream(m_pFormatCtxB, m_pVideoBCodec);
  1804. if (m_pVideoStrB == NULL)
  1805. {
  1806. avformat_free_context(m_pFormatCtxB);
  1807. return false;
  1808. #ifdef DEBUG_EXTRA
  1809. }
  1810. else
  1811. {
  1812. LOG("VideoStream B is Created");
  1813. #endif
  1814. };
  1815. const AVRational dst_fps = {m_sStreamData.fps, 1};
  1816. m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  1817. m_pVideoStrB->time_base = m_pCodecBCtx->time_base;
  1818. avcodec_parameters_from_context(m_pVideoStrB->codecpar, m_pCodecBCtx);
  1819. #ifdef DEBUG_EXTRA
  1820. LOG("Opening Stream B");
  1821. LOG(m_cSegNameB);
  1822. char tB[128];
  1823. sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrB->start_time, m_pVideoStrB->nb_frames, m_pVideoStrB->first_dts);
  1824. LOG(tB);
  1825. sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtxB->start_time, m_pFormatCtxB->duration);
  1826. LOG(tB);
  1827. #endif
  1828. // if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){
  1829. if (avio_open(&m_pFormatCtxB->pb, m_sStreamSegmentInfo[1].scratchPath, AVIO_FLAG_WRITE) < 0)
  1830. {
  1831. LOG_ERROR("Could not open output file.");
  1832. avformat_free_context(m_pFormatCtxB);
  1833. return false;
  1834. };
  1835. if (avformat_write_header(m_pFormatCtxB, &m_pFormatOpts) < 0)
  1836. {
  1837. LOG_ERROR("Error occurred when writing header to output file.");
  1838. avio_close(m_pFormatCtxB->pb);
  1839. avformat_free_context(m_pFormatCtxB);
  1840. return false;
  1841. };
  1842. // m_mFrameCounterProtector.lock();
  1843. m_nSegBFrameCounter = 0;
  1844. m_nSegBShiftFrames = 0;
  1845. m_bSegBActive = true;
  1846. m_bSegBDelete = true;
  1847. // m_mFrameCounterProtector.unlock();
  1848. #else // SEPARATED_VIDEO_ENCODERS
  1849. m_nSegBSkippedFrames = m_pVideoStrB->nb_frames + 1;
  1850. if (m_pVideoStrB->nb_frames)
  1851. {
  1852. m_pVideoStrB->nb_frames = 0;
  1853. m_pVideoStrB->start_time = 0;
  1854. m_pVideoStrB->first_dts = 0;
  1855. m_pFormatCtxB->start_time = 0;
  1856. };
  1857. if (avio_open(&m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE) < 0)
  1858. {
  1859. LOG_ERROR("Could not open output file.");
  1860. return m_bSegBActive;
  1861. };
  1862. if (avformat_write_header(m_pFormatCtxB, &m_pFormatOpts) < 0)
  1863. {
  1864. LOG_ERROR("Error occurred when writing header to output file.");
  1865. return m_bSegBActive;
  1866. };
  1867. // m_mFrameCounterProtector.lock();
  1868. m_nSegBFrameCounter = 0;
  1869. m_nSegBShiftFrames = 0;
  1870. m_bSegBActive = true;
  1871. m_bSegBDelete = true;
  1872. // m_mFrameCounterProtector.unlock();
  1873. #endif // SEPARATED_VIDEO_ENCODERS
  1874. #ifdef DEBUG_EXTRA
  1875. LOG("Stream B Opened");
  1876. #endif
  1877. #endif // !OPENCV_VIDEO_OUTPUT
  1878. #endif // !DIRECT_MJPEG_COMPOSING
  1879. };
  1880. };
  1881. return m_bSegBActive;
  1882. }
  1883. bool streamHandler::initVideoOutput()
  1884. {
  1885. m_nPreAlarmFrames = (PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps) / 1000;
  1886. m_nPostAlarmFrames = (POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps) / 1000;
  1887. m_nSegmentLimitFrames = (ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps) / 1000;
  1888. m_nHardLimitFrames = (ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps) / 1000;
  1889. #ifndef DIRECT_MJPEG_COMPOSING
  1890. #ifdef OPENCV_VIDEO_OUTPUT
  1891. m_pEncoderA = new cv::VideoWriter();
  1892. if (m_pEncoderA == NULL)
  1893. {
  1894. LOG_ERROR("Encoder A Create Failure!");
  1895. return false;
  1896. };
  1897. //m_pEncoderA->set(cv::VIDEOWRITER_PROP_QUALITY, 10.0);
  1898. //m_pEncoderA->set(cv::VIDEOWRITER_PROP_NSTRIPES, -1.0);
  1899. m_pEncoderB = new cv::VideoWriter();
  1900. if (m_pEncoderA == NULL)
  1901. {
  1902. LOG_ERROR("Encoder B Create Failure!");
  1903. return false;
  1904. };
  1905. //m_pEncoderB->set(cv::VIDEOWRITER_PROP_QUALITY, 10.0);
  1906. //m_pEncoderB->set(cv::VIDEOWRITER_PROP_NSTRIPES, -1.0);
  1907. #else
  1908. if (! initLibAV())
  1909. {
  1910. return false;
  1911. }
  1912. m_pFormat = av_guess_format(VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL);
  1913. if (m_pFormat == NULL)
  1914. {
  1915. LOG_ERROR("Out VideoFormat Not Found!");
  1916. return false;
  1917. #ifdef DEBUG_EXTRA
  1918. }
  1919. else
  1920. {
  1921. LOG("Output video Format");
  1922. LOG(VIDEO_OUTPUT_CONTAINER);
  1923. #endif
  1924. };
  1925. #ifdef SEPARATED_VIDEO_ENCODERS
  1926. /* Stream A */
  1927. m_pVideoACodec = avcodec_find_encoder(VIDEO_OUTPUT_CODEC);
  1928. if (m_pVideoACodec == NULL)
  1929. {
  1930. LOG_ERROR("Encoder Video Codec Not Found!");
  1931. return false;
  1932. #ifdef DEBUG_EXTRA
  1933. }
  1934. else
  1935. {
  1936. LOG("Video Encoder A Created");
  1937. #endif
  1938. };
  1939. m_pCodecACtx = avcodec_alloc_context3(m_pVideoACodec);
  1940. if (m_pCodecACtx == NULL)
  1941. {
  1942. LOG_ERROR("Video Encoder A Context Memory Allocation Error!");
  1943. av_free(m_pVideoACodec);
  1944. avformat_free_context(m_pFormatCtxA);
  1945. return false;
  1946. #ifdef DEBUG_EXTRA
  1947. }
  1948. else
  1949. {
  1950. LOG("Video Encoder Context A Allocated");
  1951. #endif
  1952. };
  1953. /* Stream B */
  1954. m_pVideoBCodec = avcodec_find_encoder(VIDEO_OUTPUT_CODEC);
  1955. if (m_pVideoBCodec == NULL)
  1956. {
  1957. LOG_ERROR("Out VideoCodec Not Found!");
  1958. av_free(m_pVideoACodec);
  1959. return false;
  1960. #ifdef DEBUG_EXTRA
  1961. }
  1962. else
  1963. {
  1964. LOG("Video Encoder B Created");
  1965. #endif
  1966. };
  1967. m_pCodecBCtx = avcodec_alloc_context3(m_pVideoBCodec);
  1968. if (m_pCodecBCtx == NULL)
  1969. {
  1970. LOG_ERROR("Video Encoder B Context Memory Allocation Error!");
  1971. av_free(m_pVideoACodec);
  1972. av_free(m_pVideoBCodec);
  1973. avformat_free_context(m_pFormatCtxA);
  1974. avformat_free_context(m_pFormatCtxB);
  1975. return false;
  1976. #ifdef DEBUG_EXTRA
  1977. }
  1978. else
  1979. {
  1980. LOG("Video Encoder Context B Allocated");
  1981. #endif
  1982. };
  1983. m_pCodecACtx->codec_id = VIDEO_OUTPUT_CODEC;
  1984. m_pCodecACtx->codec_type = AVMEDIA_TYPE_VIDEO;
  1985. m_pCodecACtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1986. m_pCodecACtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  1987. m_pCodecACtx->max_b_frames = 1;
  1988. m_pCodecACtx->width = m_pMaster->m_sEmbedVideoData.width;
  1989. m_pCodecACtx->height = m_pMaster->m_sEmbedVideoData.height;
  1990. m_pCodecACtx->time_base.num = 1;
  1991. m_pCodecACtx->time_base.den = m_sStreamData.fps;
  1992. m_pCodecACtx->framerate.num = m_sStreamData.fps;
  1993. m_pCodecACtx->framerate.den = 1;
  1994. m_pCodecBCtx->codec_id = VIDEO_OUTPUT_CODEC;
  1995. m_pCodecBCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  1996. m_pCodecBCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1997. m_pCodecBCtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  1998. m_pCodecBCtx->max_b_frames = 1;
  1999. m_pCodecBCtx->width = m_pMaster->m_sEmbedVideoData.width;
  2000. m_pCodecBCtx->height = m_pMaster->m_sEmbedVideoData.height;
  2001. m_pCodecBCtx->time_base.num = 1;
  2002. m_pCodecBCtx->time_base.den = m_sStreamData.fps;
  2003. m_pCodecBCtx->framerate.num = m_sStreamData.fps;
  2004. m_pCodecBCtx->framerate.den = 1;
  2005. // https://pastebin.com/yG37YhWW
  2006. // https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec
  2007. // G@ avcodec encode NALU mp4
  2008. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  2009. ////m_pCodecACtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  2010. #endif
  2011. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  2012. ////m_pCodecBCtx->codec_tag = av_codec_get_tag( m_pFormatCtxB->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  2013. #endif
  2014. m_pFormatOpts = NULL;
  2015. // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate
  2016. if ((m_pCodecACtx->codec_id == AV_CODEC_ID_H264) || (m_pCodecACtx->codec_id == AV_CODEC_ID_H265))
  2017. {
  2018. #ifdef DEBUG_EXTRA
  2019. LOG("Begin Options!");
  2020. #endif
  2021. // Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  2022. // Set format's privater options, to be passed to avformat_write_header()
  2023. /*
  2024. mp4 muxer AVOptions:
  2025. -movflags E..... MOV muxer flags (default 0)
  2026. rtphint E..... Add RTP hint tracks
  2027. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  2028. frag_keyframe E..... Fragment at video keyframes
  2029. separate_moof E..... Write separate moof/mdat atoms for each track
  2030. frag_custom E..... Flush fragments on caller requests
  2031. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  2032. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  2033. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  2034. delay_moov ??
  2035. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  2036. -rtpflags E..... RTP muxer flags (default 0)
  2037. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  2038. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  2039. skip_rtcp E..... Don't send RTCP sender reports
  2040. h264_mode0 E..... Use mode 0 for H264 in RTP
  2041. send_bye E..... Send RTCP BYE packets when finishing
  2042. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  2043. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  2044. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  2045. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  2046. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  2047. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  2048. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  2049. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  2050. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  2051. */
  2052. if (av_dict_set(&m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0) < 0)
  2053. {
  2054. LOG_ERROR("av_dict_set movflags!");
  2055. #ifdef DEBUG_EXTRA
  2056. }
  2057. else
  2058. {
  2059. LOG("MOV FLAG SET!");
  2060. #endif
  2061. };
  2062. // if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
  2063. // LOG_ERROR( "av_dict_set live!" );
  2064. // };
  2065. // default brand is "isom", which fails on some devices
  2066. if (av_dict_set(&m_pFormatOpts, "brand", "mp42", 0) < 0)
  2067. {
  2068. LOG_ERROR("av_dict_set brand!");
  2069. };
  2070. // m_pCodecCtx->max_b_frames = 1;
  2071. // m_pCodecCtx->level = 31;
  2072. m_pCodecACtx->gop_size = m_sStreamData.fps << 1; // VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  2073. /// P-frames, generated by referencing data from prev and future frames.
  2074. /// [Compression up, CPU usage up]
  2075. /// [use 3/gop]
  2076. m_pCodecACtx->max_b_frames = 5;
  2077. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  2078. /// [use 3?5 ref per P]
  2079. m_pCodecACtx->refs = 3;
  2080. /// Compression efficiency (slower -> better quality + higher cpu%)
  2081. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  2082. /// Set this option to "ultrafast" is critical for realtime encoding
  2083. av_opt_set(m_pCodecACtx->priv_data, "preset", "ultrafast", 0);
  2084. // av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  2085. // av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  2086. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  2087. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  2088. av_opt_set(m_pCodecACtx->priv_data, "crf", "32", 0);
  2089. /// Change settings based upon the specifics of input
  2090. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  2091. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  2092. av_opt_set(m_pCodecACtx->priv_data, "tune", "zerolatency", 0);
  2093. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  2094. /// Because Quicktime (ie. iOS) doesn't support this option
  2095. av_opt_set(m_pCodecACtx->priv_data, "b-pyramid", "0", 0);
  2096. #ifdef DEBUG_EXTRA
  2097. LOG("End Options!");
  2098. #endif
  2099. }
  2100. else
  2101. {
  2102. if (m_pFormat->flags & AVFMT_GLOBALHEADER)
  2103. {
  2104. m_pCodecACtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  2105. }
  2106. };
  2107. if ((m_pCodecBCtx->codec_id == AV_CODEC_ID_H264) || (m_pCodecBCtx->codec_id == AV_CODEC_ID_H265))
  2108. {
  2109. #ifdef DEBUG_EXTRA
  2110. LOG("Begin Options!");
  2111. #endif
  2112. // Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  2113. // Set format's privater options, to be passed to avformat_write_header()
  2114. /*
  2115. mp4 muxer AVOptions:
  2116. -movflags E..... MOV muxer flags (default 0)
  2117. rtphint E..... Add RTP hint tracks
  2118. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  2119. frag_keyframe E..... Fragment at video keyframes
  2120. separate_moof E..... Write separate moof/mdat atoms for each track
  2121. frag_custom E..... Flush fragments on caller requests
  2122. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  2123. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  2124. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  2125. delay_moov ??
  2126. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  2127. -rtpflags E..... RTP muxer flags (default 0)
  2128. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  2129. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  2130. skip_rtcp E..... Don't send RTCP sender reports
  2131. h264_mode0 E..... Use mode 0 for H264 in RTP
  2132. send_bye E..... Send RTCP BYE packets when finishing
  2133. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  2134. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  2135. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  2136. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  2137. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  2138. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  2139. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  2140. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  2141. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  2142. */
  2143. // m_pCodecCtx->max_b_frames = 1;
  2144. // m_pCodecCtx->level = 31;
  2145. m_pCodecBCtx->gop_size = m_sStreamData.fps << 1; // VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  2146. /// P-frames, generated by referencing data from prev and future frames.
  2147. /// [Compression up, CPU usage up]
  2148. /// [use 3/gop]
  2149. m_pCodecBCtx->max_b_frames = 5;
  2150. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  2151. /// [use 3?5 ref per P]
  2152. m_pCodecBCtx->refs = 3;
  2153. /// Compression efficiency (slower -> better quality + higher cpu%)
  2154. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  2155. /// Set this option to "ultrafast" is critical for realtime encoding
  2156. av_opt_set(m_pCodecBCtx->priv_data, "preset", "ultrafast", 0);
  2157. // av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  2158. // av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  2159. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  2160. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  2161. av_opt_set(m_pCodecBCtx->priv_data, "crf", "32", 0);
  2162. /// Change settings based upon the specifics of input
  2163. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  2164. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  2165. av_opt_set(m_pCodecBCtx->priv_data, "tune", "zerolatency", 0);
  2166. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  2167. /// Because Quicktime (ie. iOS) doesn't support this option
  2168. av_opt_set(m_pCodecBCtx->priv_data, "b-pyramid", "0", 0);
  2169. #ifdef DEBUG_EXTRA
  2170. LOG("End Options!");
  2171. #endif
  2172. }
  2173. else
  2174. {
  2175. if (m_pFormat->flags & AVFMT_GLOBALHEADER)
  2176. {
  2177. m_pCodecBCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  2178. }
  2179. };
  2180. const AVRational dst_fps = {m_sStreamData.fps, 1};
  2181. #ifdef DEBUG_EXTRA
  2182. char TB[129];
  2183. sprintf(TB, "TimeBaseA: num[%d]/den[%d]", m_pCodecACtx->time_base.num, m_pCodecACtx->time_base.den);
  2184. LOG(TB);
  2185. sprintf(TB, "TimeBaseB: num[%d]/den[%d]", m_pCodecBCtx->time_base.num, m_pCodecBCtx->time_base.den);
  2186. LOG(TB);
  2187. #endif
  2188. ////m_pVideoStrA->time_base = m_pCodecACtx->time_base;
  2189. ////m_pVideoStrB->time_base = m_pCodecBCtx->time_base;
  2190. // avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec );
  2191. // m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width;
  2192. // m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height;
  2193. // m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  2194. // m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  2195. //// m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate =
  2196. ////dst_fps;
  2197. // avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec );
  2198. // m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width;
  2199. // m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height;
  2200. // m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  2201. // m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  2202. //// m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate =
  2203. ////dst_fps;
  2204. // if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  2205. // if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  2206. //// avcodec_parameters_from_context( m_pVideoStrA->codecpar,
  2207. ////m_pCodecACtx );
  2208. // m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  2209. // m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata;
  2210. // m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  2211. //// avcodec_parameters_from_context( m_pVideoStrB->codecpar,
  2212. ////m_pCodecBCtx );
  2213. // m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  2214. // m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata;
  2215. // m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  2216. if (avcodec_is_open(m_pCodecACtx) == 0)
  2217. {
  2218. LOG("output codec context is closed, opening");
  2219. if (avcodec_open2(m_pCodecACtx, m_pVideoACodec, NULL) < 0)
  2220. {
  2221. LOG_ERROR("Error opening2 encoder");
  2222. return false;
  2223. #ifdef DEBUG_EXTRA
  2224. }
  2225. else
  2226. {
  2227. LOG("output codec context is opened");
  2228. #endif
  2229. };
  2230. #ifdef DEBUG_EXTRA
  2231. }
  2232. else
  2233. {
  2234. LOG("output codec context is already opened");
  2235. #endif
  2236. };
  2237. if (avcodec_is_open(m_pCodecBCtx) == 0)
  2238. {
  2239. LOG("output codec context is closed, opening");
  2240. if (avcodec_open2(m_pCodecBCtx, m_pVideoBCodec, NULL) < 0)
  2241. {
  2242. LOG_ERROR("Error opening2 encoder");
  2243. return false;
  2244. #ifdef DEBUG_EXTRA
  2245. }
  2246. else
  2247. {
  2248. LOG("output codec context is opened");
  2249. #endif
  2250. };
  2251. #ifdef DEBUG_EXTRA
  2252. }
  2253. else
  2254. {
  2255. LOG("output codec context is already opened");
  2256. #endif
  2257. };
  2258. #else // SEPARATED_VIDEO_ENCODERS
  2259. if (avformat_alloc_output_context2(&m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0)
  2260. {
  2261. LOG_ERROR("Format CTX A alloc error!");
  2262. return false;
  2263. }
  2264. else
  2265. {
  2266. av_dict_set(&m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0);
  2267. m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  2268. };
  2269. if (avformat_alloc_output_context2(&m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0)
  2270. {
  2271. LOG_ERROR("Format CTX B alloc error!");
  2272. avformat_free_context(m_pFormatCtxA);
  2273. return false;
  2274. }
  2275. else
  2276. {
  2277. av_dict_set(&m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0);
  2278. m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  2279. };
  2280. m_pVideoCodec = avcodec_find_encoder(VIDEO_OUTPUT_CODEC);
  2281. if (m_pVideoCodec == NULL)
  2282. {
  2283. LOG_ERROR("Output VideoCodec Not Found!");
  2284. avformat_free_context(m_pFormatCtxA);
  2285. avformat_free_context(m_pFormatCtxB);
  2286. return false;
  2287. #ifdef DEBUG_EXTRA
  2288. }
  2289. else
  2290. {
  2291. LOG("Output Video Codec Found");
  2292. #endif
  2293. };
  2294. m_pCodecCtx = avcodec_alloc_context3(m_pVideoCodec);
  2295. if (m_pCodecCtx == NULL)
  2296. {
  2297. LOG_ERROR("Out VideoCodec Context Memory Allocation Error");
  2298. av_free(m_pVideoCodec);
  2299. avformat_free_context(m_pFormatCtxA);
  2300. avformat_free_context(m_pFormatCtxB);
  2301. return false;
  2302. #ifdef DEBUG_EXTRA
  2303. }
  2304. else
  2305. {
  2306. LOG("Out Codec Context3 Allocated");
  2307. #endif
  2308. };
  2309. m_pVideoStrA = avformat_new_stream(m_pFormatCtxA, m_pVideoCodec);
  2310. if (m_pVideoStrA == NULL)
  2311. {
  2312. LOG_ERROR("VideoStream A Not Created!");
  2313. avcodec_free_context(&m_pCodecCtx);
  2314. av_free(m_pCodecCtx);
  2315. av_free(m_pVideoCodec);
  2316. // avformat_close_input ( &m_pFormatCtxA );
  2317. // avformat_close_input ( &m_pFormatCtxB );
  2318. avformat_free_context(m_pFormatCtxA);
  2319. avformat_free_context(m_pFormatCtxB);
  2320. return false;
  2321. #ifdef DEBUG_EXTRA
  2322. }
  2323. else
  2324. {
  2325. LOG("VideoStream A is Created");
  2326. #endif
  2327. };
  2328. m_pVideoStrB = avformat_new_stream(m_pFormatCtxB, m_pVideoCodec);
  2329. if (m_pVideoStrB == NULL)
  2330. {
  2331. LOG_ERROR("VideoStream B Not Created!");
  2332. avcodec_free_context(&m_pCodecCtx);
  2333. av_free(m_pCodecCtx);
  2334. av_free(m_pVideoCodec);
  2335. // avformat_close_input ( &m_pFormatCtxA );
  2336. // avformat_close_input ( &m_pFormatCtxB );
  2337. avformat_free_context(m_pFormatCtxA);
  2338. avformat_free_context(m_pFormatCtxB);
  2339. return false;
  2340. #ifdef DEBUG_EXTRA
  2341. }
  2342. else
  2343. {
  2344. LOG("VideoStream B is Created");
  2345. #endif
  2346. };
  2347. m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC;
  2348. m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  2349. m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  2350. m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  2351. // m_pCodecCtx->thread_count = 1;
  2352. // m_pCodecCtx->bit_rate_tolerance = 1;
  2353. // m_pCodecCtx->global_quality = 100;
  2354. // m_pCodecCtx->compression_level = 2;
  2355. m_pCodecCtx->max_b_frames = 1;
  2356. m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width;
  2357. m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height;
  2358. m_pCodecCtx->time_base.num = 1;
  2359. m_pCodecCtx->time_base.den = m_sStreamData.fps;
  2360. m_pCodecCtx->framerate.num = m_sStreamData.fps;
  2361. m_pCodecCtx->framerate.den = 1;
  2362. // https://pastebin.com/yG37YhWW
  2363. // https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec
  2364. // G@ avcodec encode NALU mp4
  2365. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  2366. m_pCodecCtx->codec_tag = av_codec_get_tag(m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC);
  2367. #endif
  2368. m_pFormatOpts = NULL;
  2369. // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate
  2370. if ((m_pCodecCtx->codec_id == AV_CODEC_ID_H264) || (m_pCodecCtx->codec_id == AV_CODEC_ID_H265))
  2371. {
  2372. #ifdef DEBUG_EXTRA
  2373. LOG("Begin Options!");
  2374. #endif
  2375. // Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  2376. // Set format's privater options, to be passed to avformat_write_header()
  2377. /*
  2378. mp4 muxer AVOptions:
  2379. -movflags E..... MOV muxer flags (default 0)
  2380. rtphint E..... Add RTP hint tracks
  2381. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  2382. frag_keyframe E..... Fragment at video keyframes
  2383. separate_moof E..... Write separate moof/mdat atoms for each track
  2384. frag_custom E..... Flush fragments on caller requests
  2385. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  2386. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  2387. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  2388. delay_moov ??
  2389. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  2390. -rtpflags E..... RTP muxer flags (default 0)
  2391. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  2392. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  2393. skip_rtcp E..... Don't send RTCP sender reports
  2394. h264_mode0 E..... Use mode 0 for H264 in RTP
  2395. send_bye E..... Send RTCP BYE packets when finishing
  2396. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  2397. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  2398. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  2399. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  2400. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  2401. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  2402. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  2403. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  2404. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  2405. */
  2406. if (av_dict_set(&m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0) < 0)
  2407. {
  2408. LOG_ERROR("av_dict_set movflags!");
  2409. #ifdef DEBUG_EXTRA
  2410. }
  2411. else
  2412. {
  2413. LOG("MOV FLAG SET!");
  2414. #endif
  2415. };
  2416. // if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
  2417. // LOG_ERROR( "av_dict_set live!" );
  2418. // };
  2419. // default brand is "isom", which fails on some devices
  2420. if (av_dict_set(&m_pFormatOpts, "brand", "mp42", 0) < 0)
  2421. {
  2422. LOG_ERROR("av_dict_set brand!");
  2423. };
  2424. // m_pCodecCtx->max_b_frames = 1;
  2425. // m_pCodecCtx->level = 31;
  2426. m_pCodecCtx->gop_size = m_sStreamData.fps << 1; // VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  2427. /// P-frames, generated by referencing data from prev and future frames.
  2428. /// [Compression up, CPU usage up]
  2429. /// [use 3/gop]
  2430. m_pCodecCtx->max_b_frames = 5;
  2431. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  2432. /// [use 3?5 ref per P]
  2433. m_pCodecCtx->refs = 3;
  2434. /// Compression efficiency (slower -> better quality + higher cpu%)
  2435. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  2436. /// Set this option to "ultrafast" is critical for realtime encoding
  2437. av_opt_set(m_pCodecCtx->priv_data, "preset", "ultrafast", 0);
  2438. // av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  2439. // av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  2440. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  2441. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  2442. av_opt_set(m_pCodecCtx->priv_data, "crf", "32", 0);
  2443. /// Change settings based upon the specifics of input
  2444. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  2445. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  2446. av_opt_set(m_pCodecCtx->priv_data, "tune", "zerolatency", 0);
  2447. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  2448. /// Because Quicktime (ie. iOS) doesn't support this option
  2449. av_opt_set(m_pCodecCtx->priv_data, "b-pyramid", "0", 0);
  2450. #ifdef DEBUG_EXTRA
  2451. LOG("End Options!");
  2452. #endif
  2453. }
  2454. else
  2455. {
  2456. if (m_pFormat->flags & AVFMT_GLOBALHEADER)
  2457. {
  2458. m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  2459. }
  2460. };
  2461. const AVRational dst_fps = {m_sStreamData.fps, 1};
  2462. #ifdef DEBUG_EXTRA
  2463. char TB[129];
  2464. sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den);
  2465. LOG(TB);
  2466. #endif
  2467. m_pVideoStrA->time_base = m_pCodecCtx->time_base;
  2468. m_pVideoStrB->time_base = m_pCodecCtx->time_base;
  2469. // avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec );
  2470. // m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width;
  2471. // m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height;
  2472. // m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  2473. // m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  2474. m_pVideoStrA->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  2475. // avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec );
  2476. // m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width;
  2477. // m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height;
  2478. // m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  2479. // m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  2480. m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  2481. // if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  2482. // if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  2483. avcodec_parameters_from_context(m_pVideoStrA->codecpar, m_pCodecCtx);
  2484. // m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  2485. // m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata;
  2486. // m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  2487. avcodec_parameters_from_context(m_pVideoStrB->codecpar, m_pCodecCtx);
  2488. // m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  2489. // m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata;
  2490. // m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  2491. if (avcodec_is_open(m_pCodecCtx) == 0)
  2492. {
  2493. LOG("output codec context is closed, opening");
  2494. if (avcodec_open2(m_pCodecCtx, m_pVideoCodec, NULL) < 0)
  2495. {
  2496. LOG_ERROR("Error opening2 encoder");
  2497. return false;
  2498. #ifdef DEBUG_EXTRA
  2499. }
  2500. else
  2501. {
  2502. LOG("output codec context is opened");
  2503. #endif
  2504. };
  2505. #ifdef DEBUG_EXTRA
  2506. }
  2507. else
  2508. {
  2509. LOG("output codec context is already opened");
  2510. #endif
  2511. };
  2512. #endif // SEPARATED_VIDEO_ENCODERS
  2513. m_pConvertCtx =
  2514. sws_getContext(m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, AV_PIX_FMT_BGR24, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, VIDEO_OUTPUT_PIX_FMT, SWS_FAST_BILINEAR, NULL, NULL, NULL);
  2515. if (m_pConvertCtx == NULL)
  2516. {
  2517. return false;
  2518. }
  2519. m_pAVFrame = av_frame_alloc();
  2520. if (m_pAVFrame == NULL)
  2521. {
  2522. return false;
  2523. };
  2524. m_pOutBuffer = (uint8_t *) av_malloc(av_image_get_buffer_size(VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, BUFFER_ALIGN));
  2525. if (m_pOutBuffer == NULL)
  2526. {
  2527. return false;
  2528. };
  2529. m_pAVFrame->width = m_pMaster->m_sEmbedVideoData.width;
  2530. m_pAVFrame->height = m_pMaster->m_sEmbedVideoData.height;
  2531. m_pAVFrame->format = VIDEO_OUTPUT_PIX_FMT;
  2532. // av_frame_get_buffer( m_pAVFrame, 0 );
  2533. av_image_fill_arrays(m_pAVFrame->data, m_pAVFrame->linesize, m_pOutBuffer, VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, 1);
  2534. // av_frame_make_writable( m_pAVFrame );
  2535. #endif // !OPENCV_VIDEO_OUTPUT
  2536. #endif // !DIRECT_MJPEG_COMPOSING
  2537. return init();
  2538. }
  2539. #endif // !EVE_SEQUENTAL_OUTPUT
  2540. // encoding thread
  2541. void streamHandler::m_fThreadProc(void)
  2542. {
  2543. size_t nQueueSize;
  2544. #ifndef DIRECT_MJPEG_COMPOSING
  2545. #ifndef OPENCV_VIDEO_OUTPUT
  2546. AVPacket mPacket;
  2547. int bGotPacket;
  2548. int rVal = 0;
  2549. av_init_packet(&mPacket);
  2550. #endif
  2551. #endif
  2552. pthread_setname_np(pthread_self(), "VideoStream");
  2553. while (m_bThreadStatus != TH_ENDED)
  2554. {
  2555. // At the begining All streams are closed --> try to Open
  2556. if (m_bThreadStatus < TH_WORKING){
  2557. #ifdef EVE_SEQUENTAL_OUTPUT
  2558. CSTR tAM = getUniqID_MD5();
  2559. if( tAM ){
  2560. sprintf(m_sStreamSegmentInfo.scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER);
  2561. strncpy(m_sStreamSegmentInfo.recordMD5, tAM, 32);
  2562. m_sStreamSegmentInfo.recordMD5[32] = (char) 0;
  2563. free(tAM);
  2564. m_sStreamSegmentInfo.stream_id = m_sStreamData.id;
  2565. PF_TIMESTAMP ts;
  2566. getPFTS(&ts);
  2567. m_sStreamSegmentInfo.streamTSS = ts.seconds;
  2568. m_sStreamSegmentInfo.streamTMS = ts.milliseconds;
  2569. #ifdef DEBUG_EXTRA
  2570. char tB[128];
  2571. sprintf(tB, "First Time opened %d.%d", m_sStreamSegmentInfo.streamTSS, m_sStreamSegmentInfo.streamTMS);
  2572. LOG(tB);
  2573. #endif
  2574. strncpy(m_sStreamSegmentInfo.recordEXT, VIDEO_OUTPUT_CONTAINER, 6);
  2575. m_sStreamSegmentInfo.streamFPS = m_sStreamData.fps;
  2576. m_sStreamSegmentInfo.streamWidth = m_pMaster->getWidh();
  2577. m_sStreamSegmentInfo.streamHeight = m_pMaster->getHeight();
  2578. m_sStreamSegmentInfo.eventIDS.clear();
  2579. m_sStreamSegmentInfo.eventTSS.clear();
  2580. m_sStreamSegmentInfo.eventTMS.clear();
  2581. m_sStreamSegmentInfo.eventFrames.clear();
  2582. m_sStreamSegmentInfo.dataSize = 0;
  2583. m_sStreamSegmentInfo.db_id = 0;
  2584. #ifdef DIRECT_MJPEG_COMPOSING
  2585. m_pOutputFD = fopen(m_sStreamSegmentInfo.scratchPath, "wb+");
  2586. m_nSegFrameCounter = 0;
  2587. m_nSegShiftFrames = 0;
  2588. m_bSegActive = true;
  2589. m_bSegDelete = m_bNSegDelete;
  2590. m_bNSegDelete = true;
  2591. #else // !DIRECT_MJPEG_COMPOSING
  2592. #ifdef OPENCV_VIDEO_OUTPUT
  2593. if ( m_pEncoder ){
  2594. //int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4');
  2595. int fourcc =cv::VideoWriter::fourcc('a', 'v', 'c', '1');
  2596. //int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G');
  2597. double fps = m_sStreamData.fps;
  2598. cv::String mn(m_sStreamSegmentInfo.scratchPath);
  2599. cv::Size fz(m_sStreamData.width, m_sStreamData.height);
  2600. // open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
  2601. if (! m_pEncoder->open(mn, fourcc, fps, fz) ) {
  2602. LOG_ERROR("Cannot Open Output VideoStream!");
  2603. m_bThreadStatus = TH_ENDED;
  2604. continue;
  2605. #ifdef DEBUG_EXTRA
  2606. } else {
  2607. char tB[256];
  2608. sprintf(tB, "VideoStream is Created [%s] %.2f fps", m_sStreamSegmentInfo.scratchPath, fps);
  2609. LOG(tB);
  2610. #endif
  2611. };
  2612. m_bSegActive = true;
  2613. m_bSegDelete = m_bNSegDelete;
  2614. m_bNSegDelete = true;
  2615. m_nSegFrameCounter = 0;
  2616. m_nSegShiftFrames = 0;
  2617. } else {
  2618. LOG_ERROR("No Encoder Object!");
  2619. m_bThreadStatus = TH_ENDED;
  2620. continue;
  2621. };
  2622. #else // !OPENCV_VIDEO_OUTPUT
  2623. // Check if Encoder is Ready
  2624. if (m_pFormat == NULL){
  2625. m_bThreadStatus = TH_ENDED;
  2626. continue;
  2627. }
  2628. #ifdef SEPARATED_VIDEO_ENCODERS
  2629. if (avformat_alloc_output_context2(&m_pFormatCtx, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0){
  2630. LOG_ERROR("Format CTX alloc error!");
  2631. m_bThreadStatus = TH_ENDED;
  2632. continue;
  2633. } else {
  2634. av_dict_set(&m_pFormatCtx->metadata, "Author", "Argus Sec. System", 0);
  2635. m_pFormatCtx->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  2636. };
  2637. m_pVideoStr = avformat_new_stream(m_pFormatCtx, m_pVideoACodec);
  2638. if (m_pVideoStr == NULL){
  2639. avformat_free_context(m_pFormatCtx);
  2640. m_bThreadStatus = TH_ENDED;
  2641. continue;
  2642. #ifdef DEBUG_EXTRA
  2643. } else {
  2644. LOG("VideoStream is Created");
  2645. #endif
  2646. };
  2647. const AVRational dst_fps = {m_sStreamData.fps, 1};
  2648. m_pVideoStr->r_frame_rate = m_pVideoStrA->avg_frame_rate = dst_fps;
  2649. m_pVideoStr->time_base = m_pCodecCtx->time_base;
  2650. avcodec_parameters_from_context(m_pVideoStr->codecpar, m_pCodecACtx);
  2651. #ifdef DEBUG_EXTRA
  2652. LOG("Opening Stream");
  2653. LOG(m_cSegName);
  2654. char tB[128];
  2655. sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStr->start_time, m_pVideoStr->nb_frames, m_pVideoStr->first_dts);
  2656. LOG(tB);
  2657. sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtx->start_time, m_pFormatCtx->duration);
  2658. LOG(tB);
  2659. #endif
  2660. // if (avio_open(&m_pFormatCtx->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) {
  2661. if (avio_open(&m_pFormatCtx->pb, m_sStreamSegmentInfo.scratchPath, AVIO_FLAG_WRITE) < 0)
  2662. {
  2663. LOG_ERROR("Could not open output file.");
  2664. m_bThreadStatus = TH_ENDED;
  2665. continue;
  2666. };
  2667. if (avformat_write_header(m_pFormatCtx, &m_pFormatOpts) < 0)
  2668. {
  2669. LOG_ERROR("Error occurred when writing header to output file.");
  2670. m_bThreadStatus = TH_ENDED;
  2671. continue;
  2672. };
  2673. // m_mFrameCounterProtector.lock();
  2674. m_nSegFrameCounter = 0;
  2675. m_nSegShiftFrames = 0;
  2676. m_bSegActive = true;
  2677. m_bSegDelete = m_bNSegDelete;
  2678. m_bNSegDelete = true;
  2679. // m_mFrameCounterProtector.unlock();
  2680. #else // SEPARATED_VIDEO_ENCODERS
  2681. m_nSegSkippedFrames = m_pVideoStr->nb_frames + 1;
  2682. if (m_pVideoStr->nb_frames)
  2683. {
  2684. m_pVideoStr->nb_frames = 0;
  2685. m_pVideoStr->start_time = 0;
  2686. m_pVideoStr->first_dts = 0;
  2687. m_pFormatCtx->start_time = 0;
  2688. };
  2689. #ifdef DEBUG_EXTRA
  2690. LOG("Opening Stream");
  2691. LOG(m_cSegName);
  2692. char tB[128];
  2693. sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStr->start_time, m_pVideoStr->nb_frames, m_pVideoStr->first_dts);
  2694. LOG(tB);
  2695. sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtx->start_time, m_pFormatCtx->duration);
  2696. LOG(tB);
  2697. #endif
  2698. if (avio_open(&m_pFormatCtx->pb, m_cSegName, AVIO_FLAG_WRITE) < 0)
  2699. {
  2700. LOG_ERROR("Could not open output file.");
  2701. m_bThreadStatus = TH_ENDED;
  2702. continue;
  2703. };
  2704. if (avformat_write_header(m_pFormatCtx, &m_pFormatOpts) < 0)
  2705. {
  2706. LOG_ERROR("Error occurred when writing header to output file.");
  2707. m_bThreadStatus = TH_ENDED;
  2708. continue;
  2709. };
  2710. // m_mFrameCounterProtector.lock();
  2711. m_nSegFrameCounter = 0;
  2712. m_nSegShiftFrames = 0;
  2713. m_bSegActive = true;
  2714. m_bSegDelete = m_bNSegDelete;
  2715. m_bNSegDelete = true;
  2716. // m_mFrameCounterProtector.unlock();
  2717. #endif // SEPARATED_VIDEO_ENCODERS
  2718. #ifdef DEBUG_EXTRA
  2719. LOG("Stream Opened");
  2720. #endif
  2721. #endif // !OPENCV_VIDEO_OUTPUT
  2722. #endif // !DIRECT_MJPEG_COMPOSING
  2723. };
  2724. // If was not sucessfull - exit ??
  2725. if( !m_bSegActive ){
  2726. LOG_ERROR("Can not Open VideoStream for first time!");
  2727. m_bThreadStatus = TH_ENDED;
  2728. continue;
  2729. };
  2730. #else
  2731. if (! openSegmentA()){
  2732. m_bThreadStatus = TH_ENDED;
  2733. LOG_ERROR("Can not Open VideoStream A for first time!");
  2734. continue;
  2735. };
  2736. #endif
  2737. m_bThreadStatus = TH_WORKING;
  2738. continue;
  2739. };
  2740. m_mEncodingQueueProtector.lock();
  2741. nQueueSize = m_qEncodingQueue.size();
  2742. m_mEncodingQueueProtector.unlock();
  2743. if (nQueueSize)
  2744. {
  2745. m_mEncodingQueueProtector.lock();
  2746. ENCODING_BUFFER * tData = m_qEncodingQueue.front();
  2747. if (tData)
  2748. {
  2749. m_qEncodingQueue.pop();
  2750. m_mEncodingQueueProtector.unlock();
  2751. #ifdef DIRECT_MJPEG_COMPOSING
  2752. #ifdef EVE_SEQUENTAL_OUTPUT
  2753. if( m_pOutputFD )
  2754. {
  2755. fwrite(tData->data, 1, tData->size, m_pOutputFD);
  2756. m_mFrameCounterProtector.lock();
  2757. m_nSegFrameCounter++;
  2758. m_mFrameCounterProtector.unlock();
  2759. };
  2760. #else // ! EVE_SEQUENTAL_OUTPUT
  2761. if (m_bSegAActive)
  2762. {
  2763. if (m_pOutputFD[0])
  2764. {
  2765. fwrite(tData->data, 1, tData->size, m_pOutputFD[0]);
  2766. m_mFrameCounterProtector.lock();
  2767. m_nSegAFrameCounter++;
  2768. m_mFrameCounterProtector.unlock();
  2769. };
  2770. }
  2771. if (m_bSegBActive)
  2772. {
  2773. if (m_pOutputFD[1])
  2774. {
  2775. fwrite(tData->data, 1, tData->size, m_pOutputFD[1]);
  2776. m_mFrameCounterProtector.lock();
  2777. m_nSegBFrameCounter++;
  2778. m_mFrameCounterProtector.unlock();
  2779. };
  2780. }
  2781. #endif // ! EVE_SEQUENTAL_OUTPUT
  2782. // Don't free tData->data since is pointer on static data
  2783. free(tData->data);
  2784. #else // !DIRECT_MJPEG_COMPOSING
  2785. #ifdef OPENCV_VIDEO_OUTPUT
  2786. cv::Mat image(tData->rows, tData->cols, CV_8UC3);
  2787. memcpy(image.data, tData->data, tData->size);
  2788. free(tData->data);
  2789. #ifdef EVE_SEQUENTAL_OUTPUT
  2790. if (m_bSegActive)
  2791. {
  2792. if (m_pEncoder->isOpened())
  2793. {
  2794. m_pEncoder->write(image);
  2795. m_mFrameCounterProtector.lock();
  2796. m_nSegFrameCounter++;
  2797. m_mFrameCounterProtector.unlock();
  2798. };
  2799. }
  2800. #else //!EVE_SEQUENTAL_OUTPUT
  2801. if (m_bSegAActive)
  2802. {
  2803. if (m_pEncoderA->isOpened())
  2804. {
  2805. m_pEncoderA->write(image);
  2806. m_mFrameCounterProtector.lock();
  2807. m_nSegAFrameCounter++;
  2808. m_mFrameCounterProtector.unlock();
  2809. };
  2810. }
  2811. if (m_bSegBActive)
  2812. {
  2813. if (m_pEncoderB->isOpened())
  2814. {
  2815. m_pEncoderB->write(image);
  2816. m_mFrameCounterProtector.lock();
  2817. m_nSegBFrameCounter++;
  2818. m_mFrameCounterProtector.unlock();
  2819. };
  2820. }
  2821. #endif // !EVE_SEQUENTAL_OUTPUT
  2822. #else //! OPENCV_VIDEO_OUTPUT
  2823. // av_frame_make_writable( m_pAVFrame );
  2824. // m_qEncodingQueue.pop();
  2825. // m_mEncodingQueueProtector.unlock();
  2826. sws_scale(m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize);
  2827. free(tData->data[0]);
  2828. /*
  2829. AV_PICTURE_TYPE_NONE Undefined.
  2830. AV_PICTURE_TYPE_I Intra.
  2831. AV_PICTURE_TYPE_P Predicted.
  2832. AV_PICTURE_TYPE_B Bi-dir predicted.
  2833. AV_PICTURE_TYPE_S S(GMC)-VOP MPEG4.
  2834. AV_PICTURE_TYPE_SI Switching Intra.
  2835. AV_PICTURE_TYPE_SP Switching Predicted.
  2836. AV_PICTURE_TYPE_BI BI type.
  2837. */
  2838. if ((m_nGlobalFrameCounter % m_sStreamData.fps) == 0)
  2839. {
  2840. m_pAVFrame->key_frame = 1;
  2841. m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I;
  2842. }
  2843. else
  2844. {
  2845. m_pAVFrame->key_frame = 0;
  2846. m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_NONE;
  2847. };
  2848. m_pAVFrame->pts = m_nGlobalFrameCounter + 1;
  2849. #ifdef SEPARATED_VIDEO_ENCODERS
  2850. if (m_bSegAActive)
  2851. {
  2852. rVal = avcodec_send_frame(m_pCodecACtx, m_pAVFrame);
  2853. }
  2854. if (m_bSegBActive)
  2855. {
  2856. rVal = avcodec_send_frame(m_pCodecBCtx, m_pAVFrame);
  2857. }
  2858. #else //! SEPARATED_VIDEO_ENCODERS
  2859. rVal = avcodec_send_frame(m_pCodecCtx, m_pAVFrame);
  2860. #endif //! SEPARATED_VIDEO_ENCODERS
  2861. #endif //! OPENCV_VIDEO_OUTPUT
  2862. #endif //! DIRECT_MJPEG_COMPOSING
  2863. free(tData);
  2864. m_mFrameCounterProtector.lock();
  2865. m_nGlobalFrameCounter++;
  2866. m_mFrameCounterProtector.unlock();
  2867. } else {
  2868. m_mEncodingQueueProtector.unlock();
  2869. };
  2870. };
  2871. #ifdef EVE_SEQUENTAL_OUTPUT
  2872. if ( m_bSegActive ) {
  2873. m_mFrameCounterProtector.lock();
  2874. if ( m_nSegFrameCounter == m_nHardLimitFrames ) {
  2875. #ifdef DEBUG_EXTRA
  2876. LOG("Actual Closing Video Stream");
  2877. LOG( m_sStreamSegmentInfo.scratchPath );
  2878. #endif
  2879. m_bSegActive = false;
  2880. if( !m_bSegDelete ){
  2881. #ifdef DIRECT_MJPEG_COMPOSING
  2882. if( m_pOutputFD ){
  2883. fclose(m_pOutputFD);
  2884. m_pOutputFD = NULL;
  2885. };
  2886. #else //! DIRECT_MJPEG_COMPOSING
  2887. #ifdef OPENCV_VIDEO_OUTPUT
  2888. if( m_pEncoder->isOpened() ){
  2889. m_pEncoder->release();
  2890. #ifdef DEBUG_EXTRA
  2891. } else {
  2892. LOG("Encoder is NOT Opened!");
  2893. #endif
  2894. };
  2895. #else //! OPENCV_VIDEO_OUTPUT
  2896. av_write_trailer( m_pFormatCtx );
  2897. avio_close( m_pFormatCtx->pb );
  2898. #endif //! OPENCV_VIDEO_OUTPUT
  2899. #endif //! DIRECT_MJPEG_COMPOSING
  2900. VIDEO_SEGMENT_INFO *tData = (VIDEO_SEGMENT_INFO*) malloc( sizeof(VIDEO_SEGMENT_INFO));
  2901. if( tData ){
  2902. memcpy( tData, &m_sStreamSegmentInfo, sizeof( VIDEO_SEGMENT_INFO ));
  2903. EVENT_CONTAINER * bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, tData );
  2904. if( bEVT ){
  2905. basicEventHeap::getInstance()->broadcast(bEVT);
  2906. } else {
  2907. LOG_ERROR("Event Creation failure!");
  2908. free(tData);
  2909. };
  2910. };
  2911. #ifdef DEBUG_EXTRA
  2912. LOG("Stream is Saved");
  2913. #endif
  2914. } else {
  2915. #ifdef DIRECT_MJPEG_COMPOSING
  2916. if( m_pOutputFD ){
  2917. fclose(m_pOutputFD);
  2918. m_pOutputFD = NULL;
  2919. };
  2920. #else // !DIRECT_MJPEG_COMPOSING
  2921. #ifdef OPENCV_VIDEO_OUTPUT
  2922. if (m_pEncoder->isOpened()){
  2923. m_pEncoder->release();
  2924. #ifdef DEBUG_EXTRA
  2925. } else {
  2926. LOG("Encoder is NOT Opened!");
  2927. #endif
  2928. };
  2929. #else // !OPENCV
  2930. #ifdef EVE_DONT_DELETE_SEGMENTS
  2931. av_write_trailer(m_pFormatCtx);
  2932. #endif
  2933. avio_close(m_pFormatCtx->pb);
  2934. #endif // !OPENCV_VIDEO_OUTPUT
  2935. #endif // !DIRECT_MJPEG_COMPOSING
  2936. #ifndef EVE_DONT_DELETE_SEGMENTS
  2937. unlink(m_sStreamSegmentInfo.scratchPath);
  2938. #endif
  2939. #ifdef DEBUG_EXTRA
  2940. LOG("Stream is Closed and Deleted!");
  2941. #endif
  2942. };
  2943. #ifndef DIRECT_MJPEG_COMPOSING
  2944. #ifndef OPENCV_VIDEO_OUTPUT
  2945. #ifdef SEPARATED_VIDEO_ENCODERS
  2946. #ifdef DEBUG_EXTRA
  2947. LOG("Del FCTX");
  2948. #endif
  2949. avformat_free_context( m_pFormatCtx );
  2950. m_pVideoStr = NULL;
  2951. #ifdef DEBUG_EXTRA
  2952. LOG("Del FCTX DONE");
  2953. #endif
  2954. #endif // SEPARATED_VIDEO_ENCODERS
  2955. #endif // !OPENCV
  2956. #endif // !DIRECT_MJPEG_COMPOSING
  2957. };
  2958. m_mFrameCounterProtector.unlock();
  2959. //If we closed Stream then open new
  2960. if (!m_bSegActive ) {
  2961. CSTR tAM = getUniqID_MD5();
  2962. if( tAM ){
  2963. sprintf(m_sStreamSegmentInfo.scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER);
  2964. strncpy(m_sStreamSegmentInfo.recordMD5, tAM, 32);
  2965. m_sStreamSegmentInfo.recordMD5[32] = (char) 0;
  2966. free(tAM);
  2967. m_sStreamSegmentInfo.stream_id = m_sStreamData.id;
  2968. PF_TIMESTAMP ts;
  2969. getPFTS(&ts);
  2970. m_sStreamSegmentInfo.streamTSS = ts.seconds;
  2971. m_sStreamSegmentInfo.streamTMS = ts.milliseconds;
  2972. #ifdef DEBUG_EXTRA
  2973. char tB[128];
  2974. sprintf(tB, "VideoStream opened %d.%d", m_sStreamSegmentInfo.streamTSS, m_sStreamSegmentInfo.streamTMS);
  2975. LOG(tB);
  2976. LOG( m_sStreamSegmentInfo.scratchPath );
  2977. #endif
  2978. strncpy(m_sStreamSegmentInfo.recordEXT, VIDEO_OUTPUT_CONTAINER, 6);
  2979. m_sStreamSegmentInfo.streamFPS = m_sStreamData.fps;
  2980. m_sStreamSegmentInfo.streamWidth = m_pMaster->getWidh();
  2981. m_sStreamSegmentInfo.streamHeight = m_pMaster->getHeight();
  2982. m_sStreamSegmentInfo.eventIDS.clear();
  2983. m_sStreamSegmentInfo.eventTSS.clear();
  2984. m_sStreamSegmentInfo.eventTMS.clear();
  2985. m_sStreamSegmentInfo.eventFrames.clear();
  2986. m_sStreamSegmentInfo.dataSize = 0;
  2987. m_sStreamSegmentInfo.db_id = 0;
  2988. #ifdef DIRECT_MJPEG_COMPOSING
  2989. m_pOutputFD = fopen(m_sStreamSegmentInfo.scratchPath, "wb+");
  2990. m_nSegFrameCounter = 0;
  2991. m_nSegShiftFrames = 0;
  2992. m_bSegActive = true;
  2993. m_bSegDelete = m_bNSegDelete;
  2994. m_bNSegDelete = true;
  2995. #else // !DIRECT_MJPEG_COMPOSING
  2996. #ifdef OPENCV_VIDEO_OUTPUT
  2997. if ( m_pEncoder ){
  2998. //int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4');
  2999. int fourcc =cv::VideoWriter::fourcc('a', 'v', 'c', '1');
  3000. //int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G');
  3001. double fps = m_sStreamData.fps;
  3002. cv::String mn(m_sStreamSegmentInfo.scratchPath);
  3003. cv::Size fz(m_sStreamData.width, m_sStreamData.height);
  3004. // open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
  3005. if (! m_pEncoder->open(mn, fourcc, fps, fz) ) {
  3006. LOG_ERROR("Cannot Open Output VideoStream!");
  3007. m_bThreadStatus = TH_ENDED;
  3008. continue;
  3009. #ifdef DEBUG_EXTRA
  3010. } else {
  3011. char tB[256];
  3012. sprintf(tB, "VideoStream is Created [%s] %.2f fps", m_sStreamSegmentInfo.scratchPath, fps);
  3013. LOG(tB);
  3014. #endif
  3015. };
  3016. m_bSegActive = true;
  3017. m_bSegDelete = m_bNSegDelete;
  3018. m_bNSegDelete = true;
  3019. m_nSegFrameCounter = 0;
  3020. m_nSegShiftFrames = 0;
  3021. } else {
  3022. LOG_ERROR("No Encoder Object!");
  3023. m_bThreadStatus = TH_ENDED;
  3024. continue;
  3025. };
  3026. #else // !OPENCV_VIDEO_OUTPUT
  3027. // Check if Encoder is Ready
  3028. if (m_pFormat == NULL){
  3029. m_bThreadStatus = TH_ENDED;
  3030. continue;
  3031. }
  3032. #ifdef SEPARATED_VIDEO_ENCODERS
  3033. if (avformat_alloc_output_context2(&m_pFormatCtx, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER) < 0){
  3034. LOG_ERROR("Format CTX alloc error!");
  3035. m_bThreadStatus = TH_ENDED;
  3036. continue;
  3037. } else {
  3038. av_dict_set(&m_pFormatCtx->metadata, "Author", "Argus Sec. System", 0);
  3039. m_pFormatCtx->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  3040. };
  3041. m_pVideoStr = avformat_new_stream(m_pFormatCtx, m_pVideoACodec);
  3042. if (m_pVideoStr == NULL){
  3043. avformat_free_context(m_pFormatCtx);
  3044. m_bThreadStatus = TH_ENDED;
  3045. continue;
  3046. #ifdef DEBUG_EXTRA
  3047. } else {
  3048. LOG("VideoStream is Created");
  3049. #endif
  3050. };
  3051. const AVRational dst_fps = {m_sStreamData.fps, 1};
  3052. m_pVideoStr->r_frame_rate = m_pVideoStrA->avg_frame_rate = dst_fps;
  3053. m_pVideoStr->time_base = m_pCodecCtx->time_base;
  3054. avcodec_parameters_from_context(m_pVideoStr->codecpar, m_pCodecACtx);
  3055. #ifdef DEBUG_EXTRA
  3056. LOG("Opening Stream");
  3057. LOG(m_cSegName);
  3058. char tB[128];
  3059. sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStr->start_time, m_pVideoStr->nb_frames, m_pVideoStr->first_dts);
  3060. LOG(tB);
  3061. sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtx->start_time, m_pFormatCtx->duration);
  3062. LOG(tB);
  3063. #endif
  3064. // if (avio_open(&m_pFormatCtx->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) {
  3065. if (avio_open(&m_pFormatCtx->pb, m_sStreamSegmentInfo.scratchPath, AVIO_FLAG_WRITE) < 0)
  3066. {
  3067. LOG_ERROR("Could not open output file.");
  3068. m_bThreadStatus = TH_ENDED;
  3069. continue;
  3070. };
  3071. if (avformat_write_header(m_pFormatCtx, &m_pFormatOpts) < 0)
  3072. {
  3073. LOG_ERROR("Error occurred when writing header to output file.");
  3074. m_bThreadStatus = TH_ENDED;
  3075. continue;
  3076. };
  3077. // m_mFrameCounterProtector.lock();
  3078. m_nSegFrameCounter = 0;
  3079. m_nSegShiftFrames = 0;
  3080. m_bSegActive = true;
  3081. m_bSegDelete = m_bNSegDelete;
  3082. m_bNSegDelete = true;
  3083. // m_mFrameCounterProtector.unlock();
  3084. #else // SEPARATED_VIDEO_ENCODERS
  3085. m_nSegSkippedFrames = m_pVideoStr->nb_frames + 1;
  3086. if (m_pVideoStr->nb_frames)
  3087. {
  3088. m_pVideoStr->nb_frames = 0;
  3089. m_pVideoStr->start_time = 0;
  3090. m_pVideoStr->first_dts = 0;
  3091. m_pFormatCtx->start_time = 0;
  3092. };
  3093. #ifdef DEBUG_EXTRA
  3094. LOG("Opening Stream");
  3095. LOG(m_cSegName);
  3096. char tB[128];
  3097. sprintf(tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStr->start_time, m_pVideoStr->nb_frames, m_pVideoStr->first_dts);
  3098. LOG(tB);
  3099. sprintf(tB, "CON ST:%llu DUR:%llu", m_pFormatCtx->start_time, m_pFormatCtx->duration);
  3100. LOG(tB);
  3101. #endif
  3102. if (avio_open(&m_pFormatCtx->pb, m_cSegName, AVIO_FLAG_WRITE) < 0)
  3103. {
  3104. LOG_ERROR("Could not open output file.");
  3105. m_bThreadStatus = TH_ENDED;
  3106. continue;
  3107. };
  3108. if (avformat_write_header(m_pFormatCtx, &m_pFormatOpts) < 0)
  3109. {
  3110. LOG_ERROR("Error occurred when writing header to output file.");
  3111. m_bThreadStatus = TH_ENDED;
  3112. continue;
  3113. };
  3114. // m_mFrameCounterProtector.lock();
  3115. m_nSegFrameCounter = 0;
  3116. m_nSegShiftFrames = 0;
  3117. m_bSegActive = true;
  3118. m_bSegDelete = m_bNSegDelete;
  3119. m_bNSegDelete = true;
  3120. // m_mFrameCounterProtector.unlock();
  3121. #endif // SEPARATED_VIDEO_ENCODERS
  3122. #ifdef DEBUG_EXTRA
  3123. LOG("Stream Opened");
  3124. #endif
  3125. #endif // !OPENCV_VIDEO_OUTPUT
  3126. #endif // !DIRECT_MJPEG_COMPOSING
  3127. };
  3128. };
  3129. };
  3130. #else //! EVE_SEQUENTAL_OUTPUT
  3131. // Test Commands!
  3132. m_mCurrentOperationProtector.lock();
  3133. switch (m_bCOP){
  3134. case 0x01:{
  3135. #ifdef DEBUG_EXTRA
  3136. LOG("Actual Closing Video Stream A!");
  3137. LOG(m_sStreamSegmentInfo[0].scratchPath);
  3138. #endif
  3139. m_bSegAActive = false;
  3140. if (! m_bSegADelete)
  3141. {
  3142. #ifdef DIRECT_MJPEG_COMPOSING
  3143. if (m_pOutputFD[0])
  3144. {
  3145. fclose(m_pOutputFD[0]);
  3146. m_pOutputFD[0] = NULL;
  3147. };
  3148. #else //! DIRECT_MJPEG_COMPOSING
  3149. #ifdef OPENCV_VIDEO_OUTPUT
  3150. if (m_pEncoderA->isOpened())
  3151. {
  3152. m_pEncoderA->release();
  3153. #ifdef DEBUG_EXTRA
  3154. }
  3155. else
  3156. {
  3157. LOG(" Encoder A is NOT Opened!");
  3158. #endif
  3159. };
  3160. #else //! OPENCV_VIDEO_OUTPUT
  3161. av_write_trailer(m_pFormatCtxA);
  3162. avio_close(m_pFormatCtxA->pb);
  3163. #endif //! OPENCV_VIDEO_OUTPUT
  3164. #endif //! DIRECT_MJPEG_COMPOSING
  3165. EVENT_CONTAINER * bEVT = createBasicEvent(m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[0]);
  3166. if (bEVT)
  3167. {
  3168. basicEventHeap::getInstance()->broadcast(bEVT);
  3169. }
  3170. else
  3171. {
  3172. LOG_ERROR("Event Creation failure!");
  3173. }
  3174. #ifdef DEBUG_EXTRA
  3175. LOG("Stream A is Saved");
  3176. #endif
  3177. }
  3178. else
  3179. {
  3180. #ifdef DIRECT_MJPEG_COMPOSING
  3181. if (m_pOutputFD[0])
  3182. {
  3183. fclose(m_pOutputFD[0]);
  3184. m_pOutputFD[0] = NULL;
  3185. };
  3186. #else // !DIRECT_MJPEG_COMPOSING
  3187. #ifdef OPENCV_VIDEO_OUTPUT
  3188. if (m_pEncoderA->isOpened())
  3189. {
  3190. m_pEncoderA->release();
  3191. #ifdef DEBUG_EXTRA
  3192. }
  3193. else
  3194. {
  3195. LOG(" Encoder A is NOT Opened!");
  3196. #endif
  3197. };
  3198. #else // !OPENCV
  3199. #ifdef EVE_DONT_DELETE_SEGMENTS
  3200. av_write_trailer(m_pFormatCtxA);
  3201. #endif
  3202. avio_close(m_pFormatCtxA->pb);
  3203. #endif // !OPENCV_VIDEO_OUTPUT
  3204. #endif // !DIRECT_MJPEG_COMPOSING
  3205. #ifndef EVE_DONT_DELETE_SEGMENTS
  3206. unlink(m_sStreamSegmentInfo[0].scratchPath);
  3207. #endif
  3208. #ifdef DEBUG_EXTRA
  3209. LOG("Stream A is Closed!");
  3210. #endif
  3211. };
  3212. #ifndef DIRECT_MJPEG_COMPOSING
  3213. #ifndef OPENCV_VIDEO_OUTPUT
  3214. #ifdef SEPARATED_VIDEO_ENCODERS
  3215. #ifdef DEBUG_EXTRA
  3216. LOG("Del FCTX");
  3217. #endif
  3218. avformat_free_context(m_pFormatCtxA);
  3219. m_pVideoStrA = NULL;
  3220. #ifdef DEBUG_EXTRA
  3221. LOG("Del FCTX DONE");
  3222. #endif
  3223. #endif // SEPARATED_VIDEO_ENCODERS
  3224. #endif // !OPENCV
  3225. #endif // !DIRECT_MJPEG_COMPOSING
  3226. break;
  3227. };
  3228. case 0x02:{
  3229. #ifdef DEBUG_EXTRA
  3230. LOG("Actual Closing Video Stream B!");
  3231. LOG(m_sStreamSegmentInfo[1].scratchPath);
  3232. #endif
  3233. m_bSegBActive = false;
  3234. if (! m_bSegBDelete)
  3235. {
  3236. #ifdef DIRECT_MJPEG_COMPOSING
  3237. if (m_pOutputFD[1])
  3238. {
  3239. fclose(m_pOutputFD[1]);
  3240. m_pOutputFD[1] = NULL;
  3241. };
  3242. #else // !DIRECT_MJPEG_COMPOSING
  3243. #ifdef OPENCV_VIDEO_OUTPUT
  3244. if (m_pEncoderB->isOpened())
  3245. {
  3246. m_pEncoderB->release();
  3247. #ifdef DEBUG_EXTRA
  3248. }
  3249. else
  3250. {
  3251. LOG(" Encoder B is NOT Opened!");
  3252. #endif
  3253. };
  3254. #else // !OpenCV
  3255. av_write_trailer(m_pFormatCtxB);
  3256. avio_close(m_pFormatCtxB->pb);
  3257. #endif // !OPENCV_VIDEO_OUTPUT
  3258. #endif // !DIRECT_MJPEG_COMPOSING
  3259. EVENT_CONTAINER * bEVT = createBasicEvent(m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[1]);
  3260. if (bEVT)
  3261. {
  3262. basicEventHeap::getInstance()->broadcast(bEVT);
  3263. }
  3264. else
  3265. {
  3266. LOG_ERROR("Event Creation failure!");
  3267. }
  3268. #ifdef DEBUG_EXTRA
  3269. LOG("Stream B is Saved");
  3270. #endif
  3271. }
  3272. else
  3273. {
  3274. #ifdef DIRECT_MJPEG_COMPOSING
  3275. if (m_pOutputFD[1])
  3276. {
  3277. fclose(m_pOutputFD[1]);
  3278. m_pOutputFD[1] = NULL;
  3279. };
  3280. #else
  3281. #ifdef OPENCV_VIDEO_OUTPUT
  3282. if (m_pEncoderB->isOpened())
  3283. {
  3284. m_pEncoderB->release();
  3285. #ifdef DEBUG_EXTRA
  3286. }
  3287. else
  3288. {
  3289. LOG(" Encoder B is NOT Opened!");
  3290. #endif
  3291. };
  3292. #else // !OPenCV
  3293. #ifdef EVE_DONT_DELETE_SEGMENTS
  3294. av_write_trailer(m_pFormatCtxB);
  3295. #endif
  3296. avio_close(m_pFormatCtxB->pb);
  3297. #endif // !OPENCV_VIDEO_OUTPUT
  3298. #endif // !DIRECT_MJPEG_COMPOSING
  3299. #ifndef EVE_DONT_DELETE_SEGMENTS
  3300. unlink(m_sStreamSegmentInfo[1].scratchPath);
  3301. #endif
  3302. #ifdef DEBUG_EXTRA
  3303. LOG("Stream B is Closed!");
  3304. #endif
  3305. };
  3306. #ifndef DIRECT_MJPEG_COMPOSING
  3307. #ifndef OPENCV_VIDEO_OUTPUT
  3308. #ifdef SEPARATED_VIDEO_ENCODERS
  3309. avformat_free_context(m_pFormatCtxB);
  3310. m_pVideoStrB = NULL;
  3311. #endif // SEPARATED_VIDEO_ENCODERS
  3312. #endif // !OPENCV
  3313. #endif // !DIRECT_MJPEG_COMPOSING
  3314. break;
  3315. };
  3316. };
  3317. m_bCOP = 0;
  3318. m_mCurrentOperationProtector.unlock();
  3319. #endif // !EVE_SEQUENTAL_OUTPUT
  3320. #ifndef DIRECT_MJPEG_COMPOSING
  3321. #ifndef OPENCV_VIDEO_OUTPUT
  3322. #ifdef SEPARATED_VIDEO_ENCODERS
  3323. do
  3324. {
  3325. mPacket.data = NULL;
  3326. mPacket.size = 0;
  3327. rVal = avcodec_receive_packet(m_pCodecACtx, &mPacket);
  3328. if (rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF)
  3329. {
  3330. break;
  3331. }
  3332. else if (rVal < 0)
  3333. {
  3334. LOG_ERROR("Error during encoding ");
  3335. m_bThreadStatus = TH_ENDED;
  3336. break;
  3337. };
  3338. if (! rVal)
  3339. {
  3340. if (m_bSegAActive)
  3341. {
  3342. mPacket.stream_index = m_pVideoStrA->index;
  3343. mPacket.duration = 1;
  3344. m_mFrameCounterProtector.lock();
  3345. m_nSegAFrameCounter++;
  3346. m_mFrameCounterProtector.unlock();
  3347. mPacket.pts = av_rescale_q(m_nSegAFrameCounter, m_pCodecACtx->time_base, m_pVideoStrA->time_base);
  3348. // mPacket.pts = AV_NOPTS_VALUE;
  3349. // mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  3350. mPacket.dts = mPacket.pts;
  3351. int rc = av_write_frame(m_pFormatCtxA, &mPacket);
  3352. if (rc < 0)
  3353. {
  3354. // if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) {
  3355. m_bThreadStatus = TH_ENDED;
  3356. LOG_ERROR("Trouble with Video Output A!");
  3357. av_strerror(rc, tB, 128);
  3358. LOG_ERROR(tB);
  3359. break; // continue (changed since embed into do-while)
  3360. };
  3361. };
  3362. if (m_bSegBActive)
  3363. {
  3364. mPacket.stream_index = m_pVideoStrB->index;
  3365. mPacket.duration = 1;
  3366. m_mFrameCounterProtector.lock();
  3367. m_nSegBFrameCounter++;
  3368. m_mFrameCounterProtector.unlock();
  3369. mPacket.pts = av_rescale_q(m_nSegBFrameCounter, m_pCodecBCtx->time_base, m_pVideoStrB->time_base);
  3370. // mPacket.pts = AV_NOPTS_VALUE;
  3371. // mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base );
  3372. mPacket.dts = mPacket.pts;
  3373. int rc = av_write_frame(m_pFormatCtxB, &mPacket);
  3374. if (rc < 0)
  3375. {
  3376. // if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) {
  3377. m_bThreadStatus = TH_ENDED;
  3378. LOG_ERROR("Trouble with Video Output B!");
  3379. av_strerror(rc, tB, 128);
  3380. LOG_ERROR(tB);
  3381. break; // continue (changed since embed into do-while)
  3382. };
  3383. };
  3384. av_packet_unref(&mPacket);
  3385. };
  3386. }
  3387. while (rVal >= 0 && m_bThreadStatus != TH_ENDED);
  3388. #else // !SEPARATED_VIDEO_ENCODERS
  3389. do
  3390. {
  3391. mPacket.data = NULL;
  3392. mPacket.size = 0;
  3393. rVal = avcodec_receive_packet(m_pCodecCtx, &mPacket);
  3394. if (rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF)
  3395. {
  3396. break;
  3397. }
  3398. else if (rVal < 0)
  3399. {
  3400. LOG_ERROR("Error during encoding ");
  3401. m_bThreadStatus = TH_ENDED;
  3402. break;
  3403. };
  3404. if (! rVal)
  3405. {
  3406. if (m_bSegAActive)
  3407. {
  3408. mPacket.stream_index = m_pVideoStrA->index;
  3409. mPacket.duration = 1;
  3410. mPacket.pts = av_rescale_q(m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base);
  3411. // mPacket.pts = AV_NOPTS_VALUE;
  3412. // mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  3413. mPacket.dts = mPacket.pts;
  3414. int rc = av_write_frame(m_pFormatCtxA, &mPacket);
  3415. if (rc < 0)
  3416. {
  3417. // if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) {
  3418. m_bThreadStatus = TH_ENDED;
  3419. LOG_ERROR("Trouble with Video Output A!");
  3420. av_strerror(rc, tB, 128);
  3421. LOG_ERROR(tB);
  3422. break; // continue (changed since embed into do-while)
  3423. };
  3424. };
  3425. if (m_bSegBActive)
  3426. {
  3427. mPacket.stream_index = m_pVideoStrB->index;
  3428. mPacket.duration = 1;
  3429. mPacket.pts = av_rescale_q(m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base);
  3430. // mPacket.pts = AV_NOPTS_VALUE;
  3431. // mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base );
  3432. mPacket.dts = mPacket.pts;
  3433. int rc = av_write_frame(m_pFormatCtxB, &mPacket);
  3434. if (rc < 0)
  3435. {
  3436. // if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) {
  3437. m_bThreadStatus = TH_ENDED;
  3438. LOG_ERROR("Trouble with Video Output B!");
  3439. av_strerror(rc, tB, 128);
  3440. LOG_ERROR(tB);
  3441. break; // continue (changed since embed into do-while)
  3442. };
  3443. };
  3444. av_packet_unref(&mPacket);
  3445. };
  3446. }
  3447. while (rVal >= 0 && m_bThreadStatus != TH_ENDED);
  3448. #endif // ! SEPARATED_VIDEO_ENCODERS
  3449. #endif // !OPENCV_VIDEO_OUTPUT
  3450. #endif // !DIRECT_MJPEG_COMPOSING
  3451. SLEEP(10);
  3452. };
  3453. #ifdef DEBUG_EXTRA
  3454. LOG("Encoder Loop Ended!");
  3455. #endif
  3456. }
  3457. #ifndef EVE_SEQUENTAL_OUTPUT
  3458. void streamHandler::swapActiveStreams(void)
  3459. {
  3460. if (m_bSegDelete)
  3461. {
  3462. closeSegment();
  3463. }
  3464. // m_mFrameCounterProtector.lock();
  3465. m_bActiveEncoderStream = 1 - m_bActiveEncoderStream;
  3466. if (m_bActiveEncoderStream)
  3467. {
  3468. if (m_bSegADelete)
  3469. {
  3470. closeSegmentA();
  3471. }
  3472. }
  3473. else
  3474. {
  3475. if (m_bSegBDelete)
  3476. {
  3477. closeSegmentB();
  3478. }
  3479. };
  3480. // m_mFrameCounterProtector.unlock();
  3481. }
  3482. #endif // !EVE_SEQUENTAL_OUTPUT
  3483. #endif // EVE_ENABLE_VIDEO
  3484. bool streamHandler::triggerEvent(uint32_t eid, uint32_t & dbid, uint32_t & frame)
  3485. {
  3486. #ifdef DEBUG_EXTRA
  3487. LOG("Trig Evt");
  3488. #endif
  3489. #ifdef EVE_ENABLE_VIDEO
  3490. m_mFrameCounterProtector.lock();
  3491. // To Mark Events on the Frames
  3492. m_bEvtMarkerCounter = 255;
  3493. PF_TIMESTAMP ts;
  3494. getPFTS(&ts);
  3495. if ( dbid ) dbid = dbid;
  3496. #ifdef EVE_SEQUENTAL_OUTPUT
  3497. m_bSegDelete = false;
  3498. // Keep Also Next Segment if close to a end
  3499. if ( ( m_nSegmentLimitFrames - m_nSegFrameCounter ) < m_nPostAlarmFrames ) m_bNSegDelete = false;
  3500. m_nSegShiftFrames = frame = m_nSegFrameCounter;
  3501. m_sStreamSegmentInfo.eventIDS.push_back(eid);
  3502. m_sStreamSegmentInfo.eventTSS.push_back(ts.seconds);
  3503. m_sStreamSegmentInfo.eventTMS.push_back(ts.milliseconds);
  3504. m_sStreamSegmentInfo.eventFrames.push_back(frame);
  3505. // dbid = m_sStreamSegmentInfo.db_id;// = m_nVideoRegisteredDBID;
  3506. #else // !EVE_SEQUENTAL_OUTPUT
  3507. if (!m_bActiveEncoderStream)
  3508. { // Stream A is Active
  3509. m_bSegADelete = false;
  3510. m_nSegAShiftFrames = frame = m_nSegAFrameCounter;
  3511. }
  3512. else
  3513. { // Stream B is Active
  3514. m_bSegBDelete = false;
  3515. m_nSegBShiftFrames = frame = m_nSegBFrameCounter;
  3516. };
  3517. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventIDS.push_back(eid);
  3518. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventTSS.push_back(ts.seconds);
  3519. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventTMS.push_back(ts.milliseconds);
  3520. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventFrames.push_back(frame);
  3521. // dbid = m_sStreamSegmentInfo[m_bActiveEncoderStream].db_id;// = m_nVideoRegisteredDBID;
  3522. #endif // !EVE_SEQUENTAL_OUTPUT
  3523. m_mFrameCounterProtector.unlock();
  3524. // if ( dbid == 0 ) return false;
  3525. #ifdef DEBUG_EXTRA
  3526. LOG("Event Registered!");
  3527. #endif
  3528. #endif // EVE_ENABLE_VIDEO
  3529. return true;
  3530. }
  3531. bool streamHandler::triggerCamMove(void)
  3532. {
  3533. #ifdef DEBUG_EXTRA
  3534. LOG("Trig Cammove");
  3535. #endif
  3536. m_bCamMoveCounter = 255;
  3537. return true;
  3538. }
  3539. bool streamHandler::validate(void)
  3540. {
  3541. if (m_pSource)
  3542. {
  3543. if (m_pSource->getStatus() < MS_CLOSING)
  3544. {
  3545. #ifdef EVE_ENABLE_VIDEO
  3546. if (m_nGlobalFrameCounter)
  3547. { // Frames Received from a source
  3548. if (m_nGlobalFrameCounter == m_nValidatorFrameCounter)
  3549. {
  3550. // Video Stalled!
  3551. LOG_ERROR("Video Stalled");
  3552. return false; // Try use System to recuperate
  3553. }
  3554. else
  3555. {
  3556. m_nValidatorFrameCounter = m_nGlobalFrameCounter;
  3557. }
  3558. };
  3559. if (m_bThreadStatus < TH_ENDED)
  3560. {
  3561. return true;
  3562. }
  3563. else
  3564. {
  3565. LOG_ERROR("Thread Ended!");
  3566. }
  3567. #endif
  3568. }
  3569. else
  3570. {
  3571. LOG_ERROR("Video Ended");
  3572. }
  3573. };
  3574. return false;
  3575. }
  3576. #undef LOG
  3577. #undef LOG_ERROR
  3578. #endif // !LRF_PROXY_ONLY
  3579. //#undef DEBUG_EXTRA