obs-ffmpeg-mux.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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. #define FFMPEG_MUX "obs-ffmpeg-mux.exe"
  97. #else
  98. #define FFMPEG_MUX "obs-ffmpeg-mux"
  99. #endif
  100. static inline bool capturing(struct ffmpeg_muxer *stream)
  101. {
  102. return os_atomic_load_bool(&stream->capturing);
  103. }
  104. static inline bool stopping(struct ffmpeg_muxer *stream)
  105. {
  106. return os_atomic_load_bool(&stream->stopping);
  107. }
  108. static inline bool active(struct ffmpeg_muxer *stream)
  109. {
  110. return os_atomic_load_bool(&stream->active);
  111. }
  112. /* TODO: allow codecs other than h264 whenever we start using them */
  113. static void add_video_encoder_params(struct ffmpeg_muxer *stream,
  114. struct dstr *cmd, obs_encoder_t *vencoder)
  115. {
  116. obs_data_t *settings = obs_encoder_get_settings(vencoder);
  117. int bitrate = (int)obs_data_get_int(settings, "bitrate");
  118. video_t *video = obs_get_video();
  119. const struct video_output_info *info = video_output_get_info(video);
  120. obs_data_release(settings);
  121. dstr_catf(cmd, "%s %d %d %d %d %d ", obs_encoder_get_codec(vencoder),
  122. bitrate, obs_output_get_width(stream->output),
  123. obs_output_get_height(stream->output), (int)info->fps_num,
  124. (int)info->fps_den);
  125. }
  126. static void add_audio_encoder_params(struct dstr *cmd, obs_encoder_t *aencoder)
  127. {
  128. obs_data_t *settings = obs_encoder_get_settings(aencoder);
  129. int bitrate = (int)obs_data_get_int(settings, "bitrate");
  130. audio_t *audio = obs_get_audio();
  131. struct dstr name = {0};
  132. obs_data_release(settings);
  133. dstr_copy(&name, obs_encoder_get_name(aencoder));
  134. dstr_replace(&name, "\"", "\"\"");
  135. dstr_catf(cmd, "\"%s\" %d %d %d ", name.array, bitrate,
  136. (int)obs_encoder_get_sample_rate(aencoder),
  137. (int)audio_output_get_channels(audio));
  138. dstr_free(&name);
  139. }
  140. static void log_muxer_params(struct ffmpeg_muxer *stream, const char *settings)
  141. {
  142. int ret;
  143. AVDictionary *dict = NULL;
  144. if ((ret = av_dict_parse_string(&dict, settings, "=", " ", 0))) {
  145. warn("Failed to parse muxer settings: %s\n%s", av_err2str(ret),
  146. settings);
  147. av_dict_free(&dict);
  148. return;
  149. }
  150. if (av_dict_count(dict) > 0) {
  151. struct dstr str = {0};
  152. AVDictionaryEntry *entry = NULL;
  153. while ((entry = av_dict_get(dict, "", entry,
  154. AV_DICT_IGNORE_SUFFIX)))
  155. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  156. info("Using muxer settings:%s", str.array);
  157. dstr_free(&str);
  158. }
  159. av_dict_free(&dict);
  160. }
  161. static void add_muxer_params(struct dstr *cmd, struct ffmpeg_muxer *stream)
  162. {
  163. obs_data_t *settings = obs_output_get_settings(stream->output);
  164. struct dstr mux = {0};
  165. dstr_copy(&mux, obs_data_get_string(settings, "muxer_settings"));
  166. log_muxer_params(stream, mux.array);
  167. dstr_replace(&mux, "\"", "\\\"");
  168. obs_data_release(settings);
  169. dstr_catf(cmd, "\"%s\" ", mux.array ? mux.array : "");
  170. dstr_free(&mux);
  171. }
  172. static void build_command_line(struct ffmpeg_muxer *stream, struct dstr *cmd,
  173. const char *path)
  174. {
  175. obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output);
  176. obs_encoder_t *aencoders[MAX_AUDIO_MIXES];
  177. int num_tracks = 0;
  178. for (;;) {
  179. obs_encoder_t *aencoder = obs_output_get_audio_encoder(
  180. stream->output, num_tracks);
  181. if (!aencoder)
  182. break;
  183. aencoders[num_tracks] = aencoder;
  184. num_tracks++;
  185. }
  186. dstr_init_move_array(cmd, os_get_executable_path_ptr(FFMPEG_MUX));
  187. dstr_insert_ch(cmd, 0, '\"');
  188. dstr_cat(cmd, "\" \"");
  189. dstr_copy(&stream->path, path);
  190. dstr_replace(&stream->path, "\"", "\"\"");
  191. dstr_cat_dstr(cmd, &stream->path);
  192. dstr_catf(cmd, "\" %d %d ", vencoder ? 1 : 0, num_tracks);
  193. if (vencoder)
  194. add_video_encoder_params(stream, cmd, vencoder);
  195. if (num_tracks) {
  196. dstr_cat(cmd, "aac ");
  197. for (int i = 0; i < num_tracks; i++) {
  198. add_audio_encoder_params(cmd, aencoders[i]);
  199. }
  200. }
  201. add_muxer_params(cmd, stream);
  202. }
  203. static inline void start_pipe(struct ffmpeg_muxer *stream, const char *path)
  204. {
  205. struct dstr cmd;
  206. build_command_line(stream, &cmd, path);
  207. stream->pipe = os_process_pipe_create(cmd.array, "w");
  208. dstr_free(&cmd);
  209. }
  210. static bool ffmpeg_mux_start(void *data)
  211. {
  212. struct ffmpeg_muxer *stream = data;
  213. obs_data_t *settings;
  214. const char *path;
  215. if (!obs_output_can_begin_data_capture(stream->output, 0))
  216. return false;
  217. if (!obs_output_initialize_encoders(stream->output, 0))
  218. return false;
  219. settings = obs_output_get_settings(stream->output);
  220. path = obs_data_get_string(settings, "path");
  221. /* ensure output path is writable to avoid generic error message */
  222. /* TODO: remove once ffmpeg-mux is refactored to pass errors back */
  223. FILE *test_file = os_fopen(path, "wb");
  224. if (!test_file) {
  225. struct dstr error_message;
  226. dstr_init_copy(&error_message,
  227. obs_module_text("UnableToWritePath"));
  228. #ifdef _WIN32
  229. // special warning for Windows 10 users about Defender
  230. struct win_version_info ver;
  231. get_win_ver(&ver);
  232. if (ver.major >= 10) {
  233. dstr_cat(&error_message, "\n\n");
  234. dstr_cat(&error_message,
  235. obs_module_text("WarnWindowsDefender"));
  236. }
  237. #endif
  238. dstr_replace(&error_message, "%1", path);
  239. obs_output_set_last_error(stream->output, error_message.array);
  240. dstr_free(&error_message);
  241. obs_data_release(settings);
  242. return false;
  243. }
  244. fclose(test_file);
  245. os_unlink(path);
  246. start_pipe(stream, path);
  247. obs_data_release(settings);
  248. if (!stream->pipe) {
  249. obs_output_set_last_error(
  250. stream->output, obs_module_text("HelperProcessFailed"));
  251. warn("Failed to create process pipe");
  252. return false;
  253. }
  254. /* write headers and start capture */
  255. os_atomic_set_bool(&stream->active, true);
  256. os_atomic_set_bool(&stream->capturing, true);
  257. stream->total_bytes = 0;
  258. obs_output_begin_data_capture(stream->output, 0);
  259. info("Writing file '%s'...", stream->path.array);
  260. return true;
  261. }
  262. static int deactivate(struct ffmpeg_muxer *stream, int code)
  263. {
  264. int ret = -1;
  265. if (active(stream)) {
  266. ret = os_process_pipe_destroy(stream->pipe);
  267. stream->pipe = NULL;
  268. os_atomic_set_bool(&stream->active, false);
  269. os_atomic_set_bool(&stream->sent_headers, false);
  270. info("Output of file '%s' stopped", stream->path.array);
  271. }
  272. if (code) {
  273. obs_output_signal_stop(stream->output, code);
  274. } else if (stopping(stream)) {
  275. obs_output_end_data_capture(stream->output);
  276. }
  277. os_atomic_set_bool(&stream->stopping, false);
  278. return ret;
  279. }
  280. static void ffmpeg_mux_stop(void *data, uint64_t ts)
  281. {
  282. struct ffmpeg_muxer *stream = data;
  283. if (capturing(stream) || ts == 0) {
  284. stream->stop_ts = (int64_t)ts / 1000LL;
  285. os_atomic_set_bool(&stream->stopping, true);
  286. os_atomic_set_bool(&stream->capturing, false);
  287. }
  288. }
  289. static void signal_failure(struct ffmpeg_muxer *stream)
  290. {
  291. char error[1024];
  292. int ret;
  293. int code;
  294. size_t len;
  295. len = os_process_pipe_read_err(stream->pipe, (uint8_t *)error,
  296. sizeof(error) - 1);
  297. if (len > 0) {
  298. error[len] = 0;
  299. warn("ffmpeg-mux: %s", error);
  300. obs_output_set_last_error(stream->output, error);
  301. }
  302. ret = deactivate(stream, 0);
  303. switch (ret) {
  304. case FFM_UNSUPPORTED:
  305. code = OBS_OUTPUT_UNSUPPORTED;
  306. break;
  307. default:
  308. code = OBS_OUTPUT_ERROR;
  309. }
  310. obs_output_signal_stop(stream->output, code);
  311. os_atomic_set_bool(&stream->capturing, false);
  312. }
  313. static bool write_packet(struct ffmpeg_muxer *stream,
  314. struct encoder_packet *packet)
  315. {
  316. bool is_video = packet->type == OBS_ENCODER_VIDEO;
  317. size_t ret;
  318. struct ffm_packet_info info = {.pts = packet->pts,
  319. .dts = packet->dts,
  320. .size = (uint32_t)packet->size,
  321. .index = (int)packet->track_idx,
  322. .type = is_video ? FFM_PACKET_VIDEO
  323. : FFM_PACKET_AUDIO,
  324. .keyframe = packet->keyframe};
  325. ret = os_process_pipe_write(stream->pipe, (const uint8_t *)&info,
  326. sizeof(info));
  327. if (ret != sizeof(info)) {
  328. warn("os_process_pipe_write for info structure failed");
  329. signal_failure(stream);
  330. return false;
  331. }
  332. ret = os_process_pipe_write(stream->pipe, packet->data, packet->size);
  333. if (ret != packet->size) {
  334. warn("os_process_pipe_write for packet data failed");
  335. signal_failure(stream);
  336. return false;
  337. }
  338. stream->total_bytes += packet->size;
  339. return true;
  340. }
  341. static bool send_audio_headers(struct ffmpeg_muxer *stream,
  342. obs_encoder_t *aencoder, size_t idx)
  343. {
  344. struct encoder_packet packet = {
  345. .type = OBS_ENCODER_AUDIO, .timebase_den = 1, .track_idx = idx};
  346. obs_encoder_get_extra_data(aencoder, &packet.data, &packet.size);
  347. return write_packet(stream, &packet);
  348. }
  349. static bool send_video_headers(struct ffmpeg_muxer *stream)
  350. {
  351. obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output);
  352. struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO,
  353. .timebase_den = 1};
  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. /* encoder failure */
  380. if (!packet) {
  381. deactivate(stream, OBS_OUTPUT_ENCODE_ERROR);
  382. return;
  383. }
  384. if (!stream->sent_headers) {
  385. if (!send_headers(stream))
  386. return;
  387. stream->sent_headers = true;
  388. }
  389. if (stopping(stream)) {
  390. if (packet->sys_dts_usec >= stream->stop_ts) {
  391. deactivate(stream, 0);
  392. return;
  393. }
  394. }
  395. write_packet(stream, packet);
  396. }
  397. static obs_properties_t *ffmpeg_mux_properties(void *unused)
  398. {
  399. UNUSED_PARAMETER(unused);
  400. obs_properties_t *props = obs_properties_create();
  401. obs_properties_add_text(props, "path", obs_module_text("FilePath"),
  402. OBS_TEXT_DEFAULT);
  403. return props;
  404. }
  405. static uint64_t ffmpeg_mux_total_bytes(void *data)
  406. {
  407. struct ffmpeg_muxer *stream = data;
  408. return stream->total_bytes;
  409. }
  410. struct obs_output_info ffmpeg_muxer = {
  411. .id = "ffmpeg_muxer",
  412. .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK |
  413. OBS_OUTPUT_CAN_PAUSE,
  414. .get_name = ffmpeg_mux_getname,
  415. .create = ffmpeg_mux_create,
  416. .destroy = ffmpeg_mux_destroy,
  417. .start = ffmpeg_mux_start,
  418. .stop = ffmpeg_mux_stop,
  419. .encoded_packet = ffmpeg_mux_data,
  420. .get_total_bytes = ffmpeg_mux_total_bytes,
  421. .get_properties = ffmpeg_mux_properties,
  422. };
  423. /* ------------------------------------------------------------------------ */
  424. static const char *replay_buffer_getname(void *type)
  425. {
  426. UNUSED_PARAMETER(type);
  427. return obs_module_text("ReplayBuffer");
  428. }
  429. static void replay_buffer_hotkey(void *data, obs_hotkey_id id,
  430. obs_hotkey_t *hotkey, bool pressed)
  431. {
  432. UNUSED_PARAMETER(id);
  433. UNUSED_PARAMETER(hotkey);
  434. UNUSED_PARAMETER(pressed);
  435. if (!pressed)
  436. return;
  437. struct ffmpeg_muxer *stream = data;
  438. if (os_atomic_load_bool(&stream->active)) {
  439. obs_encoder_t *vencoder =
  440. obs_output_get_video_encoder(stream->output);
  441. if (obs_encoder_paused(vencoder)) {
  442. info("Could not save buffer because encoders paused");
  443. return;
  444. }
  445. stream->save_ts = os_gettime_ns() / 1000LL;
  446. }
  447. }
  448. static void save_replay_proc(void *data, calldata_t *cd)
  449. {
  450. replay_buffer_hotkey(data, 0, NULL, true);
  451. UNUSED_PARAMETER(cd);
  452. }
  453. static void get_last_replay(void *data, calldata_t *cd)
  454. {
  455. struct ffmpeg_muxer *stream = data;
  456. if (!os_atomic_load_bool(&stream->muxing))
  457. calldata_set_string(cd, "path", stream->path.array);
  458. }
  459. static void *replay_buffer_create(obs_data_t *settings, obs_output_t *output)
  460. {
  461. UNUSED_PARAMETER(settings);
  462. struct ffmpeg_muxer *stream = bzalloc(sizeof(*stream));
  463. stream->output = output;
  464. stream->hotkey =
  465. obs_hotkey_register_output(output, "ReplayBuffer.Save",
  466. obs_module_text("ReplayBuffer.Save"),
  467. replay_buffer_hotkey, stream);
  468. proc_handler_t *ph = obs_output_get_proc_handler(output);
  469. proc_handler_add(ph, "void save()", save_replay_proc, stream);
  470. proc_handler_add(ph, "void get_last_replay(out string path)",
  471. get_last_replay, stream);
  472. return stream;
  473. }
  474. static void replay_buffer_destroy(void *data)
  475. {
  476. struct ffmpeg_muxer *stream = data;
  477. if (stream->hotkey)
  478. obs_hotkey_unregister(stream->hotkey);
  479. ffmpeg_mux_destroy(data);
  480. }
  481. static bool replay_buffer_start(void *data)
  482. {
  483. struct ffmpeg_muxer *stream = data;
  484. if (!obs_output_can_begin_data_capture(stream->output, 0))
  485. return false;
  486. if (!obs_output_initialize_encoders(stream->output, 0))
  487. return false;
  488. obs_data_t *s = obs_output_get_settings(stream->output);
  489. stream->max_time = obs_data_get_int(s, "max_time_sec") * 1000000LL;
  490. stream->max_size = obs_data_get_int(s, "max_size_mb") * (1024 * 1024);
  491. obs_data_release(s);
  492. os_atomic_set_bool(&stream->active, true);
  493. os_atomic_set_bool(&stream->capturing, true);
  494. stream->total_bytes = 0;
  495. obs_output_begin_data_capture(stream->output, 0);
  496. return true;
  497. }
  498. static bool purge_front(struct ffmpeg_muxer *stream)
  499. {
  500. struct encoder_packet pkt;
  501. bool keyframe;
  502. circlebuf_pop_front(&stream->packets, &pkt, sizeof(pkt));
  503. keyframe = pkt.type == OBS_ENCODER_VIDEO && pkt.keyframe;
  504. if (keyframe)
  505. stream->keyframes--;
  506. if (!stream->packets.size) {
  507. stream->cur_size = 0;
  508. stream->cur_time = 0;
  509. } else {
  510. struct encoder_packet first;
  511. circlebuf_peek_front(&stream->packets, &first, sizeof(first));
  512. stream->cur_time = first.dts_usec;
  513. stream->cur_size -= (int64_t)pkt.size;
  514. }
  515. obs_encoder_packet_release(&pkt);
  516. return keyframe;
  517. }
  518. static inline void purge(struct ffmpeg_muxer *stream)
  519. {
  520. if (purge_front(stream)) {
  521. struct encoder_packet pkt;
  522. for (;;) {
  523. circlebuf_peek_front(&stream->packets, &pkt,
  524. sizeof(pkt));
  525. if (pkt.type == OBS_ENCODER_VIDEO && pkt.keyframe)
  526. return;
  527. purge_front(stream);
  528. }
  529. }
  530. }
  531. static inline void replay_buffer_purge(struct ffmpeg_muxer *stream,
  532. struct encoder_packet *pkt)
  533. {
  534. if (stream->max_size) {
  535. if (!stream->packets.size || stream->keyframes <= 2)
  536. return;
  537. while ((stream->cur_size + (int64_t)pkt->size) >
  538. stream->max_size)
  539. purge(stream);
  540. }
  541. if (!stream->packets.size || stream->keyframes <= 2)
  542. return;
  543. while ((pkt->dts_usec - stream->cur_time) > stream->max_time)
  544. purge(stream);
  545. }
  546. static void insert_packet(struct darray *array, struct encoder_packet *packet,
  547. int64_t video_offset, int64_t *audio_offsets,
  548. int64_t video_dts_offset, int64_t *audio_dts_offsets)
  549. {
  550. struct encoder_packet pkt;
  551. DARRAY(struct encoder_packet) packets;
  552. packets.da = *array;
  553. size_t idx;
  554. obs_encoder_packet_ref(&pkt, packet);
  555. if (pkt.type == OBS_ENCODER_VIDEO) {
  556. pkt.dts_usec -= video_offset;
  557. pkt.dts -= video_dts_offset;
  558. pkt.pts -= video_dts_offset;
  559. } else {
  560. pkt.dts_usec -= audio_offsets[pkt.track_idx];
  561. pkt.dts -= audio_dts_offsets[pkt.track_idx];
  562. pkt.pts -= audio_dts_offsets[pkt.track_idx];
  563. }
  564. for (idx = packets.num; idx > 0; idx--) {
  565. struct encoder_packet *p = packets.array + (idx - 1);
  566. if (p->dts_usec < pkt.dts_usec)
  567. break;
  568. }
  569. da_insert(packets, idx, &pkt);
  570. *array = packets.da;
  571. }
  572. static void *replay_buffer_mux_thread(void *data)
  573. {
  574. struct ffmpeg_muxer *stream = data;
  575. start_pipe(stream, stream->path.array);
  576. if (!stream->pipe) {
  577. warn("Failed to create process pipe");
  578. goto error;
  579. }
  580. if (!send_headers(stream)) {
  581. warn("Could not write headers for file '%s'",
  582. stream->path.array);
  583. goto error;
  584. }
  585. for (size_t i = 0; i < stream->mux_packets.num; i++) {
  586. struct encoder_packet *pkt = &stream->mux_packets.array[i];
  587. write_packet(stream, pkt);
  588. obs_encoder_packet_release(pkt);
  589. }
  590. info("Wrote replay buffer to '%s'", stream->path.array);
  591. error:
  592. os_process_pipe_destroy(stream->pipe);
  593. stream->pipe = NULL;
  594. da_free(stream->mux_packets);
  595. os_atomic_set_bool(&stream->muxing, false);
  596. return NULL;
  597. }
  598. static void replay_buffer_save(struct ffmpeg_muxer *stream)
  599. {
  600. const size_t size = sizeof(struct encoder_packet);
  601. size_t num_packets = stream->packets.size / size;
  602. da_reserve(stream->mux_packets, num_packets);
  603. /* ---------------------------- */
  604. /* reorder packets */
  605. bool found_video = false;
  606. bool found_audio[MAX_AUDIO_MIXES] = {0};
  607. int64_t video_offset = 0;
  608. int64_t video_dts_offset = 0;
  609. int64_t audio_offsets[MAX_AUDIO_MIXES] = {0};
  610. int64_t audio_dts_offsets[MAX_AUDIO_MIXES] = {0};
  611. for (size_t i = 0; i < num_packets; i++) {
  612. struct encoder_packet *pkt;
  613. pkt = circlebuf_data(&stream->packets, i * size);
  614. if (pkt->type == OBS_ENCODER_VIDEO) {
  615. if (!found_video) {
  616. video_offset = pkt->dts_usec;
  617. video_dts_offset = pkt->dts;
  618. found_video = true;
  619. }
  620. } else {
  621. if (!found_audio[pkt->track_idx]) {
  622. found_audio[pkt->track_idx] = true;
  623. audio_offsets[pkt->track_idx] = pkt->dts_usec;
  624. audio_dts_offsets[pkt->track_idx] = pkt->dts;
  625. }
  626. }
  627. insert_packet(&stream->mux_packets.da, pkt, video_offset,
  628. audio_offsets, video_dts_offset,
  629. audio_dts_offsets);
  630. }
  631. /* ---------------------------- */
  632. /* generate filename */
  633. obs_data_t *settings = obs_output_get_settings(stream->output);
  634. const char *dir = obs_data_get_string(settings, "directory");
  635. const char *fmt = obs_data_get_string(settings, "format");
  636. const char *ext = obs_data_get_string(settings, "extension");
  637. bool space = obs_data_get_bool(settings, "allow_spaces");
  638. char *filename = os_generate_formatted_filename(ext, space, fmt);
  639. dstr_copy(&stream->path, dir);
  640. dstr_replace(&stream->path, "\\", "/");
  641. if (dstr_end(&stream->path) != '/')
  642. dstr_cat_ch(&stream->path, '/');
  643. dstr_cat(&stream->path, filename);
  644. bfree(filename);
  645. obs_data_release(settings);
  646. /* ---------------------------- */
  647. os_atomic_set_bool(&stream->muxing, true);
  648. stream->mux_thread_joinable = pthread_create(&stream->mux_thread, NULL,
  649. replay_buffer_mux_thread,
  650. stream) == 0;
  651. }
  652. static void deactivate_replay_buffer(struct ffmpeg_muxer *stream, int code)
  653. {
  654. if (code) {
  655. obs_output_signal_stop(stream->output, code);
  656. } else if (stopping(stream)) {
  657. obs_output_end_data_capture(stream->output);
  658. }
  659. os_atomic_set_bool(&stream->active, false);
  660. os_atomic_set_bool(&stream->sent_headers, false);
  661. os_atomic_set_bool(&stream->stopping, false);
  662. replay_buffer_clear(stream);
  663. }
  664. static void replay_buffer_data(void *data, struct encoder_packet *packet)
  665. {
  666. struct ffmpeg_muxer *stream = data;
  667. struct encoder_packet pkt;
  668. if (!active(stream))
  669. return;
  670. /* encoder failure */
  671. if (!packet) {
  672. deactivate_replay_buffer(stream, OBS_OUTPUT_ENCODE_ERROR);
  673. return;
  674. }
  675. if (stopping(stream)) {
  676. if (packet->sys_dts_usec >= stream->stop_ts) {
  677. deactivate_replay_buffer(stream, 0);
  678. return;
  679. }
  680. }
  681. obs_encoder_packet_ref(&pkt, packet);
  682. replay_buffer_purge(stream, &pkt);
  683. if (!stream->packets.size)
  684. stream->cur_time = pkt.dts_usec;
  685. stream->cur_size += pkt.size;
  686. circlebuf_push_back(&stream->packets, packet, sizeof(*packet));
  687. if (packet->type == OBS_ENCODER_VIDEO && packet->keyframe)
  688. stream->keyframes++;
  689. if (stream->save_ts && packet->sys_dts_usec >= stream->save_ts) {
  690. if (os_atomic_load_bool(&stream->muxing))
  691. return;
  692. if (stream->mux_thread_joinable) {
  693. pthread_join(stream->mux_thread, NULL);
  694. stream->mux_thread_joinable = false;
  695. }
  696. stream->save_ts = 0;
  697. replay_buffer_save(stream);
  698. }
  699. }
  700. static void replay_buffer_defaults(obs_data_t *s)
  701. {
  702. obs_data_set_default_int(s, "max_time_sec", 15);
  703. obs_data_set_default_int(s, "max_size_mb", 500);
  704. obs_data_set_default_string(s, "format", "%CCYY-%MM-%DD %hh-%mm-%ss");
  705. obs_data_set_default_string(s, "extension", "mp4");
  706. obs_data_set_default_bool(s, "allow_spaces", true);
  707. }
  708. struct obs_output_info replay_buffer = {
  709. .id = "replay_buffer",
  710. .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK |
  711. OBS_OUTPUT_CAN_PAUSE,
  712. .get_name = replay_buffer_getname,
  713. .create = replay_buffer_create,
  714. .destroy = replay_buffer_destroy,
  715. .start = replay_buffer_start,
  716. .stop = ffmpeg_mux_stop,
  717. .encoded_packet = replay_buffer_data,
  718. .get_total_bytes = ffmpeg_mux_total_bytes,
  719. .get_defaults = replay_buffer_defaults,
  720. };