mp4-output.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. /******************************************************************************
  2. Copyright (C) 2024 by Dennis Sädtler <[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 "mp4-mux.h"
  15. #include <inttypes.h>
  16. #include <obs-module.h>
  17. #include <util/platform.h>
  18. #include <util/dstr.h>
  19. #include <util/threading.h>
  20. #include <util/buffered-file-serializer.h>
  21. #include <opts-parser.h>
  22. #define do_log(level, format, ...) \
  23. blog(level, "[mp4 output: '%s'] " format, obs_output_get_name(out->output), ##__VA_ARGS__)
  24. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  25. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  26. struct chapter {
  27. int64_t dts_usec;
  28. char *name;
  29. };
  30. struct mp4_output {
  31. obs_output_t *output;
  32. struct dstr path;
  33. /* File serializer buffer configuration */
  34. size_t buffer_size;
  35. size_t chunk_size;
  36. struct serializer serializer;
  37. volatile bool active;
  38. volatile bool stopping;
  39. uint64_t stop_ts;
  40. bool allow_overwrite;
  41. uint64_t total_bytes;
  42. pthread_mutex_t mutex;
  43. struct mp4_mux *muxer;
  44. int flags;
  45. int64_t last_dts_usec;
  46. DARRAY(struct chapter) chapters;
  47. /* File splitting stuff */
  48. bool split_file_enabled;
  49. bool split_file_ready;
  50. volatile bool manual_split;
  51. size_t cur_size;
  52. size_t max_size;
  53. int64_t start_time;
  54. int64_t max_time;
  55. bool found_video[MAX_OUTPUT_VIDEO_ENCODERS];
  56. bool found_audio[MAX_OUTPUT_AUDIO_ENCODERS];
  57. int64_t video_pts_offsets[MAX_OUTPUT_VIDEO_ENCODERS];
  58. int64_t audio_dts_offsets[MAX_OUTPUT_AUDIO_ENCODERS];
  59. /* Buffer for packets while we reinitialise the muxer after splitting */
  60. DARRAY(struct encoder_packet) split_buffer;
  61. };
  62. static inline bool stopping(struct mp4_output *out)
  63. {
  64. return os_atomic_load_bool(&out->stopping);
  65. }
  66. static inline bool active(struct mp4_output *out)
  67. {
  68. return os_atomic_load_bool(&out->active);
  69. }
  70. static inline int64_t packet_pts_usec(struct encoder_packet *packet)
  71. {
  72. return packet->pts * 1000000 / packet->timebase_den;
  73. }
  74. static inline void ts_offset_clear(struct mp4_output *out)
  75. {
  76. for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) {
  77. out->found_video[i] = false;
  78. out->video_pts_offsets[i] = 0;
  79. }
  80. for (size_t i = 0; i < MAX_OUTPUT_AUDIO_ENCODERS; i++) {
  81. out->found_audio[i] = false;
  82. out->audio_dts_offsets[i] = 0;
  83. }
  84. }
  85. static inline void ts_offset_update(struct mp4_output *out, struct encoder_packet *packet)
  86. {
  87. int64_t *offset;
  88. int64_t ts;
  89. bool *found;
  90. if (packet->type == OBS_ENCODER_VIDEO) {
  91. offset = &out->video_pts_offsets[packet->track_idx];
  92. found = &out->found_video[packet->track_idx];
  93. ts = packet->pts;
  94. } else {
  95. offset = &out->audio_dts_offsets[packet->track_idx];
  96. found = &out->found_audio[packet->track_idx];
  97. ts = packet->dts;
  98. }
  99. if (*found)
  100. return;
  101. *offset = ts;
  102. *found = true;
  103. }
  104. static const char *mp4_output_name(void *unused)
  105. {
  106. UNUSED_PARAMETER(unused);
  107. return obs_module_text("MP4Output");
  108. }
  109. static void mp4_output_destroy(void *data)
  110. {
  111. struct mp4_output *out = data;
  112. for (size_t i = 0; i < out->chapters.num; i++)
  113. bfree(out->chapters.array[i].name);
  114. da_free(out->chapters);
  115. pthread_mutex_destroy(&out->mutex);
  116. dstr_free(&out->path);
  117. bfree(out);
  118. }
  119. static void mp4_add_chapter_proc(void *data, calldata_t *cd)
  120. {
  121. struct mp4_output *out = data;
  122. struct dstr name = {0};
  123. dstr_copy(&name, calldata_string(cd, "chapter_name"));
  124. if (name.len == 0) {
  125. /* Generate name if none provided. */
  126. dstr_catf(&name, "%s %zu", obs_module_text("MP4Output.UnnamedChapter"), out->chapters.num + 1);
  127. }
  128. int64_t totalRecordSeconds = out->last_dts_usec / 1000 / 1000;
  129. int seconds = (int)totalRecordSeconds % 60;
  130. int totalMinutes = (int)totalRecordSeconds / 60;
  131. int minutes = totalMinutes % 60;
  132. int hours = totalMinutes / 60;
  133. info("Adding chapter \"%s\" at %02d:%02d:%02d", name.array, hours, minutes, seconds);
  134. pthread_mutex_lock(&out->mutex);
  135. struct chapter *chap = da_push_back_new(out->chapters);
  136. chap->dts_usec = out->last_dts_usec;
  137. chap->name = name.array;
  138. pthread_mutex_unlock(&out->mutex);
  139. }
  140. static void split_file_proc(void *data, calldata_t *cd)
  141. {
  142. struct mp4_output *out = data;
  143. calldata_set_bool(cd, "split_file_enabled", out->split_file_enabled);
  144. if (!out->split_file_enabled)
  145. return;
  146. os_atomic_set_bool(&out->manual_split, true);
  147. }
  148. static void *mp4_output_create(obs_data_t *settings, obs_output_t *output)
  149. {
  150. struct mp4_output *out = bzalloc(sizeof(struct mp4_output));
  151. out->output = output;
  152. pthread_mutex_init(&out->mutex, NULL);
  153. signal_handler_t *sh = obs_output_get_signal_handler(output);
  154. signal_handler_add(sh, "void file_changed(string next_file)");
  155. proc_handler_t *ph = obs_output_get_proc_handler(output);
  156. proc_handler_add(ph, "void split_file(out bool split_file_enabled)", split_file_proc, out);
  157. proc_handler_add(ph, "void add_chapter(string chapter_name)", mp4_add_chapter_proc, out);
  158. UNUSED_PARAMETER(settings);
  159. return out;
  160. }
  161. static inline void apply_flag(int *flags, const char *value, int flag_value)
  162. {
  163. if (atoi(value))
  164. *flags |= flag_value;
  165. else
  166. *flags &= ~flag_value;
  167. }
  168. static void parse_custom_options(struct mp4_output *out, const char *opts_str)
  169. {
  170. int flags = MP4_USE_NEGATIVE_CTS;
  171. struct obs_options opts = obs_parse_options(opts_str);
  172. for (size_t i = 0; i < opts.count; i++) {
  173. struct obs_option opt = opts.options[i];
  174. if (strcmp(opt.name, "skip_soft_remux") == 0) {
  175. apply_flag(&flags, opt.value, MP4_SKIP_FINALISATION);
  176. } else if (strcmp(opt.name, "write_encoder_info") == 0) {
  177. apply_flag(&flags, opt.value, MP4_WRITE_ENCODER_INFO);
  178. } else if (strcmp(opt.name, "use_metadata_tags") == 0) {
  179. apply_flag(&flags, opt.value, MP4_USE_MDTA_KEY_VALUE);
  180. } else if (strcmp(opt.name, "use_negative_cts") == 0) {
  181. apply_flag(&flags, opt.value, MP4_USE_NEGATIVE_CTS);
  182. } else if (strcmp(opt.name, "buffer_size") == 0) {
  183. out->buffer_size = strtoull(opt.value, 0, 10) * 1048576ULL;
  184. } else if (strcmp(opt.name, "chunk_size") == 0) {
  185. out->chunk_size = strtoull(opt.value, 0, 10) * 1048576ULL;
  186. } else {
  187. blog(LOG_WARNING, "Unknown muxer option: %s = %s", opt.name, opt.value);
  188. }
  189. }
  190. obs_free_options(opts);
  191. out->flags = flags;
  192. }
  193. static void generate_filename(struct mp4_output *out, struct dstr *dst, bool overwrite);
  194. static bool mp4_output_start(void *data)
  195. {
  196. struct mp4_output *out = data;
  197. if (!obs_output_can_begin_data_capture(out->output, 0))
  198. return false;
  199. if (!obs_output_initialize_encoders(out->output, 0))
  200. return false;
  201. os_atomic_set_bool(&out->stopping, false);
  202. obs_data_t *settings = obs_output_get_settings(out->output);
  203. out->max_time = obs_data_get_int(settings, "max_time_sec") * 1000000LL;
  204. out->max_size = obs_data_get_int(settings, "max_size_mb") * 1024 * 1024;
  205. out->split_file_enabled = obs_data_get_bool(settings, "split_file");
  206. out->allow_overwrite = obs_data_get_bool(settings, "allow_overwrite");
  207. out->cur_size = 0;
  208. /* Get path */
  209. const char *path = obs_data_get_string(settings, "path");
  210. if (path && *path) {
  211. dstr_copy(&out->path, path);
  212. } else {
  213. generate_filename(out, &out->path, out->allow_overwrite);
  214. info("Output path not specified. Using generated path '%s'", out->path.array);
  215. }
  216. /* Allow skipping the remux step for debugging purposes. */
  217. const char *muxer_settings = obs_data_get_string(settings, "muxer_settings");
  218. parse_custom_options(out, muxer_settings);
  219. obs_data_release(settings);
  220. if (!buffered_file_serializer_init(&out->serializer, out->path.array, out->buffer_size, out->chunk_size)) {
  221. warn("Unable to open MP4 file '%s'", out->path.array);
  222. return false;
  223. }
  224. /* Initialise muxer and start capture */
  225. out->muxer = mp4_mux_create(out->output, &out->serializer, out->flags);
  226. os_atomic_set_bool(&out->active, true);
  227. obs_output_begin_data_capture(out->output, 0);
  228. info("Writing Hybrid MP4 file '%s'...", out->path.array);
  229. return true;
  230. }
  231. static inline bool should_split(struct mp4_output *out, struct encoder_packet *packet)
  232. {
  233. /* split at video frame on primary track */
  234. if (packet->type != OBS_ENCODER_VIDEO || packet->track_idx > 0)
  235. return false;
  236. /* don't split group of pictures */
  237. if (!packet->keyframe)
  238. return false;
  239. if (os_atomic_load_bool(&out->manual_split))
  240. return true;
  241. /* reached maximum file size */
  242. if (out->max_size > 0 && out->cur_size + (int64_t)packet->size >= out->max_size)
  243. return true;
  244. /* reached maximum duration */
  245. if (out->max_time > 0 && packet->dts_usec - out->start_time >= out->max_time)
  246. return true;
  247. return false;
  248. }
  249. static void find_best_filename(struct dstr *path, bool space)
  250. {
  251. int num = 2;
  252. if (!os_file_exists(path->array))
  253. return;
  254. const char *ext = strrchr(path->array, '.');
  255. if (!ext)
  256. return;
  257. size_t extstart = ext - path->array;
  258. struct dstr testpath;
  259. dstr_init_copy_dstr(&testpath, path);
  260. for (;;) {
  261. dstr_resize(&testpath, extstart);
  262. dstr_catf(&testpath, space ? " (%d)" : "_%d", num++);
  263. dstr_cat(&testpath, ext);
  264. if (!os_file_exists(testpath.array)) {
  265. dstr_free(path);
  266. dstr_init_move(path, &testpath);
  267. break;
  268. }
  269. }
  270. }
  271. static void generate_filename(struct mp4_output *out, struct dstr *dst, bool overwrite)
  272. {
  273. obs_data_t *settings = obs_output_get_settings(out->output);
  274. const char *dir = obs_data_get_string(settings, "directory");
  275. const char *fmt = obs_data_get_string(settings, "format");
  276. const char *ext = obs_data_get_string(settings, "extension");
  277. bool space = obs_data_get_bool(settings, "allow_spaces");
  278. char *filename = os_generate_formatted_filename(ext, space, fmt);
  279. dstr_copy(dst, dir);
  280. dstr_replace(dst, "\\", "/");
  281. if (dstr_end(dst) != '/')
  282. dstr_cat_ch(dst, '/');
  283. dstr_cat(dst, filename);
  284. char *slash = strrchr(dst->array, '/');
  285. if (slash) {
  286. *slash = 0;
  287. os_mkdirs(dst->array);
  288. *slash = '/';
  289. }
  290. if (!overwrite)
  291. find_best_filename(dst, space);
  292. bfree(filename);
  293. obs_data_release(settings);
  294. }
  295. static bool change_file(struct mp4_output *out, struct encoder_packet *pkt)
  296. {
  297. uint64_t start_time = os_gettime_ns();
  298. /* finalise file */
  299. for (size_t i = 0; i < out->chapters.num; i++) {
  300. struct chapter *chap = &out->chapters.array[i];
  301. mp4_mux_add_chapter(out->muxer, chap->dts_usec, chap->name);
  302. }
  303. mp4_mux_finalise(out->muxer);
  304. info("Waiting for file writer to finish...");
  305. /* flush/close file and destroy old muxer */
  306. buffered_file_serializer_free(&out->serializer);
  307. mp4_mux_destroy(out->muxer);
  308. for (size_t i = 0; i < out->chapters.num; i++)
  309. bfree(out->chapters.array[i].name);
  310. da_clear(out->chapters);
  311. info("MP4 file split complete. Finalization took %" PRIu64 " ms.", (os_gettime_ns() - start_time) / 1000000);
  312. /* open new file */
  313. generate_filename(out, &out->path, out->allow_overwrite);
  314. info("Changing output file to '%s'", out->path.array);
  315. if (!buffered_file_serializer_init(&out->serializer, out->path.array, out->buffer_size, out->chunk_size)) {
  316. warn("Unable to open MP4 file '%s'", out->path.array);
  317. return false;
  318. }
  319. out->muxer = mp4_mux_create(out->output, &out->serializer, out->flags);
  320. calldata_t cd = {0};
  321. signal_handler_t *sh = obs_output_get_signal_handler(out->output);
  322. calldata_set_string(&cd, "next_file", out->path.array);
  323. signal_handler_signal(sh, "file_changed", &cd);
  324. calldata_free(&cd);
  325. out->cur_size = 0;
  326. out->start_time = pkt->dts_usec;
  327. ts_offset_clear(out);
  328. return true;
  329. }
  330. static void mp4_output_stop(void *data, uint64_t ts)
  331. {
  332. struct mp4_output *out = data;
  333. out->stop_ts = ts / 1000;
  334. os_atomic_set_bool(&out->stopping, true);
  335. }
  336. static void mp4_mux_destroy_task(void *ptr)
  337. {
  338. struct mp4_mux *muxer = ptr;
  339. mp4_mux_destroy(muxer);
  340. }
  341. static void mp4_output_actual_stop(struct mp4_output *out, int code)
  342. {
  343. os_atomic_set_bool(&out->active, false);
  344. uint64_t start_time = os_gettime_ns();
  345. for (size_t i = 0; i < out->chapters.num; i++) {
  346. struct chapter *chap = &out->chapters.array[i];
  347. mp4_mux_add_chapter(out->muxer, chap->dts_usec, chap->name);
  348. }
  349. mp4_mux_finalise(out->muxer);
  350. if (code) {
  351. obs_output_signal_stop(out->output, code);
  352. } else {
  353. obs_output_end_data_capture(out->output);
  354. }
  355. info("Waiting for file writer to finish...");
  356. /* Flush/close output file and destroy muxer */
  357. buffered_file_serializer_free(&out->serializer);
  358. obs_queue_task(OBS_TASK_DESTROY, mp4_mux_destroy_task, out->muxer, false);
  359. out->muxer = NULL;
  360. /* Clear chapter data */
  361. for (size_t i = 0; i < out->chapters.num; i++)
  362. bfree(out->chapters.array[i].name);
  363. da_clear(out->chapters);
  364. info("MP4 file output complete. Finalization took %" PRIu64 " ms.", (os_gettime_ns() - start_time) / 1000000);
  365. }
  366. static void push_back_packet(struct mp4_output *out, struct encoder_packet *packet)
  367. {
  368. struct encoder_packet pkt;
  369. obs_encoder_packet_ref(&pkt, packet);
  370. da_push_back(out->split_buffer, &pkt);
  371. }
  372. static inline bool submit_packet(struct mp4_output *out, struct encoder_packet *pkt)
  373. {
  374. out->total_bytes += pkt->size;
  375. if (!out->split_file_enabled)
  376. return mp4_mux_submit_packet(out->muxer, pkt);
  377. out->cur_size += pkt->size;
  378. /* Apply DTS/PTS offset local packet copy */
  379. struct encoder_packet modified = *pkt;
  380. if (modified.type == OBS_ENCODER_VIDEO) {
  381. modified.dts -= out->video_pts_offsets[modified.track_idx];
  382. modified.pts -= out->video_pts_offsets[modified.track_idx];
  383. } else {
  384. modified.dts -= out->audio_dts_offsets[modified.track_idx];
  385. modified.pts -= out->audio_dts_offsets[modified.track_idx];
  386. }
  387. return mp4_mux_submit_packet(out->muxer, &modified);
  388. }
  389. static void mp4_output_packet(void *data, struct encoder_packet *packet)
  390. {
  391. struct mp4_output *out = data;
  392. pthread_mutex_lock(&out->mutex);
  393. if (!active(out))
  394. goto unlock;
  395. if (!packet) {
  396. mp4_output_actual_stop(out, OBS_OUTPUT_ENCODE_ERROR);
  397. goto unlock;
  398. }
  399. if (stopping(out)) {
  400. if (packet->sys_dts_usec >= (int64_t)out->stop_ts) {
  401. mp4_output_actual_stop(out, 0);
  402. goto unlock;
  403. }
  404. }
  405. if (out->split_file_enabled) {
  406. if (out->split_buffer.num) {
  407. int64_t pts_usec = packet_pts_usec(packet);
  408. struct encoder_packet *first_pkt = out->split_buffer.array;
  409. int64_t first_pts_usec = packet_pts_usec(first_pkt);
  410. if (pts_usec >= first_pts_usec) {
  411. if (packet->type != OBS_ENCODER_AUDIO) {
  412. push_back_packet(out, packet);
  413. goto unlock;
  414. }
  415. if (!change_file(out, first_pkt)) {
  416. mp4_output_actual_stop(out, OBS_OUTPUT_ERROR);
  417. goto unlock;
  418. }
  419. out->split_file_ready = true;
  420. }
  421. } else if (should_split(out, packet)) {
  422. push_back_packet(out, packet);
  423. goto unlock;
  424. }
  425. }
  426. if (out->split_file_ready) {
  427. for (size_t i = 0; i < out->split_buffer.num; i++) {
  428. struct encoder_packet *pkt = &out->split_buffer.array[i];
  429. ts_offset_update(out, pkt);
  430. submit_packet(out, pkt);
  431. obs_encoder_packet_release(pkt);
  432. }
  433. da_free(out->split_buffer);
  434. out->split_file_ready = false;
  435. os_atomic_set_bool(&out->manual_split, false);
  436. }
  437. if (out->split_file_enabled)
  438. ts_offset_update(out, packet);
  439. /* Update PTS for chapter markers */
  440. if (packet->type == OBS_ENCODER_VIDEO && packet->track_idx == 0)
  441. out->last_dts_usec = packet->dts_usec - out->start_time;
  442. submit_packet(out, packet);
  443. if (serializer_get_pos(&out->serializer) == -1)
  444. mp4_output_actual_stop(out, OBS_OUTPUT_ERROR);
  445. unlock:
  446. pthread_mutex_unlock(&out->mutex);
  447. }
  448. static obs_properties_t *mp4_output_properties(void *unused)
  449. {
  450. UNUSED_PARAMETER(unused);
  451. obs_properties_t *props = obs_properties_create();
  452. obs_properties_add_text(props, "path", obs_module_text("MP4Output.FilePath"), OBS_TEXT_DEFAULT);
  453. obs_properties_add_text(props, "muxer_settings", "muxer_settings", OBS_TEXT_DEFAULT);
  454. return props;
  455. }
  456. uint64_t mp4_output_total_bytes(void *data)
  457. {
  458. struct mp4_output *out = data;
  459. return out->total_bytes;
  460. }
  461. struct obs_output_info mp4_output_info = {
  462. .id = "mp4_output",
  463. .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK_AV | OBS_OUTPUT_CAN_PAUSE,
  464. .encoded_video_codecs = "h264;hevc;av1",
  465. .encoded_audio_codecs = "aac",
  466. .get_name = mp4_output_name,
  467. .create = mp4_output_create,
  468. .destroy = mp4_output_destroy,
  469. .start = mp4_output_start,
  470. .stop = mp4_output_stop,
  471. .encoded_packet = mp4_output_packet,
  472. .get_properties = mp4_output_properties,
  473. .get_total_bytes = mp4_output_total_bytes,
  474. };