obs-ffmpeg-mux.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. /******************************************************************************
  2. Copyright (C) 2015 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <obs-module.h>
  15. #include <obs-hotkey.h>
  16. #include <obs-avc.h>
  17. #include <util/dstr.h>
  18. #include <util/pipe.h>
  19. #include <util/darray.h>
  20. #include <util/platform.h>
  21. #include <util/circlebuf.h>
  22. #include <util/threading.h>
  23. #include "ffmpeg-mux/ffmpeg-mux.h"
  24. #ifdef _WIN32
  25. #include "util/windows/win-version.h"
  26. #endif
  27. #include <libavformat/avformat.h>
  28. #define do_log(level, format, ...) \
  29. blog(level, "[ffmpeg muxer: '%s'] " format, \
  30. obs_output_get_name(stream->output), ##__VA_ARGS__)
  31. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  32. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  33. struct ffmpeg_muxer {
  34. obs_output_t *output;
  35. os_process_pipe_t *pipe;
  36. int64_t stop_ts;
  37. uint64_t total_bytes;
  38. struct dstr path;
  39. bool sent_headers;
  40. volatile bool active;
  41. volatile bool stopping;
  42. volatile bool capturing;
  43. /* replay buffer */
  44. struct circlebuf packets;
  45. int64_t cur_size;
  46. int64_t cur_time;
  47. int64_t max_size;
  48. int64_t max_time;
  49. int64_t save_ts;
  50. int keyframes;
  51. obs_hotkey_id hotkey;
  52. DARRAY(struct encoder_packet) mux_packets;
  53. pthread_t mux_thread;
  54. bool mux_thread_joinable;
  55. volatile bool muxing;
  56. };
  57. static const char *ffmpeg_mux_getname(void *type)
  58. {
  59. UNUSED_PARAMETER(type);
  60. return obs_module_text("FFmpegMuxer");
  61. }
  62. static inline void replay_buffer_clear(struct ffmpeg_muxer *stream)
  63. {
  64. while (stream->packets.size > 0) {
  65. struct encoder_packet pkt;
  66. circlebuf_pop_front(&stream->packets, &pkt, sizeof(pkt));
  67. obs_encoder_packet_release(&pkt);
  68. }
  69. circlebuf_free(&stream->packets);
  70. stream->cur_size = 0;
  71. stream->cur_time = 0;
  72. stream->max_size = 0;
  73. stream->max_time = 0;
  74. stream->save_ts = 0;
  75. stream->keyframes = 0;
  76. }
  77. static void ffmpeg_mux_destroy(void *data)
  78. {
  79. struct ffmpeg_muxer *stream = data;
  80. replay_buffer_clear(stream);
  81. if (stream->mux_thread_joinable)
  82. pthread_join(stream->mux_thread, NULL);
  83. da_free(stream->mux_packets);
  84. os_process_pipe_destroy(stream->pipe);
  85. dstr_free(&stream->path);
  86. bfree(stream);
  87. }
  88. static void *ffmpeg_mux_create(obs_data_t *settings, obs_output_t *output)
  89. {
  90. struct ffmpeg_muxer *stream = bzalloc(sizeof(*stream));
  91. stream->output = output;
  92. UNUSED_PARAMETER(settings);
  93. return stream;
  94. }
  95. #ifdef _WIN32
  96. #ifdef _WIN64
  97. #define FFMPEG_MUX "ffmpeg-mux64.exe"
  98. #else
  99. #define FFMPEG_MUX "ffmpeg-mux32.exe"
  100. #endif
  101. #else
  102. #define FFMPEG_MUX "ffmpeg-mux"
  103. #endif
  104. static inline bool capturing(struct ffmpeg_muxer *stream)
  105. {
  106. return os_atomic_load_bool(&stream->capturing);
  107. }
  108. static inline bool stopping(struct ffmpeg_muxer *stream)
  109. {
  110. return os_atomic_load_bool(&stream->stopping);
  111. }
  112. static inline bool active(struct ffmpeg_muxer *stream)
  113. {
  114. return os_atomic_load_bool(&stream->active);
  115. }
  116. /* TODO: allow codecs other than h264 whenever we start using them */
  117. static void add_video_encoder_params(struct ffmpeg_muxer *stream,
  118. struct dstr *cmd, obs_encoder_t *vencoder)
  119. {
  120. obs_data_t *settings = obs_encoder_get_settings(vencoder);
  121. int bitrate = (int)obs_data_get_int(settings, "bitrate");
  122. video_t *video = obs_get_video();
  123. const struct video_output_info *info = video_output_get_info(video);
  124. obs_data_release(settings);
  125. dstr_catf(cmd, "%s %d %d %d %d %d ",
  126. obs_encoder_get_codec(vencoder),
  127. bitrate,
  128. obs_output_get_width(stream->output),
  129. obs_output_get_height(stream->output),
  130. (int)info->fps_num,
  131. (int)info->fps_den);
  132. }
  133. static void add_audio_encoder_params(struct dstr *cmd, obs_encoder_t *aencoder)
  134. {
  135. obs_data_t *settings = obs_encoder_get_settings(aencoder);
  136. int bitrate = (int)obs_data_get_int(settings, "bitrate");
  137. audio_t *audio = obs_get_audio();
  138. struct dstr name = {0};
  139. obs_data_release(settings);
  140. dstr_copy(&name, obs_encoder_get_name(aencoder));
  141. dstr_replace(&name, "\"", "\"\"");
  142. dstr_catf(cmd, "\"%s\" %d %d %d ",
  143. name.array,
  144. bitrate,
  145. (int)obs_encoder_get_sample_rate(aencoder),
  146. (int)audio_output_get_channels(audio));
  147. dstr_free(&name);
  148. }
  149. static void log_muxer_params(struct ffmpeg_muxer *stream, const char *settings)
  150. {
  151. int ret;
  152. AVDictionary *dict = NULL;
  153. if ((ret = av_dict_parse_string(&dict, settings, "=", " ", 0))) {
  154. warn("Failed to parse muxer settings: %s\n%s",
  155. av_err2str(ret), settings);
  156. av_dict_free(&dict);
  157. return;
  158. }
  159. if (av_dict_count(dict) > 0) {
  160. struct dstr str = {0};
  161. AVDictionaryEntry *entry = NULL;
  162. while ((entry = av_dict_get(dict, "", entry,
  163. AV_DICT_IGNORE_SUFFIX)))
  164. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  165. info("Using muxer settings:%s", str.array);
  166. dstr_free(&str);
  167. }
  168. av_dict_free(&dict);
  169. }
  170. static void add_muxer_params(struct dstr *cmd, struct ffmpeg_muxer *stream)
  171. {
  172. obs_data_t *settings = obs_output_get_settings(stream->output);
  173. struct dstr mux = {0};
  174. dstr_copy(&mux, obs_data_get_string(settings, "muxer_settings"));
  175. log_muxer_params(stream, mux.array);
  176. dstr_replace(&mux, "\"", "\\\"");
  177. obs_data_release(settings);
  178. dstr_catf(cmd, "\"%s\" ", mux.array ? mux.array : "");
  179. dstr_free(&mux);
  180. }
  181. static void build_command_line(struct ffmpeg_muxer *stream, struct dstr *cmd,
  182. const char *path)
  183. {
  184. obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output);
  185. obs_encoder_t *aencoders[MAX_AUDIO_MIXES];
  186. int num_tracks = 0;
  187. for (;;) {
  188. obs_encoder_t *aencoder = obs_output_get_audio_encoder(
  189. stream->output, num_tracks);
  190. if (!aencoder)
  191. break;
  192. aencoders[num_tracks] = aencoder;
  193. num_tracks++;
  194. }
  195. dstr_init_move_array(cmd, obs_module_file(FFMPEG_MUX));
  196. dstr_insert_ch(cmd, 0, '\"');
  197. dstr_cat(cmd, "\" \"");
  198. dstr_copy(&stream->path, path);
  199. dstr_replace(&stream->path, "\"", "\"\"");
  200. dstr_cat_dstr(cmd, &stream->path);
  201. dstr_catf(cmd, "\" %d %d ", vencoder ? 1 : 0, num_tracks);
  202. if (vencoder)
  203. add_video_encoder_params(stream, cmd, vencoder);
  204. if (num_tracks) {
  205. dstr_cat(cmd, "aac ");
  206. for (int i = 0; i < num_tracks; i++) {
  207. add_audio_encoder_params(cmd, aencoders[i]);
  208. }
  209. }
  210. add_muxer_params(cmd, stream);
  211. }
  212. static inline void start_pipe(struct ffmpeg_muxer *stream, const char *path)
  213. {
  214. struct dstr cmd;
  215. build_command_line(stream, &cmd, path);
  216. stream->pipe = os_process_pipe_create(cmd.array, "w");
  217. dstr_free(&cmd);
  218. }
  219. static bool ffmpeg_mux_start(void *data)
  220. {
  221. struct ffmpeg_muxer *stream = data;
  222. obs_data_t *settings;
  223. const char *path;
  224. if (!obs_output_can_begin_data_capture(stream->output, 0))
  225. return false;
  226. if (!obs_output_initialize_encoders(stream->output, 0))
  227. return false;
  228. settings = obs_output_get_settings(stream->output);
  229. path = obs_data_get_string(settings, "path");
  230. /* ensure output path is writable to avoid generic error message */
  231. /* TODO: remove once ffmpeg-mux is refactored to pass errors back */
  232. FILE *test_file = os_fopen(path, "wb");
  233. if (!test_file) {
  234. struct dstr error_message;
  235. dstr_init_copy(&error_message,
  236. obs_module_text("UnableToWritePath"));
  237. #ifdef _WIN32
  238. // special warning for Windows 10 users about Defender
  239. struct win_version_info ver;
  240. get_win_ver(&ver);
  241. if (ver.major >= 10) {
  242. dstr_cat(&error_message, "\n\n");
  243. dstr_cat(&error_message,
  244. obs_module_text("WarnWindowsDefender"));
  245. }
  246. #endif
  247. dstr_replace(&error_message, "%1", path);
  248. obs_output_set_last_error(stream->output,
  249. error_message.array);
  250. dstr_free(&error_message);
  251. obs_data_release(settings);
  252. return false;
  253. }
  254. fclose(test_file);
  255. os_unlink(path);
  256. start_pipe(stream, path);
  257. obs_data_release(settings);
  258. if (!stream->pipe) {
  259. obs_output_set_last_error(stream->output,
  260. obs_module_text("HelperProcessFailed"));
  261. warn("Failed to create process pipe");
  262. return false;
  263. }
  264. /* write headers and start capture */
  265. os_atomic_set_bool(&stream->active, true);
  266. os_atomic_set_bool(&stream->capturing, true);
  267. stream->total_bytes = 0;
  268. obs_output_begin_data_capture(stream->output, 0);
  269. info("Writing file '%s'...", stream->path.array);
  270. return true;
  271. }
  272. static int deactivate(struct ffmpeg_muxer *stream)
  273. {
  274. int ret = -1;
  275. if (active(stream)) {
  276. ret = os_process_pipe_destroy(stream->pipe);
  277. stream->pipe = NULL;
  278. os_atomic_set_bool(&stream->active, false);
  279. os_atomic_set_bool(&stream->sent_headers, false);
  280. info("Output of file '%s' stopped", stream->path.array);
  281. }
  282. if (stopping(stream))
  283. obs_output_end_data_capture(stream->output);
  284. os_atomic_set_bool(&stream->stopping, false);
  285. return ret;
  286. }
  287. static void ffmpeg_mux_stop(void *data, uint64_t ts)
  288. {
  289. struct ffmpeg_muxer *stream = data;
  290. if (capturing(stream) || ts == 0) {
  291. stream->stop_ts = (int64_t)ts / 1000LL;
  292. os_atomic_set_bool(&stream->stopping, true);
  293. os_atomic_set_bool(&stream->capturing, false);
  294. }
  295. }
  296. static void signal_failure(struct ffmpeg_muxer *stream)
  297. {
  298. int ret = deactivate(stream);
  299. int code;
  300. switch (ret) {
  301. case FFM_UNSUPPORTED: code = OBS_OUTPUT_UNSUPPORTED; break;
  302. default: code = OBS_OUTPUT_ERROR;
  303. }
  304. obs_output_signal_stop(stream->output, code);
  305. os_atomic_set_bool(&stream->capturing, false);
  306. }
  307. static bool write_packet(struct ffmpeg_muxer *stream,
  308. struct encoder_packet *packet)
  309. {
  310. bool is_video = packet->type == OBS_ENCODER_VIDEO;
  311. size_t ret;
  312. struct ffm_packet_info info = {
  313. .pts = packet->pts,
  314. .dts = packet->dts,
  315. .size = (uint32_t)packet->size,
  316. .index = (int)packet->track_idx,
  317. .type = is_video ? FFM_PACKET_VIDEO : FFM_PACKET_AUDIO,
  318. .keyframe = packet->keyframe
  319. };
  320. ret = os_process_pipe_write(stream->pipe, (const uint8_t*)&info,
  321. sizeof(info));
  322. if (ret != sizeof(info)) {
  323. warn("os_process_pipe_write for info structure failed");
  324. signal_failure(stream);
  325. return false;
  326. }
  327. ret = os_process_pipe_write(stream->pipe, packet->data, packet->size);
  328. if (ret != packet->size) {
  329. warn("os_process_pipe_write for packet data failed");
  330. signal_failure(stream);
  331. return false;
  332. }
  333. stream->total_bytes += packet->size;
  334. return true;
  335. }
  336. static bool send_audio_headers(struct ffmpeg_muxer *stream,
  337. obs_encoder_t *aencoder, size_t idx)
  338. {
  339. struct encoder_packet packet = {
  340. .type = OBS_ENCODER_AUDIO,
  341. .timebase_den = 1,
  342. .track_idx = idx
  343. };
  344. obs_encoder_get_extra_data(aencoder, &packet.data, &packet.size);
  345. return write_packet(stream, &packet);
  346. }
  347. static bool send_video_headers(struct ffmpeg_muxer *stream)
  348. {
  349. obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output);
  350. struct encoder_packet packet = {
  351. .type = OBS_ENCODER_VIDEO,
  352. .timebase_den = 1
  353. };
  354. obs_encoder_get_extra_data(vencoder, &packet.data, &packet.size);
  355. return write_packet(stream, &packet);
  356. }
  357. static bool send_headers(struct ffmpeg_muxer *stream)
  358. {
  359. obs_encoder_t *aencoder;
  360. size_t idx = 0;
  361. if (!send_video_headers(stream))
  362. return false;
  363. do {
  364. aencoder = obs_output_get_audio_encoder(stream->output, idx);
  365. if (aencoder) {
  366. if (!send_audio_headers(stream, aencoder, idx)) {
  367. return false;
  368. }
  369. idx++;
  370. }
  371. } while (aencoder);
  372. return true;
  373. }
  374. static void ffmpeg_mux_data(void *data, struct encoder_packet *packet)
  375. {
  376. struct ffmpeg_muxer *stream = data;
  377. if (!active(stream))
  378. return;
  379. if (!stream->sent_headers) {
  380. if (!send_headers(stream))
  381. return;
  382. stream->sent_headers = true;
  383. }
  384. if (stopping(stream)) {
  385. if (packet->sys_dts_usec >= stream->stop_ts) {
  386. deactivate(stream);
  387. return;
  388. }
  389. }
  390. write_packet(stream, packet);
  391. }
  392. static obs_properties_t *ffmpeg_mux_properties(void *unused)
  393. {
  394. UNUSED_PARAMETER(unused);
  395. obs_properties_t *props = obs_properties_create();
  396. obs_properties_add_text(props, "path",
  397. obs_module_text("FilePath"),
  398. OBS_TEXT_DEFAULT);
  399. return props;
  400. }
  401. static uint64_t ffmpeg_mux_total_bytes(void *data)
  402. {
  403. struct ffmpeg_muxer *stream = data;
  404. return stream->total_bytes;
  405. }
  406. struct obs_output_info ffmpeg_muxer = {
  407. .id = "ffmpeg_muxer",
  408. .flags = OBS_OUTPUT_AV |
  409. OBS_OUTPUT_ENCODED |
  410. OBS_OUTPUT_MULTI_TRACK,
  411. .get_name = ffmpeg_mux_getname,
  412. .create = ffmpeg_mux_create,
  413. .destroy = ffmpeg_mux_destroy,
  414. .start = ffmpeg_mux_start,
  415. .stop = ffmpeg_mux_stop,
  416. .encoded_packet = ffmpeg_mux_data,
  417. .get_total_bytes= ffmpeg_mux_total_bytes,
  418. .get_properties = ffmpeg_mux_properties
  419. };
  420. /* ------------------------------------------------------------------------ */
  421. static const char *replay_buffer_getname(void *type)
  422. {
  423. UNUSED_PARAMETER(type);
  424. return obs_module_text("ReplayBuffer");
  425. }
  426. static void replay_buffer_hotkey(void *data, obs_hotkey_id id,
  427. obs_hotkey_t *hotkey, bool pressed)
  428. {
  429. UNUSED_PARAMETER(id);
  430. UNUSED_PARAMETER(hotkey);
  431. UNUSED_PARAMETER(pressed);
  432. struct ffmpeg_muxer *stream = data;
  433. if (os_atomic_load_bool(&stream->active))
  434. stream->save_ts = os_gettime_ns() / 1000LL;
  435. }
  436. static void save_replay_proc(void *data, calldata_t *cd)
  437. {
  438. replay_buffer_hotkey(data, 0, NULL, true);
  439. UNUSED_PARAMETER(cd);
  440. }
  441. static void get_last_replay(void *data, calldata_t *cd)
  442. {
  443. struct ffmpeg_muxer *stream = data;
  444. if (!os_atomic_load_bool(&stream->muxing))
  445. calldata_set_string(cd, "path", stream->path.array);
  446. }
  447. static void *replay_buffer_create(obs_data_t *settings, obs_output_t *output)
  448. {
  449. UNUSED_PARAMETER(settings);
  450. struct ffmpeg_muxer *stream = bzalloc(sizeof(*stream));
  451. stream->output = output;
  452. stream->hotkey = obs_hotkey_register_output(output,
  453. "ReplayBuffer.Save",
  454. obs_module_text("ReplayBuffer.Save"),
  455. replay_buffer_hotkey, stream);
  456. proc_handler_t *ph = obs_output_get_proc_handler(output);
  457. proc_handler_add(ph, "void save()", save_replay_proc, stream);
  458. proc_handler_add(ph, "void get_last_replay(out string path)",
  459. get_last_replay, stream);
  460. return stream;
  461. }
  462. static void replay_buffer_destroy(void *data)
  463. {
  464. struct ffmpeg_muxer *stream = data;
  465. if (stream->hotkey)
  466. obs_hotkey_unregister(stream->hotkey);
  467. ffmpeg_mux_destroy(data);
  468. }
  469. static bool replay_buffer_start(void *data)
  470. {
  471. struct ffmpeg_muxer *stream = data;
  472. if (!obs_output_can_begin_data_capture(stream->output, 0))
  473. return false;
  474. if (!obs_output_initialize_encoders(stream->output, 0))
  475. return false;
  476. obs_data_t *s = obs_output_get_settings(stream->output);
  477. stream->max_time = obs_data_get_int(s, "max_time_sec") * 1000000LL;
  478. stream->max_size = obs_data_get_int(s, "max_size_mb") * (1024 * 1024);
  479. obs_data_release(s);
  480. os_atomic_set_bool(&stream->active, true);
  481. os_atomic_set_bool(&stream->capturing, true);
  482. stream->total_bytes = 0;
  483. obs_output_begin_data_capture(stream->output, 0);
  484. return true;
  485. }
  486. static bool purge_front(struct ffmpeg_muxer *stream)
  487. {
  488. struct encoder_packet pkt;
  489. bool keyframe;
  490. circlebuf_pop_front(&stream->packets, &pkt, sizeof(pkt));
  491. keyframe = pkt.type == OBS_ENCODER_VIDEO && pkt.keyframe;
  492. if (keyframe)
  493. stream->keyframes--;
  494. if (!stream->packets.size) {
  495. stream->cur_size = 0;
  496. stream->cur_time = 0;
  497. } else {
  498. struct encoder_packet first;
  499. circlebuf_peek_front(&stream->packets, &first, sizeof(first));
  500. stream->cur_time = first.dts_usec;
  501. stream->cur_size -= (int64_t)pkt.size;
  502. }
  503. obs_encoder_packet_release(&pkt);
  504. return keyframe;
  505. }
  506. static inline void purge(struct ffmpeg_muxer *stream)
  507. {
  508. if (purge_front(stream)) {
  509. struct encoder_packet pkt;
  510. for (;;) {
  511. circlebuf_peek_front(&stream->packets, &pkt,
  512. sizeof(pkt));
  513. if (pkt.type == OBS_ENCODER_VIDEO && pkt.keyframe)
  514. return;
  515. purge_front(stream);
  516. }
  517. }
  518. }
  519. static inline void replay_buffer_purge(struct ffmpeg_muxer *stream,
  520. struct encoder_packet *pkt)
  521. {
  522. if (stream->max_size) {
  523. if (!stream->packets.size || stream->keyframes <= 2)
  524. return;
  525. while ((stream->cur_size + (int64_t)pkt->size) >
  526. stream->max_size)
  527. purge(stream);
  528. }
  529. if (!stream->packets.size || stream->keyframes <= 2)
  530. return;
  531. while ((pkt->dts_usec - stream->cur_time) > stream->max_time)
  532. purge(stream);
  533. }
  534. static void insert_packet(struct darray *array, struct encoder_packet *packet,
  535. int64_t video_offset, int64_t *audio_offsets,
  536. int64_t video_dts_offset, int64_t *audio_dts_offsets)
  537. {
  538. struct encoder_packet pkt;
  539. DARRAY(struct encoder_packet) packets;
  540. packets.da = *array;
  541. size_t idx;
  542. obs_encoder_packet_ref(&pkt, packet);
  543. if (pkt.type == OBS_ENCODER_VIDEO) {
  544. pkt.dts_usec -= video_offset;
  545. pkt.dts -= video_dts_offset;
  546. pkt.pts -= video_dts_offset;
  547. } else {
  548. pkt.dts_usec -= audio_offsets[pkt.track_idx];
  549. pkt.dts -= audio_dts_offsets[pkt.track_idx];
  550. pkt.pts -= audio_dts_offsets[pkt.track_idx];
  551. }
  552. for (idx = packets.num; idx > 0; idx--) {
  553. struct encoder_packet *p = packets.array + (idx - 1);
  554. if (p->dts_usec < pkt.dts_usec)
  555. break;
  556. }
  557. da_insert(packets, idx, &pkt);
  558. *array = packets.da;
  559. }
  560. static void *replay_buffer_mux_thread(void *data)
  561. {
  562. struct ffmpeg_muxer *stream = data;
  563. start_pipe(stream, stream->path.array);
  564. if (!stream->pipe) {
  565. warn("Failed to create process pipe");
  566. goto error;
  567. }
  568. if (!send_headers(stream)) {
  569. warn("Could not write headers for file '%s'",
  570. stream->path.array);
  571. goto error;
  572. }
  573. for (size_t i = 0; i < stream->mux_packets.num; i++) {
  574. struct encoder_packet *pkt = &stream->mux_packets.array[i];
  575. write_packet(stream, pkt);
  576. obs_encoder_packet_release(pkt);
  577. }
  578. info("Wrote replay buffer to '%s'", stream->path.array);
  579. error:
  580. os_process_pipe_destroy(stream->pipe);
  581. stream->pipe = NULL;
  582. da_free(stream->mux_packets);
  583. os_atomic_set_bool(&stream->muxing, false);
  584. return NULL;
  585. }
  586. static void replay_buffer_save(struct ffmpeg_muxer *stream)
  587. {
  588. const size_t size = sizeof(struct encoder_packet);
  589. size_t num_packets = stream->packets.size / size;
  590. da_reserve(stream->mux_packets, num_packets);
  591. /* ---------------------------- */
  592. /* reorder packets */
  593. bool found_video = false;
  594. bool found_audio[MAX_AUDIO_MIXES] = {0};
  595. int64_t video_offset = 0;
  596. int64_t video_dts_offset = 0;
  597. int64_t audio_offsets[MAX_AUDIO_MIXES] = {0};
  598. int64_t audio_dts_offsets[MAX_AUDIO_MIXES] = {0};
  599. for (size_t i = 0; i < num_packets; i++) {
  600. struct encoder_packet *pkt;
  601. pkt = circlebuf_data(&stream->packets, i * size);
  602. if (pkt->type == OBS_ENCODER_VIDEO) {
  603. if (!found_video) {
  604. video_offset = pkt->dts_usec;
  605. video_dts_offset = pkt->dts;
  606. found_video = true;
  607. }
  608. } else {
  609. if (!found_audio[pkt->track_idx]) {
  610. found_audio[pkt->track_idx] = true;
  611. audio_offsets[pkt->track_idx] = pkt->dts_usec;
  612. audio_dts_offsets[pkt->track_idx] = pkt->dts;
  613. }
  614. }
  615. insert_packet(&stream->mux_packets.da, pkt,
  616. video_offset, audio_offsets,
  617. video_dts_offset, audio_dts_offsets);
  618. }
  619. /* ---------------------------- */
  620. /* generate filename */
  621. obs_data_t *settings = obs_output_get_settings(stream->output);
  622. const char *dir = obs_data_get_string(settings, "directory");
  623. const char *fmt = obs_data_get_string(settings, "format");
  624. const char *ext = obs_data_get_string(settings, "extension");
  625. bool space = obs_data_get_bool(settings, "allow_spaces");
  626. char *filename = os_generate_formatted_filename(ext, space, fmt);
  627. dstr_copy(&stream->path, dir);
  628. dstr_replace(&stream->path, "\\", "/");
  629. if (dstr_end(&stream->path) != '/')
  630. dstr_cat_ch(&stream->path, '/');
  631. dstr_cat(&stream->path, filename);
  632. bfree(filename);
  633. obs_data_release(settings);
  634. /* ---------------------------- */
  635. os_atomic_set_bool(&stream->muxing, true);
  636. stream->mux_thread_joinable = pthread_create(&stream->mux_thread, NULL,
  637. replay_buffer_mux_thread, stream) == 0;
  638. }
  639. static void deactivate_replay_buffer(struct ffmpeg_muxer *stream)
  640. {
  641. if (stopping(stream))
  642. obs_output_end_data_capture(stream->output);
  643. os_atomic_set_bool(&stream->active, false);
  644. os_atomic_set_bool(&stream->sent_headers, false);
  645. os_atomic_set_bool(&stream->stopping, false);
  646. replay_buffer_clear(stream);
  647. }
  648. static void replay_buffer_data(void *data, struct encoder_packet *packet)
  649. {
  650. struct ffmpeg_muxer *stream = data;
  651. struct encoder_packet pkt;
  652. if (!active(stream))
  653. return;
  654. if (stopping(stream)) {
  655. if (packet->sys_dts_usec >= stream->stop_ts) {
  656. deactivate_replay_buffer(stream);
  657. return;
  658. }
  659. }
  660. obs_encoder_packet_ref(&pkt, packet);
  661. replay_buffer_purge(stream, &pkt);
  662. if (!stream->packets.size)
  663. stream->cur_time = pkt.dts_usec;
  664. stream->cur_size += pkt.size;
  665. circlebuf_push_back(&stream->packets, packet, sizeof(*packet));
  666. if (packet->type == OBS_ENCODER_VIDEO && packet->keyframe)
  667. stream->keyframes++;
  668. if (stream->save_ts && packet->sys_dts_usec >= stream->save_ts) {
  669. if (os_atomic_load_bool(&stream->muxing))
  670. return;
  671. if (stream->mux_thread_joinable) {
  672. pthread_join(stream->mux_thread, NULL);
  673. stream->mux_thread_joinable = false;
  674. }
  675. stream->save_ts = 0;
  676. replay_buffer_save(stream);
  677. }
  678. }
  679. static void replay_buffer_defaults(obs_data_t *s)
  680. {
  681. obs_data_set_default_int(s, "max_time_sec", 15);
  682. obs_data_set_default_int(s, "max_size_mb", 500);
  683. obs_data_set_default_string(s, "format", "%CCYY-%MM-%DD %hh-%mm-%ss");
  684. obs_data_set_default_string(s, "extension", "mp4");
  685. obs_data_set_default_bool(s, "allow_spaces", true);
  686. }
  687. struct obs_output_info replay_buffer = {
  688. .id = "replay_buffer",
  689. .flags = OBS_OUTPUT_AV |
  690. OBS_OUTPUT_ENCODED |
  691. OBS_OUTPUT_MULTI_TRACK,
  692. .get_name = replay_buffer_getname,
  693. .create = replay_buffer_create,
  694. .destroy = replay_buffer_destroy,
  695. .start = replay_buffer_start,
  696. .stop = ffmpeg_mux_stop,
  697. .encoded_packet = replay_buffer_data,
  698. .get_total_bytes= ffmpeg_mux_total_bytes,
  699. .get_defaults = replay_buffer_defaults
  700. };