obs-ffmpeg-mux.c 24 KB

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