obs-ffmpeg-mux.c 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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. calldata_t cd = {0};
  532. signal_handler_t *sh =
  533. obs_output_get_signal_handler(stream->output);
  534. signal_handler_signal(sh, "saved", &cd);
  535. stream->save_ts = os_gettime_ns() / 1000LL;
  536. }
  537. }
  538. static void save_replay_proc(void *data, calldata_t *cd)
  539. {
  540. replay_buffer_hotkey(data, 0, NULL, true);
  541. UNUSED_PARAMETER(cd);
  542. }
  543. static void get_last_replay(void *data, calldata_t *cd)
  544. {
  545. struct ffmpeg_muxer *stream = data;
  546. if (!os_atomic_load_bool(&stream->muxing))
  547. calldata_set_string(cd, "path", stream->path.array);
  548. }
  549. static void *replay_buffer_create(obs_data_t *settings, obs_output_t *output)
  550. {
  551. UNUSED_PARAMETER(settings);
  552. struct ffmpeg_muxer *stream = bzalloc(sizeof(*stream));
  553. stream->output = output;
  554. stream->hotkey =
  555. obs_hotkey_register_output(output, "ReplayBuffer.Save",
  556. obs_module_text("ReplayBuffer.Save"),
  557. replay_buffer_hotkey, stream);
  558. proc_handler_t *ph = obs_output_get_proc_handler(output);
  559. proc_handler_add(ph, "void save()", save_replay_proc, stream);
  560. proc_handler_add(ph, "void get_last_replay(out string path)",
  561. get_last_replay, stream);
  562. signal_handler_t *sh = obs_output_get_signal_handler(output);
  563. signal_handler_add(sh, "void saved()");
  564. return stream;
  565. }
  566. static void replay_buffer_destroy(void *data)
  567. {
  568. struct ffmpeg_muxer *stream = data;
  569. if (stream->hotkey)
  570. obs_hotkey_unregister(stream->hotkey);
  571. ffmpeg_mux_destroy(data);
  572. }
  573. static bool replay_buffer_start(void *data)
  574. {
  575. struct ffmpeg_muxer *stream = data;
  576. if (!obs_output_can_begin_data_capture(stream->output, 0))
  577. return false;
  578. if (!obs_output_initialize_encoders(stream->output, 0))
  579. return false;
  580. obs_data_t *s = obs_output_get_settings(stream->output);
  581. stream->max_time = obs_data_get_int(s, "max_time_sec") * 1000000LL;
  582. stream->max_size = obs_data_get_int(s, "max_size_mb") * (1024 * 1024);
  583. obs_data_release(s);
  584. os_atomic_set_bool(&stream->active, true);
  585. os_atomic_set_bool(&stream->capturing, true);
  586. stream->total_bytes = 0;
  587. obs_output_begin_data_capture(stream->output, 0);
  588. return true;
  589. }
  590. static bool purge_front(struct ffmpeg_muxer *stream)
  591. {
  592. struct encoder_packet pkt;
  593. bool keyframe;
  594. circlebuf_pop_front(&stream->packets, &pkt, sizeof(pkt));
  595. keyframe = pkt.type == OBS_ENCODER_VIDEO && pkt.keyframe;
  596. if (keyframe)
  597. stream->keyframes--;
  598. if (!stream->packets.size) {
  599. stream->cur_size = 0;
  600. stream->cur_time = 0;
  601. } else {
  602. struct encoder_packet first;
  603. circlebuf_peek_front(&stream->packets, &first, sizeof(first));
  604. stream->cur_time = first.dts_usec;
  605. stream->cur_size -= (int64_t)pkt.size;
  606. }
  607. obs_encoder_packet_release(&pkt);
  608. return keyframe;
  609. }
  610. static inline void purge(struct ffmpeg_muxer *stream)
  611. {
  612. if (purge_front(stream)) {
  613. struct encoder_packet pkt;
  614. for (;;) {
  615. circlebuf_peek_front(&stream->packets, &pkt,
  616. sizeof(pkt));
  617. if (pkt.type == OBS_ENCODER_VIDEO && pkt.keyframe)
  618. return;
  619. purge_front(stream);
  620. }
  621. }
  622. }
  623. static inline void replay_buffer_purge(struct ffmpeg_muxer *stream,
  624. struct encoder_packet *pkt)
  625. {
  626. if (stream->max_size) {
  627. if (!stream->packets.size || stream->keyframes <= 2)
  628. return;
  629. while ((stream->cur_size + (int64_t)pkt->size) >
  630. stream->max_size)
  631. purge(stream);
  632. }
  633. if (!stream->packets.size || stream->keyframes <= 2)
  634. return;
  635. while ((pkt->dts_usec - stream->cur_time) > stream->max_time)
  636. purge(stream);
  637. }
  638. static void insert_packet(struct darray *array, struct encoder_packet *packet,
  639. int64_t video_offset, int64_t *audio_offsets,
  640. int64_t video_dts_offset, int64_t *audio_dts_offsets)
  641. {
  642. struct encoder_packet pkt;
  643. DARRAY(struct encoder_packet) packets;
  644. packets.da = *array;
  645. size_t idx;
  646. obs_encoder_packet_ref(&pkt, packet);
  647. if (pkt.type == OBS_ENCODER_VIDEO) {
  648. pkt.dts_usec -= video_offset;
  649. pkt.dts -= video_dts_offset;
  650. pkt.pts -= video_dts_offset;
  651. } else {
  652. pkt.dts_usec -= audio_offsets[pkt.track_idx];
  653. pkt.dts -= audio_dts_offsets[pkt.track_idx];
  654. pkt.pts -= audio_dts_offsets[pkt.track_idx];
  655. }
  656. for (idx = packets.num; idx > 0; idx--) {
  657. struct encoder_packet *p = packets.array + (idx - 1);
  658. if (p->dts_usec < pkt.dts_usec)
  659. break;
  660. }
  661. da_insert(packets, idx, &pkt);
  662. *array = packets.da;
  663. }
  664. static void *replay_buffer_mux_thread(void *data)
  665. {
  666. struct ffmpeg_muxer *stream = data;
  667. start_pipe(stream, stream->path.array);
  668. if (!stream->pipe) {
  669. warn("Failed to create process pipe");
  670. goto error;
  671. }
  672. if (!send_headers(stream)) {
  673. warn("Could not write headers for file '%s'",
  674. stream->path.array);
  675. goto error;
  676. }
  677. for (size_t i = 0; i < stream->mux_packets.num; i++) {
  678. struct encoder_packet *pkt = &stream->mux_packets.array[i];
  679. write_packet(stream, pkt);
  680. obs_encoder_packet_release(pkt);
  681. }
  682. info("Wrote replay buffer to '%s'", stream->path.array);
  683. error:
  684. os_process_pipe_destroy(stream->pipe);
  685. stream->pipe = NULL;
  686. da_free(stream->mux_packets);
  687. os_atomic_set_bool(&stream->muxing, false);
  688. return NULL;
  689. }
  690. static void replay_buffer_save(struct ffmpeg_muxer *stream)
  691. {
  692. const size_t size = sizeof(struct encoder_packet);
  693. size_t num_packets = stream->packets.size / size;
  694. da_reserve(stream->mux_packets, num_packets);
  695. /* ---------------------------- */
  696. /* reorder packets */
  697. bool found_video = false;
  698. bool found_audio[MAX_AUDIO_MIXES] = {0};
  699. int64_t video_offset = 0;
  700. int64_t video_dts_offset = 0;
  701. int64_t audio_offsets[MAX_AUDIO_MIXES] = {0};
  702. int64_t audio_dts_offsets[MAX_AUDIO_MIXES] = {0};
  703. for (size_t i = 0; i < num_packets; i++) {
  704. struct encoder_packet *pkt;
  705. pkt = circlebuf_data(&stream->packets, i * size);
  706. if (pkt->type == OBS_ENCODER_VIDEO) {
  707. if (!found_video) {
  708. video_offset = pkt->dts_usec;
  709. video_dts_offset = pkt->dts;
  710. found_video = true;
  711. }
  712. } else {
  713. if (!found_audio[pkt->track_idx]) {
  714. found_audio[pkt->track_idx] = true;
  715. audio_offsets[pkt->track_idx] = pkt->dts_usec;
  716. audio_dts_offsets[pkt->track_idx] = pkt->dts;
  717. }
  718. }
  719. insert_packet(&stream->mux_packets.da, pkt, video_offset,
  720. audio_offsets, video_dts_offset,
  721. audio_dts_offsets);
  722. }
  723. /* ---------------------------- */
  724. /* generate filename */
  725. obs_data_t *settings = obs_output_get_settings(stream->output);
  726. const char *dir = obs_data_get_string(settings, "directory");
  727. const char *fmt = obs_data_get_string(settings, "format");
  728. const char *ext = obs_data_get_string(settings, "extension");
  729. bool space = obs_data_get_bool(settings, "allow_spaces");
  730. char *filename = os_generate_formatted_filename(ext, space, fmt);
  731. dstr_copy(&stream->path, dir);
  732. dstr_replace(&stream->path, "\\", "/");
  733. if (dstr_end(&stream->path) != '/')
  734. dstr_cat_ch(&stream->path, '/');
  735. dstr_cat(&stream->path, filename);
  736. char *slash = strrchr(stream->path.array, '/');
  737. if (slash) {
  738. *slash = 0;
  739. os_mkdirs(stream->path.array);
  740. *slash = '/';
  741. }
  742. bfree(filename);
  743. obs_data_release(settings);
  744. /* ---------------------------- */
  745. os_atomic_set_bool(&stream->muxing, true);
  746. stream->mux_thread_joinable = pthread_create(&stream->mux_thread, NULL,
  747. replay_buffer_mux_thread,
  748. stream) == 0;
  749. }
  750. static void deactivate_replay_buffer(struct ffmpeg_muxer *stream, int code)
  751. {
  752. if (code) {
  753. obs_output_signal_stop(stream->output, code);
  754. } else if (stopping(stream)) {
  755. obs_output_end_data_capture(stream->output);
  756. }
  757. os_atomic_set_bool(&stream->active, false);
  758. os_atomic_set_bool(&stream->sent_headers, false);
  759. os_atomic_set_bool(&stream->stopping, false);
  760. replay_buffer_clear(stream);
  761. }
  762. static void replay_buffer_data(void *data, struct encoder_packet *packet)
  763. {
  764. struct ffmpeg_muxer *stream = data;
  765. struct encoder_packet pkt;
  766. if (!active(stream))
  767. return;
  768. /* encoder failure */
  769. if (!packet) {
  770. deactivate_replay_buffer(stream, OBS_OUTPUT_ENCODE_ERROR);
  771. return;
  772. }
  773. if (stopping(stream)) {
  774. if (packet->sys_dts_usec >= stream->stop_ts) {
  775. deactivate_replay_buffer(stream, 0);
  776. return;
  777. }
  778. }
  779. obs_encoder_packet_ref(&pkt, packet);
  780. replay_buffer_purge(stream, &pkt);
  781. if (!stream->packets.size)
  782. stream->cur_time = pkt.dts_usec;
  783. stream->cur_size += pkt.size;
  784. circlebuf_push_back(&stream->packets, packet, sizeof(*packet));
  785. if (packet->type == OBS_ENCODER_VIDEO && packet->keyframe)
  786. stream->keyframes++;
  787. if (stream->save_ts && packet->sys_dts_usec >= stream->save_ts) {
  788. if (os_atomic_load_bool(&stream->muxing))
  789. return;
  790. if (stream->mux_thread_joinable) {
  791. pthread_join(stream->mux_thread, NULL);
  792. stream->mux_thread_joinable = false;
  793. }
  794. stream->save_ts = 0;
  795. replay_buffer_save(stream);
  796. }
  797. }
  798. static void replay_buffer_defaults(obs_data_t *s)
  799. {
  800. obs_data_set_default_int(s, "max_time_sec", 15);
  801. obs_data_set_default_int(s, "max_size_mb", 500);
  802. obs_data_set_default_string(s, "format", "%CCYY-%MM-%DD %hh-%mm-%ss");
  803. obs_data_set_default_string(s, "extension", "mp4");
  804. obs_data_set_default_bool(s, "allow_spaces", true);
  805. }
  806. struct obs_output_info replay_buffer = {
  807. .id = "replay_buffer",
  808. .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK |
  809. OBS_OUTPUT_CAN_PAUSE,
  810. .get_name = replay_buffer_getname,
  811. .create = replay_buffer_create,
  812. .destroy = replay_buffer_destroy,
  813. .start = replay_buffer_start,
  814. .stop = ffmpeg_mux_stop,
  815. .encoded_packet = replay_buffer_data,
  816. .get_total_bytes = ffmpeg_mux_total_bytes,
  817. .get_defaults = replay_buffer_defaults,
  818. };