obs-ffmpeg-mux.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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. if (!stream->packets.size)
  591. return false;
  592. circlebuf_pop_front(&stream->packets, &pkt, sizeof(pkt));
  593. keyframe = pkt.type == OBS_ENCODER_VIDEO && pkt.keyframe;
  594. if (keyframe)
  595. stream->keyframes--;
  596. if (!stream->packets.size) {
  597. stream->cur_size = 0;
  598. stream->cur_time = 0;
  599. } else {
  600. struct encoder_packet first;
  601. circlebuf_peek_front(&stream->packets, &first, sizeof(first));
  602. stream->cur_time = first.dts_usec;
  603. stream->cur_size -= (int64_t)pkt.size;
  604. }
  605. obs_encoder_packet_release(&pkt);
  606. return keyframe;
  607. }
  608. static inline void purge(struct ffmpeg_muxer *stream)
  609. {
  610. if (purge_front(stream)) {
  611. struct encoder_packet pkt;
  612. for (;;) {
  613. if (!stream->packets.size)
  614. return;
  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. bool error = false;
  668. start_pipe(stream, stream->path.array);
  669. if (!stream->pipe) {
  670. warn("Failed to create process pipe");
  671. error = true;
  672. goto error;
  673. }
  674. if (!send_headers(stream)) {
  675. warn("Could not write headers for file '%s'",
  676. stream->path.array);
  677. error = true;
  678. goto error;
  679. }
  680. for (size_t i = 0; i < stream->mux_packets.num; i++) {
  681. struct encoder_packet *pkt = &stream->mux_packets.array[i];
  682. write_packet(stream, pkt);
  683. obs_encoder_packet_release(pkt);
  684. }
  685. info("Wrote replay buffer to '%s'", stream->path.array);
  686. error:
  687. os_process_pipe_destroy(stream->pipe);
  688. stream->pipe = NULL;
  689. da_free(stream->mux_packets);
  690. os_atomic_set_bool(&stream->muxing, false);
  691. if (!error) {
  692. calldata_t cd = {0};
  693. signal_handler_t *sh =
  694. obs_output_get_signal_handler(stream->output);
  695. signal_handler_signal(sh, "saved", &cd);
  696. }
  697. return NULL;
  698. }
  699. static void replay_buffer_save(struct ffmpeg_muxer *stream)
  700. {
  701. const size_t size = sizeof(struct encoder_packet);
  702. size_t num_packets = stream->packets.size / size;
  703. da_reserve(stream->mux_packets, num_packets);
  704. /* ---------------------------- */
  705. /* reorder packets */
  706. bool found_video = false;
  707. bool found_audio[MAX_AUDIO_MIXES] = {0};
  708. int64_t video_offset = 0;
  709. int64_t video_dts_offset = 0;
  710. int64_t audio_offsets[MAX_AUDIO_MIXES] = {0};
  711. int64_t audio_dts_offsets[MAX_AUDIO_MIXES] = {0};
  712. for (size_t i = 0; i < num_packets; i++) {
  713. struct encoder_packet *pkt;
  714. pkt = circlebuf_data(&stream->packets, i * size);
  715. if (pkt->type == OBS_ENCODER_VIDEO) {
  716. if (!found_video) {
  717. video_offset = pkt->dts_usec;
  718. video_dts_offset = pkt->dts;
  719. found_video = true;
  720. }
  721. } else {
  722. if (!found_audio[pkt->track_idx]) {
  723. found_audio[pkt->track_idx] = true;
  724. audio_offsets[pkt->track_idx] = pkt->dts_usec;
  725. audio_dts_offsets[pkt->track_idx] = pkt->dts;
  726. }
  727. }
  728. insert_packet(&stream->mux_packets.da, pkt, video_offset,
  729. audio_offsets, video_dts_offset,
  730. audio_dts_offsets);
  731. }
  732. /* ---------------------------- */
  733. /* generate filename */
  734. obs_data_t *settings = obs_output_get_settings(stream->output);
  735. const char *dir = obs_data_get_string(settings, "directory");
  736. const char *fmt = obs_data_get_string(settings, "format");
  737. const char *ext = obs_data_get_string(settings, "extension");
  738. bool space = obs_data_get_bool(settings, "allow_spaces");
  739. char *filename = os_generate_formatted_filename(ext, space, fmt);
  740. dstr_copy(&stream->path, dir);
  741. dstr_replace(&stream->path, "\\", "/");
  742. if (dstr_end(&stream->path) != '/')
  743. dstr_cat_ch(&stream->path, '/');
  744. dstr_cat(&stream->path, filename);
  745. char *slash = strrchr(stream->path.array, '/');
  746. if (slash) {
  747. *slash = 0;
  748. os_mkdirs(stream->path.array);
  749. *slash = '/';
  750. }
  751. bfree(filename);
  752. obs_data_release(settings);
  753. /* ---------------------------- */
  754. os_atomic_set_bool(&stream->muxing, true);
  755. stream->mux_thread_joinable = pthread_create(&stream->mux_thread, NULL,
  756. replay_buffer_mux_thread,
  757. stream) == 0;
  758. }
  759. static void deactivate_replay_buffer(struct ffmpeg_muxer *stream, int code)
  760. {
  761. if (code) {
  762. obs_output_signal_stop(stream->output, code);
  763. } else if (stopping(stream)) {
  764. obs_output_end_data_capture(stream->output);
  765. }
  766. os_atomic_set_bool(&stream->active, false);
  767. os_atomic_set_bool(&stream->sent_headers, false);
  768. os_atomic_set_bool(&stream->stopping, false);
  769. replay_buffer_clear(stream);
  770. }
  771. static void replay_buffer_data(void *data, struct encoder_packet *packet)
  772. {
  773. struct ffmpeg_muxer *stream = data;
  774. struct encoder_packet pkt;
  775. if (!active(stream))
  776. return;
  777. /* encoder failure */
  778. if (!packet) {
  779. deactivate_replay_buffer(stream, OBS_OUTPUT_ENCODE_ERROR);
  780. return;
  781. }
  782. if (stopping(stream)) {
  783. if (packet->sys_dts_usec >= stream->stop_ts) {
  784. deactivate_replay_buffer(stream, 0);
  785. return;
  786. }
  787. }
  788. obs_encoder_packet_ref(&pkt, packet);
  789. replay_buffer_purge(stream, &pkt);
  790. if (!stream->packets.size)
  791. stream->cur_time = pkt.dts_usec;
  792. stream->cur_size += pkt.size;
  793. circlebuf_push_back(&stream->packets, packet, sizeof(*packet));
  794. if (packet->type == OBS_ENCODER_VIDEO && packet->keyframe)
  795. stream->keyframes++;
  796. if (stream->save_ts && packet->sys_dts_usec >= stream->save_ts) {
  797. if (os_atomic_load_bool(&stream->muxing))
  798. return;
  799. if (stream->mux_thread_joinable) {
  800. pthread_join(stream->mux_thread, NULL);
  801. stream->mux_thread_joinable = false;
  802. }
  803. stream->save_ts = 0;
  804. replay_buffer_save(stream);
  805. }
  806. }
  807. static void replay_buffer_defaults(obs_data_t *s)
  808. {
  809. obs_data_set_default_int(s, "max_time_sec", 15);
  810. obs_data_set_default_int(s, "max_size_mb", 500);
  811. obs_data_set_default_string(s, "format", "%CCYY-%MM-%DD %hh-%mm-%ss");
  812. obs_data_set_default_string(s, "extension", "mp4");
  813. obs_data_set_default_bool(s, "allow_spaces", true);
  814. }
  815. struct obs_output_info replay_buffer = {
  816. .id = "replay_buffer",
  817. .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK |
  818. OBS_OUTPUT_CAN_PAUSE,
  819. .get_name = replay_buffer_getname,
  820. .create = replay_buffer_create,
  821. .destroy = replay_buffer_destroy,
  822. .start = replay_buffer_start,
  823. .stop = ffmpeg_mux_stop,
  824. .encoded_packet = replay_buffer_data,
  825. .get_total_bytes = ffmpeg_mux_total_bytes,
  826. .get_defaults = replay_buffer_defaults,
  827. };