obs-ffmpeg-mux.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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 *replay_buffer_create(obs_data_t *settings, obs_output_t *output)
  429. {
  430. UNUSED_PARAMETER(settings);
  431. struct ffmpeg_muxer *stream = bzalloc(sizeof(*stream));
  432. stream->output = output;
  433. stream->hotkey = obs_hotkey_register_output(output,
  434. "ReplayBuffer.Save",
  435. obs_module_text("ReplayBuffer.Save"),
  436. replay_buffer_hotkey, stream);
  437. proc_handler_t *ph = obs_output_get_proc_handler(output);
  438. proc_handler_add(ph, "void save()", save_replay_proc, stream);
  439. return stream;
  440. }
  441. static void replay_buffer_destroy(void *data)
  442. {
  443. struct ffmpeg_muxer *stream = data;
  444. if (stream->hotkey)
  445. obs_hotkey_unregister(stream->hotkey);
  446. ffmpeg_mux_destroy(data);
  447. }
  448. static bool replay_buffer_start(void *data)
  449. {
  450. struct ffmpeg_muxer *stream = data;
  451. if (!obs_output_can_begin_data_capture(stream->output, 0))
  452. return false;
  453. if (!obs_output_initialize_encoders(stream->output, 0))
  454. return false;
  455. obs_data_t *s = obs_output_get_settings(stream->output);
  456. stream->max_time = obs_data_get_int(s, "max_time_sec") * 1000000LL;
  457. stream->max_size = obs_data_get_int(s, "max_size_mb") * (1024 * 1024);
  458. obs_data_release(s);
  459. os_atomic_set_bool(&stream->active, true);
  460. os_atomic_set_bool(&stream->capturing, true);
  461. stream->total_bytes = 0;
  462. obs_output_begin_data_capture(stream->output, 0);
  463. return true;
  464. }
  465. static bool purge_front(struct ffmpeg_muxer *stream)
  466. {
  467. struct encoder_packet pkt;
  468. bool keyframe;
  469. circlebuf_pop_front(&stream->packets, &pkt, sizeof(pkt));
  470. keyframe = pkt.type == OBS_ENCODER_VIDEO && pkt.keyframe;
  471. if (keyframe)
  472. stream->keyframes--;
  473. if (!stream->packets.size) {
  474. stream->cur_size = 0;
  475. stream->cur_time = 0;
  476. } else {
  477. struct encoder_packet first;
  478. circlebuf_peek_front(&stream->packets, &first, sizeof(first));
  479. stream->cur_time = first.dts_usec;
  480. stream->cur_size -= (int64_t)pkt.size;
  481. }
  482. obs_encoder_packet_release(&pkt);
  483. return keyframe;
  484. }
  485. static inline void purge(struct ffmpeg_muxer *stream)
  486. {
  487. if (purge_front(stream)) {
  488. struct encoder_packet pkt;
  489. for (;;) {
  490. circlebuf_peek_front(&stream->packets, &pkt,
  491. sizeof(pkt));
  492. if (pkt.type == OBS_ENCODER_VIDEO && pkt.keyframe)
  493. return;
  494. purge_front(stream);
  495. }
  496. }
  497. }
  498. static inline void replay_buffer_purge(struct ffmpeg_muxer *stream,
  499. struct encoder_packet *pkt)
  500. {
  501. if (stream->max_size) {
  502. if (!stream->packets.size || stream->keyframes <= 2)
  503. return;
  504. while ((stream->cur_size + (int64_t)pkt->size) >
  505. stream->max_size)
  506. purge(stream);
  507. }
  508. if (!stream->packets.size || stream->keyframes <= 2)
  509. return;
  510. while ((pkt->dts_usec - stream->cur_time) > stream->max_time)
  511. purge(stream);
  512. }
  513. static void insert_packet(struct darray *array, struct encoder_packet *packet,
  514. int64_t video_offset, int64_t *audio_offsets,
  515. int64_t video_dts_offset, int64_t *audio_dts_offsets)
  516. {
  517. struct encoder_packet pkt;
  518. DARRAY(struct encoder_packet) packets;
  519. packets.da = *array;
  520. size_t idx;
  521. obs_encoder_packet_ref(&pkt, packet);
  522. if (pkt.type == OBS_ENCODER_VIDEO) {
  523. pkt.dts_usec -= video_offset;
  524. pkt.dts -= video_dts_offset;
  525. pkt.pts -= video_dts_offset;
  526. } else {
  527. pkt.dts_usec -= audio_offsets[pkt.track_idx];
  528. pkt.dts -= audio_dts_offsets[pkt.track_idx];
  529. pkt.pts -= audio_dts_offsets[pkt.track_idx];
  530. }
  531. for (idx = packets.num; idx > 0; idx--) {
  532. struct encoder_packet *p = packets.array + (idx - 1);
  533. if (p->dts_usec < pkt.dts_usec)
  534. break;
  535. }
  536. da_insert(packets, idx, &pkt);
  537. *array = packets.da;
  538. }
  539. static void *replay_buffer_mux_thread(void *data)
  540. {
  541. struct ffmpeg_muxer *stream = data;
  542. start_pipe(stream, stream->path.array);
  543. if (!stream->pipe) {
  544. warn("Failed to create process pipe");
  545. goto error;
  546. }
  547. if (!send_headers(stream)) {
  548. warn("Could not write headers for file '%s'",
  549. stream->path.array);
  550. goto error;
  551. }
  552. for (size_t i = 0; i < stream->mux_packets.num; i++) {
  553. struct encoder_packet *pkt = &stream->mux_packets.array[i];
  554. write_packet(stream, pkt);
  555. obs_encoder_packet_release(pkt);
  556. }
  557. info("Wrote replay buffer to '%s'", stream->path.array);
  558. error:
  559. os_process_pipe_destroy(stream->pipe);
  560. stream->pipe = NULL;
  561. da_free(stream->mux_packets);
  562. os_atomic_set_bool(&stream->muxing, false);
  563. return NULL;
  564. }
  565. static void replay_buffer_save(struct ffmpeg_muxer *stream)
  566. {
  567. const size_t size = sizeof(struct encoder_packet);
  568. size_t num_packets = stream->packets.size / size;
  569. da_reserve(stream->mux_packets, num_packets);
  570. /* ---------------------------- */
  571. /* reorder packets */
  572. bool found_video = false;
  573. bool found_audio[MAX_AUDIO_MIXES] = {0};
  574. int64_t video_offset = 0;
  575. int64_t video_dts_offset = 0;
  576. int64_t audio_offsets[MAX_AUDIO_MIXES] = {0};
  577. int64_t audio_dts_offsets[MAX_AUDIO_MIXES] = {0};
  578. for (size_t i = 0; i < num_packets; i++) {
  579. struct encoder_packet *pkt;
  580. pkt = circlebuf_data(&stream->packets, i * size);
  581. if (pkt->type == OBS_ENCODER_VIDEO) {
  582. if (!found_video) {
  583. video_offset = pkt->dts_usec;
  584. video_dts_offset = pkt->dts;
  585. found_video = true;
  586. }
  587. } else {
  588. if (!found_audio[pkt->track_idx]) {
  589. found_audio[pkt->track_idx] = true;
  590. audio_offsets[pkt->track_idx] = pkt->dts_usec;
  591. audio_dts_offsets[pkt->track_idx] = pkt->dts;
  592. }
  593. }
  594. insert_packet(&stream->mux_packets.da, pkt,
  595. video_offset, audio_offsets,
  596. video_dts_offset, audio_dts_offsets);
  597. }
  598. /* ---------------------------- */
  599. /* generate filename */
  600. obs_data_t *settings = obs_output_get_settings(stream->output);
  601. const char *dir = obs_data_get_string(settings, "directory");
  602. const char *fmt = obs_data_get_string(settings, "format");
  603. const char *ext = obs_data_get_string(settings, "extension");
  604. bool space = obs_data_get_bool(settings, "allow_spaces");
  605. char *filename = os_generate_formatted_filename(ext, space, fmt);
  606. dstr_copy(&stream->path, dir);
  607. dstr_replace(&stream->path, "\\", "/");
  608. if (dstr_end(&stream->path) != '/')
  609. dstr_cat_ch(&stream->path, '/');
  610. dstr_cat(&stream->path, filename);
  611. bfree(filename);
  612. obs_data_release(settings);
  613. /* ---------------------------- */
  614. os_atomic_set_bool(&stream->muxing, true);
  615. stream->mux_thread_joinable = pthread_create(&stream->mux_thread, NULL,
  616. replay_buffer_mux_thread, stream) == 0;
  617. }
  618. static void deactivate_replay_buffer(struct ffmpeg_muxer *stream)
  619. {
  620. if (stopping(stream))
  621. obs_output_end_data_capture(stream->output);
  622. os_atomic_set_bool(&stream->active, false);
  623. os_atomic_set_bool(&stream->sent_headers, false);
  624. os_atomic_set_bool(&stream->stopping, false);
  625. replay_buffer_clear(stream);
  626. }
  627. static void replay_buffer_data(void *data, struct encoder_packet *packet)
  628. {
  629. struct ffmpeg_muxer *stream = data;
  630. struct encoder_packet pkt;
  631. if (!active(stream))
  632. return;
  633. if (stopping(stream)) {
  634. if (packet->sys_dts_usec >= stream->stop_ts) {
  635. deactivate_replay_buffer(stream);
  636. return;
  637. }
  638. }
  639. obs_encoder_packet_ref(&pkt, packet);
  640. replay_buffer_purge(stream, &pkt);
  641. if (!stream->packets.size)
  642. stream->cur_time = pkt.dts_usec;
  643. stream->cur_size += pkt.size;
  644. circlebuf_push_back(&stream->packets, packet, sizeof(*packet));
  645. if (packet->type == OBS_ENCODER_VIDEO && packet->keyframe)
  646. stream->keyframes++;
  647. if (stream->save_ts && packet->sys_dts_usec >= stream->save_ts) {
  648. if (os_atomic_load_bool(&stream->muxing))
  649. return;
  650. if (stream->mux_thread_joinable) {
  651. pthread_join(stream->mux_thread, NULL);
  652. stream->mux_thread_joinable = false;
  653. }
  654. stream->save_ts = 0;
  655. replay_buffer_save(stream);
  656. }
  657. }
  658. static void replay_buffer_defaults(obs_data_t *s)
  659. {
  660. obs_data_set_default_int(s, "max_time_sec", 15);
  661. obs_data_set_default_int(s, "max_size_mb", 500);
  662. obs_data_set_default_string(s, "format", "%CCYY-%MM-%DD %hh-%mm-%ss");
  663. obs_data_set_default_string(s, "extension", "mp4");
  664. obs_data_set_default_bool(s, "allow_spaces", true);
  665. }
  666. struct obs_output_info replay_buffer = {
  667. .id = "replay_buffer",
  668. .flags = OBS_OUTPUT_AV |
  669. OBS_OUTPUT_ENCODED |
  670. OBS_OUTPUT_MULTI_TRACK,
  671. .get_name = replay_buffer_getname,
  672. .create = replay_buffer_create,
  673. .destroy = replay_buffer_destroy,
  674. .start = replay_buffer_start,
  675. .stop = ffmpeg_mux_stop,
  676. .encoded_packet = replay_buffer_data,
  677. .get_total_bytes= ffmpeg_mux_total_bytes,
  678. .get_defaults = replay_buffer_defaults
  679. };