obs-ffmpeg-mux.c 21 KB

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