obs-ffmpeg-mux.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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 void set_file_not_readable_error(struct ffmpeg_muxer *stream,
  211. obs_data_t *settings, const char *path)
  212. {
  213. struct dstr error_message;
  214. dstr_init_copy(&error_message, obs_module_text("UnableToWritePath"));
  215. #ifdef _WIN32
  216. /* special warning for Windows 10 users about Defender */
  217. struct win_version_info ver;
  218. get_win_ver(&ver);
  219. if (ver.major >= 10) {
  220. dstr_cat(&error_message, "\n\n");
  221. dstr_cat(&error_message,
  222. obs_module_text("WarnWindowsDefender"));
  223. }
  224. #endif
  225. dstr_replace(&error_message, "%1", path);
  226. obs_output_set_last_error(stream->output, error_message.array);
  227. dstr_free(&error_message);
  228. obs_data_release(settings);
  229. }
  230. static bool ffmpeg_mux_start(void *data)
  231. {
  232. struct ffmpeg_muxer *stream = data;
  233. obs_data_t *settings;
  234. const char *path;
  235. if (!obs_output_can_begin_data_capture(stream->output, 0))
  236. return false;
  237. if (!obs_output_initialize_encoders(stream->output, 0))
  238. return false;
  239. settings = obs_output_get_settings(stream->output);
  240. path = obs_data_get_string(settings, "path");
  241. /* ensure output path is writable to avoid generic error message */
  242. /* TODO: remove once ffmpeg-mux is refactored to pass errors back */
  243. FILE *test_file = os_fopen(path, "wb");
  244. if (!test_file) {
  245. set_file_not_readable_error(stream, settings, path);
  246. return false;
  247. }
  248. fclose(test_file);
  249. os_unlink(path);
  250. start_pipe(stream, path);
  251. obs_data_release(settings);
  252. if (!stream->pipe) {
  253. obs_output_set_last_error(
  254. stream->output, obs_module_text("HelperProcessFailed"));
  255. warn("Failed to create process pipe");
  256. return false;
  257. }
  258. /* write headers and start capture */
  259. os_atomic_set_bool(&stream->active, true);
  260. os_atomic_set_bool(&stream->capturing, true);
  261. stream->total_bytes = 0;
  262. obs_output_begin_data_capture(stream->output, 0);
  263. info("Writing file '%s'...", stream->path.array);
  264. return true;
  265. }
  266. static int deactivate(struct ffmpeg_muxer *stream, int code)
  267. {
  268. int ret = -1;
  269. if (active(stream)) {
  270. ret = os_process_pipe_destroy(stream->pipe);
  271. stream->pipe = NULL;
  272. os_atomic_set_bool(&stream->active, false);
  273. os_atomic_set_bool(&stream->sent_headers, false);
  274. info("Output of file '%s' stopped", stream->path.array);
  275. }
  276. if (code) {
  277. obs_output_signal_stop(stream->output, code);
  278. } else if (stopping(stream)) {
  279. obs_output_end_data_capture(stream->output);
  280. }
  281. os_atomic_set_bool(&stream->stopping, false);
  282. return ret;
  283. }
  284. static void ffmpeg_mux_stop(void *data, uint64_t ts)
  285. {
  286. struct ffmpeg_muxer *stream = data;
  287. if (capturing(stream) || ts == 0) {
  288. stream->stop_ts = (int64_t)ts / 1000LL;
  289. os_atomic_set_bool(&stream->stopping, true);
  290. os_atomic_set_bool(&stream->capturing, false);
  291. }
  292. }
  293. static void signal_failure(struct ffmpeg_muxer *stream)
  294. {
  295. char error[1024];
  296. int ret;
  297. int code;
  298. size_t len;
  299. len = os_process_pipe_read_err(stream->pipe, (uint8_t *)error,
  300. sizeof(error) - 1);
  301. if (len > 0) {
  302. error[len] = 0;
  303. warn("ffmpeg-mux: %s", error);
  304. obs_output_set_last_error(stream->output, error);
  305. }
  306. ret = deactivate(stream, 0);
  307. switch (ret) {
  308. case FFM_UNSUPPORTED:
  309. code = OBS_OUTPUT_UNSUPPORTED;
  310. break;
  311. default:
  312. code = OBS_OUTPUT_ERROR;
  313. }
  314. obs_output_signal_stop(stream->output, code);
  315. os_atomic_set_bool(&stream->capturing, false);
  316. }
  317. static bool write_packet(struct ffmpeg_muxer *stream,
  318. struct encoder_packet *packet)
  319. {
  320. bool is_video = packet->type == OBS_ENCODER_VIDEO;
  321. size_t ret;
  322. struct ffm_packet_info info = {.pts = packet->pts,
  323. .dts = packet->dts,
  324. .size = (uint32_t)packet->size,
  325. .index = (int)packet->track_idx,
  326. .type = is_video ? FFM_PACKET_VIDEO
  327. : FFM_PACKET_AUDIO,
  328. .keyframe = packet->keyframe};
  329. ret = os_process_pipe_write(stream->pipe, (const uint8_t *)&info,
  330. sizeof(info));
  331. if (ret != sizeof(info)) {
  332. warn("os_process_pipe_write for info structure failed");
  333. signal_failure(stream);
  334. return false;
  335. }
  336. ret = os_process_pipe_write(stream->pipe, packet->data, packet->size);
  337. if (ret != packet->size) {
  338. warn("os_process_pipe_write for packet data failed");
  339. signal_failure(stream);
  340. return false;
  341. }
  342. stream->total_bytes += packet->size;
  343. return true;
  344. }
  345. static bool send_audio_headers(struct ffmpeg_muxer *stream,
  346. obs_encoder_t *aencoder, size_t idx)
  347. {
  348. struct encoder_packet packet = {
  349. .type = OBS_ENCODER_AUDIO, .timebase_den = 1, .track_idx = idx};
  350. obs_encoder_get_extra_data(aencoder, &packet.data, &packet.size);
  351. return write_packet(stream, &packet);
  352. }
  353. static bool send_video_headers(struct ffmpeg_muxer *stream)
  354. {
  355. obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output);
  356. struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO,
  357. .timebase_den = 1};
  358. obs_encoder_get_extra_data(vencoder, &packet.data, &packet.size);
  359. return write_packet(stream, &packet);
  360. }
  361. static bool send_headers(struct ffmpeg_muxer *stream)
  362. {
  363. obs_encoder_t *aencoder;
  364. size_t idx = 0;
  365. if (!send_video_headers(stream))
  366. return false;
  367. do {
  368. aencoder = obs_output_get_audio_encoder(stream->output, idx);
  369. if (aencoder) {
  370. if (!send_audio_headers(stream, aencoder, idx)) {
  371. return false;
  372. }
  373. idx++;
  374. }
  375. } while (aencoder);
  376. return true;
  377. }
  378. static void ffmpeg_mux_data(void *data, struct encoder_packet *packet)
  379. {
  380. struct ffmpeg_muxer *stream = data;
  381. if (!active(stream))
  382. return;
  383. /* encoder failure */
  384. if (!packet) {
  385. deactivate(stream, OBS_OUTPUT_ENCODE_ERROR);
  386. return;
  387. }
  388. if (!stream->sent_headers) {
  389. if (!send_headers(stream))
  390. return;
  391. stream->sent_headers = true;
  392. }
  393. if (stopping(stream)) {
  394. if (packet->sys_dts_usec >= stream->stop_ts) {
  395. deactivate(stream, 0);
  396. return;
  397. }
  398. }
  399. write_packet(stream, packet);
  400. }
  401. static obs_properties_t *ffmpeg_mux_properties(void *unused)
  402. {
  403. UNUSED_PARAMETER(unused);
  404. obs_properties_t *props = obs_properties_create();
  405. obs_properties_add_text(props, "path", obs_module_text("FilePath"),
  406. OBS_TEXT_DEFAULT);
  407. return props;
  408. }
  409. static uint64_t ffmpeg_mux_total_bytes(void *data)
  410. {
  411. struct ffmpeg_muxer *stream = data;
  412. return stream->total_bytes;
  413. }
  414. struct obs_output_info ffmpeg_muxer = {
  415. .id = "ffmpeg_muxer",
  416. .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK |
  417. OBS_OUTPUT_CAN_PAUSE,
  418. .get_name = ffmpeg_mux_getname,
  419. .create = ffmpeg_mux_create,
  420. .destroy = ffmpeg_mux_destroy,
  421. .start = ffmpeg_mux_start,
  422. .stop = ffmpeg_mux_stop,
  423. .encoded_packet = ffmpeg_mux_data,
  424. .get_total_bytes = ffmpeg_mux_total_bytes,
  425. .get_properties = ffmpeg_mux_properties,
  426. };
  427. /* ------------------------------------------------------------------------ */
  428. static const char *replay_buffer_getname(void *type)
  429. {
  430. UNUSED_PARAMETER(type);
  431. return obs_module_text("ReplayBuffer");
  432. }
  433. static void replay_buffer_hotkey(void *data, obs_hotkey_id id,
  434. obs_hotkey_t *hotkey, bool pressed)
  435. {
  436. UNUSED_PARAMETER(id);
  437. UNUSED_PARAMETER(hotkey);
  438. UNUSED_PARAMETER(pressed);
  439. if (!pressed)
  440. return;
  441. struct ffmpeg_muxer *stream = data;
  442. if (os_atomic_load_bool(&stream->active)) {
  443. obs_encoder_t *vencoder =
  444. obs_output_get_video_encoder(stream->output);
  445. if (obs_encoder_paused(vencoder)) {
  446. info("Could not save buffer because encoders paused");
  447. return;
  448. }
  449. stream->save_ts = os_gettime_ns() / 1000LL;
  450. }
  451. }
  452. static void save_replay_proc(void *data, calldata_t *cd)
  453. {
  454. replay_buffer_hotkey(data, 0, NULL, true);
  455. UNUSED_PARAMETER(cd);
  456. }
  457. static void get_last_replay(void *data, calldata_t *cd)
  458. {
  459. struct ffmpeg_muxer *stream = data;
  460. if (!os_atomic_load_bool(&stream->muxing))
  461. calldata_set_string(cd, "path", stream->path.array);
  462. }
  463. static void *replay_buffer_create(obs_data_t *settings, obs_output_t *output)
  464. {
  465. UNUSED_PARAMETER(settings);
  466. struct ffmpeg_muxer *stream = bzalloc(sizeof(*stream));
  467. stream->output = output;
  468. stream->hotkey =
  469. obs_hotkey_register_output(output, "ReplayBuffer.Save",
  470. obs_module_text("ReplayBuffer.Save"),
  471. replay_buffer_hotkey, stream);
  472. proc_handler_t *ph = obs_output_get_proc_handler(output);
  473. proc_handler_add(ph, "void save()", save_replay_proc, stream);
  474. proc_handler_add(ph, "void get_last_replay(out string path)",
  475. get_last_replay, stream);
  476. return stream;
  477. }
  478. static void replay_buffer_destroy(void *data)
  479. {
  480. struct ffmpeg_muxer *stream = data;
  481. if (stream->hotkey)
  482. obs_hotkey_unregister(stream->hotkey);
  483. ffmpeg_mux_destroy(data);
  484. }
  485. static bool replay_buffer_start(void *data)
  486. {
  487. struct ffmpeg_muxer *stream = data;
  488. if (!obs_output_can_begin_data_capture(stream->output, 0))
  489. return false;
  490. if (!obs_output_initialize_encoders(stream->output, 0))
  491. return false;
  492. obs_data_t *s = obs_output_get_settings(stream->output);
  493. stream->max_time = obs_data_get_int(s, "max_time_sec") * 1000000LL;
  494. stream->max_size = obs_data_get_int(s, "max_size_mb") * (1024 * 1024);
  495. obs_data_release(s);
  496. os_atomic_set_bool(&stream->active, true);
  497. os_atomic_set_bool(&stream->capturing, true);
  498. stream->total_bytes = 0;
  499. obs_output_begin_data_capture(stream->output, 0);
  500. return true;
  501. }
  502. static bool purge_front(struct ffmpeg_muxer *stream)
  503. {
  504. struct encoder_packet pkt;
  505. bool keyframe;
  506. circlebuf_pop_front(&stream->packets, &pkt, sizeof(pkt));
  507. keyframe = pkt.type == OBS_ENCODER_VIDEO && pkt.keyframe;
  508. if (keyframe)
  509. stream->keyframes--;
  510. if (!stream->packets.size) {
  511. stream->cur_size = 0;
  512. stream->cur_time = 0;
  513. } else {
  514. struct encoder_packet first;
  515. circlebuf_peek_front(&stream->packets, &first, sizeof(first));
  516. stream->cur_time = first.dts_usec;
  517. stream->cur_size -= (int64_t)pkt.size;
  518. }
  519. obs_encoder_packet_release(&pkt);
  520. return keyframe;
  521. }
  522. static inline void purge(struct ffmpeg_muxer *stream)
  523. {
  524. if (purge_front(stream)) {
  525. struct encoder_packet pkt;
  526. for (;;) {
  527. circlebuf_peek_front(&stream->packets, &pkt,
  528. sizeof(pkt));
  529. if (pkt.type == OBS_ENCODER_VIDEO && pkt.keyframe)
  530. return;
  531. purge_front(stream);
  532. }
  533. }
  534. }
  535. static inline void replay_buffer_purge(struct ffmpeg_muxer *stream,
  536. struct encoder_packet *pkt)
  537. {
  538. if (stream->max_size) {
  539. if (!stream->packets.size || stream->keyframes <= 2)
  540. return;
  541. while ((stream->cur_size + (int64_t)pkt->size) >
  542. stream->max_size)
  543. purge(stream);
  544. }
  545. if (!stream->packets.size || stream->keyframes <= 2)
  546. return;
  547. while ((pkt->dts_usec - stream->cur_time) > stream->max_time)
  548. purge(stream);
  549. }
  550. static void insert_packet(struct darray *array, struct encoder_packet *packet,
  551. int64_t video_offset, int64_t *audio_offsets,
  552. int64_t video_dts_offset, int64_t *audio_dts_offsets)
  553. {
  554. struct encoder_packet pkt;
  555. DARRAY(struct encoder_packet) packets;
  556. packets.da = *array;
  557. size_t idx;
  558. obs_encoder_packet_ref(&pkt, packet);
  559. if (pkt.type == OBS_ENCODER_VIDEO) {
  560. pkt.dts_usec -= video_offset;
  561. pkt.dts -= video_dts_offset;
  562. pkt.pts -= video_dts_offset;
  563. } else {
  564. pkt.dts_usec -= audio_offsets[pkt.track_idx];
  565. pkt.dts -= audio_dts_offsets[pkt.track_idx];
  566. pkt.pts -= audio_dts_offsets[pkt.track_idx];
  567. }
  568. for (idx = packets.num; idx > 0; idx--) {
  569. struct encoder_packet *p = packets.array + (idx - 1);
  570. if (p->dts_usec < pkt.dts_usec)
  571. break;
  572. }
  573. da_insert(packets, idx, &pkt);
  574. *array = packets.da;
  575. }
  576. static void *replay_buffer_mux_thread(void *data)
  577. {
  578. struct ffmpeg_muxer *stream = data;
  579. start_pipe(stream, stream->path.array);
  580. if (!stream->pipe) {
  581. warn("Failed to create process pipe");
  582. goto error;
  583. }
  584. if (!send_headers(stream)) {
  585. warn("Could not write headers for file '%s'",
  586. stream->path.array);
  587. goto error;
  588. }
  589. for (size_t i = 0; i < stream->mux_packets.num; i++) {
  590. struct encoder_packet *pkt = &stream->mux_packets.array[i];
  591. write_packet(stream, pkt);
  592. obs_encoder_packet_release(pkt);
  593. }
  594. info("Wrote replay buffer to '%s'", stream->path.array);
  595. error:
  596. os_process_pipe_destroy(stream->pipe);
  597. stream->pipe = NULL;
  598. da_free(stream->mux_packets);
  599. os_atomic_set_bool(&stream->muxing, false);
  600. return NULL;
  601. }
  602. static void replay_buffer_save(struct ffmpeg_muxer *stream)
  603. {
  604. const size_t size = sizeof(struct encoder_packet);
  605. size_t num_packets = stream->packets.size / size;
  606. da_reserve(stream->mux_packets, num_packets);
  607. /* ---------------------------- */
  608. /* reorder packets */
  609. bool found_video = false;
  610. bool found_audio[MAX_AUDIO_MIXES] = {0};
  611. int64_t video_offset = 0;
  612. int64_t video_dts_offset = 0;
  613. int64_t audio_offsets[MAX_AUDIO_MIXES] = {0};
  614. int64_t audio_dts_offsets[MAX_AUDIO_MIXES] = {0};
  615. for (size_t i = 0; i < num_packets; i++) {
  616. struct encoder_packet *pkt;
  617. pkt = circlebuf_data(&stream->packets, i * size);
  618. if (pkt->type == OBS_ENCODER_VIDEO) {
  619. if (!found_video) {
  620. video_offset = pkt->dts_usec;
  621. video_dts_offset = pkt->dts;
  622. found_video = true;
  623. }
  624. } else {
  625. if (!found_audio[pkt->track_idx]) {
  626. found_audio[pkt->track_idx] = true;
  627. audio_offsets[pkt->track_idx] = pkt->dts_usec;
  628. audio_dts_offsets[pkt->track_idx] = pkt->dts;
  629. }
  630. }
  631. insert_packet(&stream->mux_packets.da, pkt, video_offset,
  632. audio_offsets, video_dts_offset,
  633. audio_dts_offsets);
  634. }
  635. /* ---------------------------- */
  636. /* generate filename */
  637. obs_data_t *settings = obs_output_get_settings(stream->output);
  638. const char *dir = obs_data_get_string(settings, "directory");
  639. const char *fmt = obs_data_get_string(settings, "format");
  640. const char *ext = obs_data_get_string(settings, "extension");
  641. bool space = obs_data_get_bool(settings, "allow_spaces");
  642. char *filename = os_generate_formatted_filename(ext, space, fmt);
  643. dstr_copy(&stream->path, dir);
  644. dstr_replace(&stream->path, "\\", "/");
  645. if (dstr_end(&stream->path) != '/')
  646. dstr_cat_ch(&stream->path, '/');
  647. dstr_cat(&stream->path, filename);
  648. bfree(filename);
  649. obs_data_release(settings);
  650. /* ---------------------------- */
  651. os_atomic_set_bool(&stream->muxing, true);
  652. stream->mux_thread_joinable = pthread_create(&stream->mux_thread, NULL,
  653. replay_buffer_mux_thread,
  654. stream) == 0;
  655. }
  656. static void deactivate_replay_buffer(struct ffmpeg_muxer *stream, int code)
  657. {
  658. if (code) {
  659. obs_output_signal_stop(stream->output, code);
  660. } else if (stopping(stream)) {
  661. obs_output_end_data_capture(stream->output);
  662. }
  663. os_atomic_set_bool(&stream->active, false);
  664. os_atomic_set_bool(&stream->sent_headers, false);
  665. os_atomic_set_bool(&stream->stopping, false);
  666. replay_buffer_clear(stream);
  667. }
  668. static void replay_buffer_data(void *data, struct encoder_packet *packet)
  669. {
  670. struct ffmpeg_muxer *stream = data;
  671. struct encoder_packet pkt;
  672. if (!active(stream))
  673. return;
  674. /* encoder failure */
  675. if (!packet) {
  676. deactivate_replay_buffer(stream, OBS_OUTPUT_ENCODE_ERROR);
  677. return;
  678. }
  679. if (stopping(stream)) {
  680. if (packet->sys_dts_usec >= stream->stop_ts) {
  681. deactivate_replay_buffer(stream, 0);
  682. return;
  683. }
  684. }
  685. obs_encoder_packet_ref(&pkt, packet);
  686. replay_buffer_purge(stream, &pkt);
  687. if (!stream->packets.size)
  688. stream->cur_time = pkt.dts_usec;
  689. stream->cur_size += pkt.size;
  690. circlebuf_push_back(&stream->packets, packet, sizeof(*packet));
  691. if (packet->type == OBS_ENCODER_VIDEO && packet->keyframe)
  692. stream->keyframes++;
  693. if (stream->save_ts && packet->sys_dts_usec >= stream->save_ts) {
  694. if (os_atomic_load_bool(&stream->muxing))
  695. return;
  696. if (stream->mux_thread_joinable) {
  697. pthread_join(stream->mux_thread, NULL);
  698. stream->mux_thread_joinable = false;
  699. }
  700. stream->save_ts = 0;
  701. replay_buffer_save(stream);
  702. }
  703. }
  704. static void replay_buffer_defaults(obs_data_t *s)
  705. {
  706. obs_data_set_default_int(s, "max_time_sec", 15);
  707. obs_data_set_default_int(s, "max_size_mb", 500);
  708. obs_data_set_default_string(s, "format", "%CCYY-%MM-%DD %hh-%mm-%ss");
  709. obs_data_set_default_string(s, "extension", "mp4");
  710. obs_data_set_default_bool(s, "allow_spaces", true);
  711. }
  712. struct obs_output_info replay_buffer = {
  713. .id = "replay_buffer",
  714. .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK |
  715. OBS_OUTPUT_CAN_PAUSE,
  716. .get_name = replay_buffer_getname,
  717. .create = replay_buffer_create,
  718. .destroy = replay_buffer_destroy,
  719. .start = replay_buffer_start,
  720. .stop = ffmpeg_mux_stop,
  721. .encoded_packet = replay_buffer_data,
  722. .get_total_bytes = ffmpeg_mux_total_bytes,
  723. .get_defaults = replay_buffer_defaults,
  724. };