1
0

obs-ffmpeg-mux.c 22 KB

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