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.

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