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.

415 lines
9.6 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "fmp4Writer.h"
  2. #include <cerrno>
  3. #include <cstring>
  4. #include <ctime>
  5. #include <sys/stat.h>
  6. #include "../codecs/h264/h264.h"
  7. namespace mtx {
  8. namespace {
  9. // Box building: a box is written with a placeholder size that is patched when it ends
  10. class BoxWriter
  11. {
  12. public:
  13. Bytes buf;
  14. void u8(uint32_t v) { buf.push_back((uint8_t) v); }
  15. void u16(uint32_t v)
  16. {
  17. u8(v >> 8);
  18. u8(v);
  19. }
  20. void u24(uint32_t v)
  21. {
  22. u8(v >> 16);
  23. u16(v);
  24. }
  25. void u32(uint32_t v)
  26. {
  27. u16(v >> 16);
  28. u16(v);
  29. }
  30. void u64(uint64_t v)
  31. {
  32. u32((uint32_t) (v >> 32));
  33. u32((uint32_t) v);
  34. }
  35. void bytes(const Bytes & b) { buf.insert(buf.end(), b.begin(), b.end()); }
  36. void str(const char * s, size_t n) { buf.insert(buf.end(), (const uint8_t *) s, (const uint8_t *) s + n); }
  37. void zeros(size_t n) { buf.insert(buf.end(), n, 0); }
  38. size_t begin(const char * type)
  39. {
  40. size_t tPos = buf.size();
  41. u32(0);
  42. str(type, 4);
  43. return tPos;
  44. }
  45. size_t beginFull(const char * type, uint8_t version, uint32_t flags)
  46. {
  47. size_t tPos = begin(type);
  48. u8(version);
  49. u24(flags);
  50. return tPos;
  51. }
  52. void end(size_t pos)
  53. {
  54. uint32_t s = (uint32_t) (buf.size() - pos);
  55. buf[pos] = (uint8_t) (s >> 24);
  56. buf[pos + 1] = (uint8_t) (s >> 16);
  57. buf[pos + 2] = (uint8_t) (s >> 8);
  58. buf[pos + 3] = (uint8_t) s;
  59. }
  60. void patch32(size_t pos, uint32_t v)
  61. {
  62. buf[pos] = (uint8_t) (v >> 24);
  63. buf[pos + 1] = (uint8_t) (v >> 16);
  64. buf[pos + 2] = (uint8_t) (v >> 8);
  65. buf[pos + 3] = (uint8_t) v;
  66. }
  67. void matrix()
  68. {
  69. static const uint32_t m[9] = {0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000};
  70. for (uint32_t v : m)
  71. {
  72. u32(v);
  73. }
  74. }
  75. };
  76. const uint32_t TIMESCALE = 90000;
  77. const uint32_t TRACK_ID = 1;
  78. Bytes buildInit(const Bytes & sps, const Bytes & pps, int width, int height)
  79. {
  80. BoxWriter w;
  81. size_t b = w.begin("ftyp");
  82. w.str("iso6", 4);
  83. w.u32(1);
  84. w.str("iso6", 4);
  85. w.str("iso5", 4);
  86. w.str("mp41", 4);
  87. w.str("avc1", 4);
  88. w.end(b);
  89. size_t moov = w.begin("moov");
  90. {
  91. size_t mvhd = w.beginFull("mvhd", 0, 0);
  92. w.u32(0); // creation
  93. w.u32(0); // modification
  94. w.u32(1000);
  95. w.u32(0); // duration: unknown (fragmented)
  96. w.u32(0x00010000); // rate
  97. w.u16(0x0100); // volume
  98. w.zeros(10);
  99. w.matrix();
  100. w.zeros(24);
  101. w.u32(TRACK_ID + 1);
  102. w.end(mvhd);
  103. size_t trak = w.begin("trak");
  104. {
  105. size_t tkhd = w.beginFull("tkhd", 0, 3);
  106. w.u32(0);
  107. w.u32(0);
  108. w.u32(TRACK_ID);
  109. w.u32(0);
  110. w.u32(0); // duration
  111. w.zeros(8);
  112. w.u16(0); // layer
  113. w.u16(0); // alternate group
  114. w.u16(0); // volume
  115. w.u16(0);
  116. w.matrix();
  117. w.u32((uint32_t) width << 16);
  118. w.u32((uint32_t) height << 16);
  119. w.end(tkhd);
  120. size_t mdia = w.begin("mdia");
  121. {
  122. size_t mdhd = w.beginFull("mdhd", 0, 0);
  123. w.u32(0);
  124. w.u32(0);
  125. w.u32(TIMESCALE);
  126. w.u32(0);
  127. w.u16(0x55c4); // "und"
  128. w.u16(0);
  129. w.end(mdhd);
  130. size_t hdlr = w.beginFull("hdlr", 0, 0);
  131. w.u32(0);
  132. w.str("vide", 4);
  133. w.zeros(12);
  134. w.str("VideoHandler", 13);
  135. w.end(hdlr);
  136. size_t minf = w.begin("minf");
  137. {
  138. size_t vmhd = w.beginFull("vmhd", 0, 1);
  139. w.zeros(8);
  140. w.end(vmhd);
  141. size_t dinf = w.begin("dinf");
  142. size_t dref = w.beginFull("dref", 0, 0);
  143. w.u32(1);
  144. size_t url = w.beginFull("url ", 0, 1);
  145. w.end(url);
  146. w.end(dref);
  147. w.end(dinf);
  148. size_t stbl = w.begin("stbl");
  149. {
  150. size_t stsd = w.beginFull("stsd", 0, 0);
  151. w.u32(1);
  152. size_t avc1 = w.begin("avc1");
  153. w.zeros(6);
  154. w.u16(1); // data reference index
  155. w.zeros(16);
  156. w.u16((uint32_t) width);
  157. w.u16((uint32_t) height);
  158. w.u32(0x00480000); // 72 dpi
  159. w.u32(0x00480000);
  160. w.u32(0);
  161. w.u16(1); // frame count
  162. w.zeros(32); // compressor name
  163. w.u16(0x0018); // depth
  164. w.u16(0xffff); // pre_defined = -1
  165. size_t avcC = w.begin("avcC");
  166. w.bytes(h264::buildAvcC(sps, pps));
  167. w.end(avcC);
  168. w.end(avc1);
  169. w.end(stsd);
  170. size_t stts = w.beginFull("stts", 0, 0);
  171. w.u32(0);
  172. w.end(stts);
  173. size_t stsc = w.beginFull("stsc", 0, 0);
  174. w.u32(0);
  175. w.end(stsc);
  176. size_t stsz = w.beginFull("stsz", 0, 0);
  177. w.u32(0);
  178. w.u32(0);
  179. w.end(stsz);
  180. size_t stco = w.beginFull("stco", 0, 0);
  181. w.u32(0);
  182. w.end(stco);
  183. }
  184. w.end(stbl);
  185. }
  186. w.end(minf);
  187. }
  188. w.end(mdia);
  189. }
  190. w.end(trak);
  191. size_t mvex = w.begin("mvex");
  192. size_t trex = w.beginFull("trex", 0, 0);
  193. w.u32(TRACK_ID);
  194. w.u32(1); // default sample description
  195. w.u32(0);
  196. w.u32(0);
  197. w.u32(0);
  198. w.end(trex);
  199. w.end(mvex);
  200. }
  201. w.end(moov);
  202. return w.buf;
  203. }
  204. } // namespace
  205. bool mkdirAll(const std::string & dir)
  206. {
  207. if (dir.empty())
  208. {
  209. return true;
  210. }
  211. std::string tCur;
  212. size_t tPos = 0;
  213. while (tPos != std::string::npos)
  214. {
  215. tPos = dir.find('/', tPos + 1);
  216. tCur = dir.substr(0, tPos);
  217. if (tCur.empty())
  218. {
  219. continue;
  220. }
  221. if (mkdir(tCur.c_str(), 0755) != 0 && errno != EEXIST)
  222. {
  223. return false;
  224. }
  225. }
  226. return true;
  227. }
  228. std::string expandRecordPath(const std::string & pattern, const std::string & pathName, int64_t timeUs)
  229. {
  230. time_t tSec = (time_t) (timeUs / 1000000);
  231. struct tm tTm;
  232. localtime_r(&tSec, &tTm);
  233. std::string tOut;
  234. char tB[32];
  235. for (size_t i = 0; i < pattern.size(); i++)
  236. {
  237. if (pattern[i] != '%' || i + 1 >= pattern.size())
  238. {
  239. tOut.push_back(pattern[i]);
  240. continue;
  241. }
  242. if (pattern.compare(i, 5, "%path") == 0)
  243. {
  244. tOut += pathName;
  245. i += 4;
  246. continue;
  247. }
  248. char c = pattern[++i];
  249. switch (c)
  250. {
  251. case 'Y': snprintf(tB, sizeof(tB), "%04d", tTm.tm_year + 1900); break;
  252. case 'm': snprintf(tB, sizeof(tB), "%02d", tTm.tm_mon + 1); break;
  253. case 'd': snprintf(tB, sizeof(tB), "%02d", tTm.tm_mday); break;
  254. case 'H': snprintf(tB, sizeof(tB), "%02d", tTm.tm_hour); break;
  255. case 'M': snprintf(tB, sizeof(tB), "%02d", tTm.tm_min); break;
  256. case 'S': snprintf(tB, sizeof(tB), "%02d", tTm.tm_sec); break;
  257. case 'f': snprintf(tB, sizeof(tB), "%06d", (int) (timeUs % 1000000)); break;
  258. case 's': snprintf(tB, sizeof(tB), "%lld", (long long) tSec); break;
  259. default: snprintf(tB, sizeof(tB), "%%%c", c); break;
  260. }
  261. tOut += tB;
  262. }
  263. return tOut + ".mp4";
  264. }
  265. bool Fmp4Writer::open(const std::string & file, const Bytes & sps, const Bytes & pps, int width, int height, std::string & err)
  266. {
  267. close();
  268. size_t tSlash = file.rfind('/');
  269. if (tSlash != std::string::npos && ! mkdirAll(file.substr(0, tSlash)))
  270. {
  271. err = "cannot create the directory of " + file + ": " + strerror(errno);
  272. return false;
  273. }
  274. m_pFile = fopen(file.c_str(), "wb");
  275. if (m_pFile == nullptr)
  276. {
  277. err = "cannot create " + file + ": " + strerror(errno);
  278. return false;
  279. }
  280. m_sFile = file;
  281. m_nSequence = 0;
  282. m_vPending.clear();
  283. Bytes tInit = buildInit(sps, pps, width, height);
  284. if (fwrite(tInit.data(), 1, tInit.size(), m_pFile) != tInit.size() || fflush(m_pFile) != 0)
  285. {
  286. err = "write error on " + file + ": " + strerror(errno);
  287. fclose(m_pFile);
  288. m_pFile = nullptr;
  289. return false;
  290. }
  291. return true;
  292. }
  293. void Fmp4Writer::addSample(int64_t dts, const UnitPtr & unit)
  294. {
  295. Sample s;
  296. s.dts = dts;
  297. s.idr = unit->idr;
  298. s.data = h264::toAvcc(unit->nalus);
  299. m_vPending.push_back(std::move(s));
  300. }
  301. int64_t Fmp4Writer::pendingSpan() const
  302. {
  303. if (m_vPending.size() < 2)
  304. {
  305. return 0;
  306. }
  307. return m_vPending.back().dts - m_vPending.front().dts;
  308. }
  309. bool Fmp4Writer::flushFragment(int64_t nextDts, bool final, std::string & err)
  310. {
  311. if (m_pFile == nullptr || m_vPending.empty())
  312. {
  313. return true;
  314. }
  315. // The duration of the last sample is nextDts - its dts (the recorder flushes before adding the next
  316. // unit); on the final flush of a segment it is the previous duration.
  317. size_t tCount = m_vPending.size();
  318. BoxWriter w;
  319. size_t moof = w.begin("moof");
  320. size_t mfhd = w.beginFull("mfhd", 0, 0);
  321. w.u32(++m_nSequence);
  322. w.end(mfhd);
  323. size_t traf = w.begin("traf");
  324. size_t tfhd = w.beginFull("tfhd", 0, 0x020000); // default-base-is-moof
  325. w.u32(TRACK_ID);
  326. w.end(tfhd);
  327. size_t tfdt = w.beginFull("tfdt", 1, 0);
  328. w.u64((uint64_t) (m_vPending.front().dts < 0 ? 0 : m_vPending.front().dts));
  329. w.end(tfdt);
  330. size_t trun = w.beginFull("trun", 0, 0x000001 | 0x000100 | 0x000200 | 0x000400);
  331. w.u32((uint32_t) tCount);
  332. size_t tDataOffsetPos = w.buf.size();
  333. w.u32(0);
  334. size_t tMdatSize = 0;
  335. for (size_t i = 0; i < tCount; i++)
  336. {
  337. int64_t tDur;
  338. if (i + 1 < m_vPending.size())
  339. {
  340. tDur = m_vPending[i + 1].dts - m_vPending[i].dts;
  341. }
  342. else
  343. {
  344. tDur = final ? m_nLastDuration : nextDts - m_vPending[i].dts;
  345. }
  346. if (tDur <= 0 || tDur > 10 * (int64_t) TIMESCALE)
  347. {
  348. tDur = m_nLastDuration; // timestamp jump or B-frames: keep the timeline going
  349. }
  350. m_nLastDuration = tDur;
  351. w.u32((uint32_t) tDur);
  352. w.u32((uint32_t) m_vPending[i].data.size());
  353. w.u32(m_vPending[i].idr ? 0x02000000 : 0x01010000);
  354. tMdatSize += m_vPending[i].data.size();
  355. }
  356. w.end(trun);
  357. w.end(traf);
  358. w.end(moof);
  359. w.patch32(tDataOffsetPos, (uint32_t) (w.buf.size() + 8)); // from the start of moof to the mdat payload
  360. w.u32((uint32_t) (tMdatSize + 8));
  361. w.str("mdat", 4);
  362. bool tOk = fwrite(w.buf.data(), 1, w.buf.size(), m_pFile) == w.buf.size();
  363. for (size_t i = 0; i < tCount && tOk; i++)
  364. {
  365. tOk = fwrite(m_vPending[i].data.data(), 1, m_vPending[i].data.size(), m_pFile) == m_vPending[i].data.size();
  366. }
  367. tOk = tOk && fflush(m_pFile) == 0;
  368. m_vPending.erase(m_vPending.begin(), m_vPending.begin() + tCount);
  369. if (! tOk)
  370. {
  371. err = "write error on " + m_sFile + ": " + strerror(errno);
  372. return false;
  373. }
  374. return true;
  375. }
  376. void Fmp4Writer::close()
  377. {
  378. if (m_pFile != nullptr)
  379. {
  380. std::string tErr;
  381. flushFragment(0, true, tErr);
  382. fclose(m_pFile);
  383. m_pFile = nullptr;
  384. }
  385. m_vPending.clear();
  386. }
  387. } // namespace mtx