mp4-output.c 16 KB

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