obs-ffmpeg-mux.c 25 KB

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