ffmpeg-mux.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  1. /*
  2. * Copyright (c) 2015 Hugh Bailey <[email protected]>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #ifdef _WIN32
  17. #include <io.h>
  18. #include <fcntl.h>
  19. #include <windows.h>
  20. #define inline __inline
  21. #endif
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include "ffmpeg-mux.h"
  25. #include <util/threading.h>
  26. #include <util/platform.h>
  27. #include <util/circlebuf.h>
  28. #include <util/dstr.h>
  29. #include <libavcodec/avcodec.h>
  30. #include <libavformat/avformat.h>
  31. #include <libavutil/channel_layout.h>
  32. #include <libavutil/mastering_display_metadata.h>
  33. #define ANSI_COLOR_RED "\x1b[0;91m"
  34. #define ANSI_COLOR_MAGENTA "\x1b[0;95m"
  35. #define ANSI_COLOR_RESET "\x1b[0m"
  36. #if LIBAVCODEC_VERSION_MAJOR >= 58
  37. #define CODEC_FLAG_GLOBAL_H AV_CODEC_FLAG_GLOBAL_HEADER
  38. #else
  39. #define CODEC_FLAG_GLOBAL_H CODEC_FLAG_GLOBAL_HEADER
  40. #endif
  41. #define AVIO_BUFFER_SIZE 65536
  42. /* ------------------------------------------------------------------------- */
  43. static char *global_stream_key = "";
  44. struct resize_buf {
  45. uint8_t *buf;
  46. size_t size;
  47. size_t capacity;
  48. };
  49. static inline void resize_buf_resize(struct resize_buf *rb, size_t size)
  50. {
  51. if (!rb->buf) {
  52. rb->buf = malloc(size);
  53. rb->size = size;
  54. rb->capacity = size;
  55. } else {
  56. if (rb->capacity < size) {
  57. size_t capx2 = rb->capacity * 2;
  58. size_t new_cap = capx2 > size ? capx2 : size;
  59. rb->buf = realloc(rb->buf, new_cap);
  60. rb->capacity = new_cap;
  61. }
  62. rb->size = size;
  63. }
  64. }
  65. static inline void resize_buf_free(struct resize_buf *rb)
  66. {
  67. free(rb->buf);
  68. }
  69. /* ------------------------------------------------------------------------- */
  70. struct main_params {
  71. char *file;
  72. /* printable_file is file with any stream key information removed */
  73. struct dstr printable_file;
  74. int has_video;
  75. int tracks;
  76. char *vcodec;
  77. int vbitrate;
  78. int gop;
  79. int width;
  80. int height;
  81. int fps_num;
  82. int fps_den;
  83. int color_primaries;
  84. int color_trc;
  85. int colorspace;
  86. int color_range;
  87. int chroma_sample_location;
  88. int max_luminance;
  89. char *acodec;
  90. char *muxer_settings;
  91. int codec_tag;
  92. };
  93. struct audio_params {
  94. char *name;
  95. int abitrate;
  96. int sample_rate;
  97. int frame_size;
  98. int channels;
  99. };
  100. struct header {
  101. uint8_t *data;
  102. int size;
  103. };
  104. struct audio_info {
  105. AVStream *stream;
  106. AVCodecContext *ctx;
  107. };
  108. struct io_header {
  109. uint64_t seek_offset;
  110. size_t data_length;
  111. };
  112. struct io_buffer {
  113. bool active;
  114. bool shutdown_requested;
  115. bool output_error;
  116. os_event_t *buffer_space_available_event;
  117. os_event_t *new_data_available_event;
  118. pthread_t io_thread;
  119. pthread_mutex_t data_mutex;
  120. FILE *output_file;
  121. struct circlebuf data;
  122. uint64_t next_pos;
  123. };
  124. struct ffmpeg_mux {
  125. AVFormatContext *output;
  126. AVStream *video_stream;
  127. AVCodecContext *video_ctx;
  128. AVPacket *packet;
  129. struct audio_info *audio_infos;
  130. struct main_params params;
  131. struct audio_params *audio;
  132. struct header video_header;
  133. struct header *audio_header;
  134. int num_audio_streams;
  135. bool initialized;
  136. struct io_buffer io;
  137. };
  138. static void header_free(struct header *header)
  139. {
  140. free(header->data);
  141. }
  142. static void free_avformat(struct ffmpeg_mux *ffm)
  143. {
  144. if (ffm->output) {
  145. avcodec_free_context(&ffm->video_ctx);
  146. if ((ffm->output->oformat->flags & AVFMT_NOFILE) == 0)
  147. avio_close(ffm->output->pb);
  148. avformat_free_context(ffm->output);
  149. ffm->output = NULL;
  150. }
  151. if (ffm->audio_infos) {
  152. for (int i = 0; i < ffm->num_audio_streams; ++i)
  153. avcodec_free_context(&ffm->audio_infos[i].ctx);
  154. free(ffm->audio_infos);
  155. }
  156. ffm->video_stream = NULL;
  157. ffm->audio_infos = NULL;
  158. ffm->num_audio_streams = 0;
  159. }
  160. static void ffmpeg_mux_free(struct ffmpeg_mux *ffm)
  161. {
  162. if (ffm->initialized) {
  163. av_write_trailer(ffm->output);
  164. }
  165. // If we're writing to a file with the circlebuf, shut it
  166. // down gracefully
  167. if (ffm->io.active) {
  168. os_atomic_set_bool(&ffm->io.shutdown_requested, true);
  169. // Wakes up the I/O thread and waits for it to finish
  170. pthread_mutex_lock(&ffm->io.data_mutex);
  171. os_event_signal(ffm->io.new_data_available_event);
  172. pthread_mutex_unlock(&ffm->io.data_mutex);
  173. pthread_join(ffm->io.io_thread, NULL);
  174. // Cleanup everything else
  175. av_free(ffm->output->pb->buffer);
  176. avio_context_free(&ffm->output->pb);
  177. os_event_destroy(ffm->io.new_data_available_event);
  178. os_event_destroy(ffm->io.buffer_space_available_event);
  179. pthread_mutex_destroy(&ffm->io.data_mutex);
  180. circlebuf_free(&ffm->io.data);
  181. }
  182. free_avformat(ffm);
  183. header_free(&ffm->video_header);
  184. if (ffm->audio_header) {
  185. for (int i = 0; i < ffm->params.tracks; i++) {
  186. header_free(&ffm->audio_header[i]);
  187. }
  188. free(ffm->audio_header);
  189. }
  190. if (ffm->audio) {
  191. free(ffm->audio);
  192. }
  193. dstr_free(&ffm->params.printable_file);
  194. av_packet_free(&ffm->packet);
  195. memset(ffm, 0, sizeof(*ffm));
  196. }
  197. static bool get_opt_str(int *p_argc, char ***p_argv, char **str,
  198. const char *opt)
  199. {
  200. int argc = *p_argc;
  201. char **argv = *p_argv;
  202. if (!argc) {
  203. printf("Missing expected option: '%s'\n", opt);
  204. return false;
  205. }
  206. (*p_argc)--;
  207. (*p_argv)++;
  208. *str = argv[0];
  209. return true;
  210. }
  211. static bool get_opt_int(int *p_argc, char ***p_argv, int *i, const char *opt)
  212. {
  213. char *str;
  214. if (!get_opt_str(p_argc, p_argv, &str, opt)) {
  215. return false;
  216. }
  217. *i = atoi(str);
  218. return true;
  219. }
  220. static bool get_audio_params(struct audio_params *audio, int *argc,
  221. char ***argv)
  222. {
  223. if (!get_opt_str(argc, argv, &audio->name, "audio track name"))
  224. return false;
  225. if (!get_opt_int(argc, argv, &audio->abitrate, "audio bitrate"))
  226. return false;
  227. if (!get_opt_int(argc, argv, &audio->sample_rate, "audio sample rate"))
  228. return false;
  229. if (!get_opt_int(argc, argv, &audio->frame_size, "audio frame size"))
  230. return false;
  231. if (!get_opt_int(argc, argv, &audio->channels, "audio channels"))
  232. return false;
  233. return true;
  234. }
  235. static void ffmpeg_log_callback(void *param, int level, const char *format,
  236. va_list args)
  237. {
  238. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  239. char out_buffer[4096];
  240. struct dstr out = {0};
  241. vsnprintf(out_buffer, sizeof(out_buffer), format, args);
  242. dstr_copy(&out, out_buffer);
  243. if (global_stream_key && *global_stream_key) {
  244. dstr_replace(&out, global_stream_key, "{stream_key}");
  245. }
  246. switch (level) {
  247. case AV_LOG_INFO:
  248. fprintf(stdout, "info: [ffmpeg_muxer] %s", out.array);
  249. fflush(stdout);
  250. break;
  251. case AV_LOG_WARNING:
  252. fprintf(stdout, "%swarning: [ffmpeg_muxer] %s%s",
  253. ANSI_COLOR_MAGENTA, out.array, ANSI_COLOR_RESET);
  254. fflush(stdout);
  255. break;
  256. case AV_LOG_ERROR:
  257. fprintf(stderr, "%serror: [ffmpeg_muxer] %s%s", ANSI_COLOR_RED,
  258. out.array, ANSI_COLOR_RESET);
  259. fflush(stderr);
  260. }
  261. dstr_free(&out);
  262. #else
  263. UNUSED_PARAMETER(level);
  264. UNUSED_PARAMETER(format);
  265. UNUSED_PARAMETER(args);
  266. #endif
  267. UNUSED_PARAMETER(param);
  268. }
  269. static bool init_params(int *argc, char ***argv, struct main_params *params,
  270. struct audio_params **p_audio)
  271. {
  272. struct audio_params *audio = NULL;
  273. if (!get_opt_str(argc, argv, &params->file, "file name"))
  274. return false;
  275. if (!get_opt_int(argc, argv, &params->has_video, "video track count"))
  276. return false;
  277. if (!get_opt_int(argc, argv, &params->tracks, "audio track count"))
  278. return false;
  279. if (params->has_video > 1 || params->has_video < 0) {
  280. puts("Invalid number of video tracks\n");
  281. return false;
  282. }
  283. if (params->tracks < 0) {
  284. puts("Invalid number of audio tracks\n");
  285. return false;
  286. }
  287. if (params->has_video == 0 && params->tracks == 0) {
  288. puts("Must have at least 1 audio track or 1 video track\n");
  289. return false;
  290. }
  291. if (params->has_video) {
  292. if (!get_opt_str(argc, argv, &params->vcodec, "video codec"))
  293. return false;
  294. if (!get_opt_int(argc, argv, &params->vbitrate,
  295. "video bitrate"))
  296. return false;
  297. if (!get_opt_int(argc, argv, &params->width, "video width"))
  298. return false;
  299. if (!get_opt_int(argc, argv, &params->height, "video height"))
  300. return false;
  301. if (!get_opt_int(argc, argv, &params->color_primaries,
  302. "video color primaries"))
  303. return false;
  304. if (!get_opt_int(argc, argv, &params->color_trc,
  305. "video color trc"))
  306. return false;
  307. if (!get_opt_int(argc, argv, &params->colorspace,
  308. "video colorspace"))
  309. return false;
  310. if (!get_opt_int(argc, argv, &params->color_range,
  311. "video color range"))
  312. return false;
  313. if (!get_opt_int(argc, argv, &params->chroma_sample_location,
  314. "video chroma sample location"))
  315. return false;
  316. if (!get_opt_int(argc, argv, &params->max_luminance,
  317. "video max luminance"))
  318. return false;
  319. if (!get_opt_int(argc, argv, &params->fps_num, "video fps num"))
  320. return false;
  321. if (!get_opt_int(argc, argv, &params->fps_den, "video fps den"))
  322. return false;
  323. if (!get_opt_int(argc, argv, &params->codec_tag,
  324. "video codec tag"))
  325. params->codec_tag = 0;
  326. }
  327. if (params->tracks) {
  328. if (!get_opt_str(argc, argv, &params->acodec, "audio codec"))
  329. return false;
  330. audio = calloc(params->tracks, sizeof(*audio));
  331. for (int i = 0; i < params->tracks; i++) {
  332. if (!get_audio_params(&audio[i], argc, argv)) {
  333. free(audio);
  334. return false;
  335. }
  336. }
  337. }
  338. *p_audio = audio;
  339. dstr_copy(&params->printable_file, params->file);
  340. get_opt_str(argc, argv, &global_stream_key, "stream key");
  341. if (strcmp(global_stream_key, "") != 0) {
  342. dstr_replace(&params->printable_file, global_stream_key,
  343. "{stream_key}");
  344. }
  345. av_log_set_callback(ffmpeg_log_callback);
  346. get_opt_str(argc, argv, &params->muxer_settings, "muxer settings");
  347. return true;
  348. }
  349. static bool new_stream(struct ffmpeg_mux *ffm, AVStream **stream,
  350. const char *name)
  351. {
  352. *stream = avformat_new_stream(ffm->output, NULL);
  353. if (!*stream) {
  354. fprintf(stderr, "Couldn't create stream for encoder '%s'\n",
  355. name);
  356. return false;
  357. }
  358. (*stream)->id = ffm->output->nb_streams - 1;
  359. return true;
  360. }
  361. static void create_video_stream(struct ffmpeg_mux *ffm)
  362. {
  363. AVCodecContext *context;
  364. void *extradata = NULL;
  365. const char *name = ffm->params.vcodec;
  366. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  367. if (!codec) {
  368. fprintf(stderr, "Couldn't find codec '%s'\n", name);
  369. return;
  370. }
  371. if (!new_stream(ffm, &ffm->video_stream, name))
  372. return;
  373. if (ffm->video_header.size) {
  374. extradata = av_memdup(ffm->video_header.data,
  375. ffm->video_header.size);
  376. }
  377. context = avcodec_alloc_context3(NULL);
  378. context->codec_type = codec->type;
  379. context->codec_id = codec->id;
  380. context->codec_tag = ffm->params.codec_tag;
  381. context->bit_rate = (int64_t)ffm->params.vbitrate * 1000;
  382. context->width = ffm->params.width;
  383. context->height = ffm->params.height;
  384. context->coded_width = ffm->params.width;
  385. context->coded_height = ffm->params.height;
  386. context->color_primaries = ffm->params.color_primaries;
  387. context->color_trc = ffm->params.color_trc;
  388. context->colorspace = ffm->params.colorspace;
  389. context->color_range = ffm->params.color_range;
  390. context->chroma_sample_location = ffm->params.chroma_sample_location;
  391. context->extradata = extradata;
  392. context->extradata_size = ffm->video_header.size;
  393. context->time_base =
  394. (AVRational){ffm->params.fps_den, ffm->params.fps_num};
  395. ffm->video_stream->time_base = context->time_base;
  396. #if LIBAVFORMAT_VERSION_MAJOR < 59
  397. // codec->time_base may still be used if LIBAVFORMAT_VERSION_MAJOR < 59
  398. PRAGMA_WARN_PUSH
  399. PRAGMA_WARN_DEPRECATION
  400. ffm->video_stream->codec->time_base = context->time_base;
  401. PRAGMA_WARN_POP
  402. #endif
  403. ffm->video_stream->avg_frame_rate = av_inv_q(context->time_base);
  404. const int max_luminance = ffm->params.max_luminance;
  405. if (max_luminance > 0) {
  406. size_t content_size;
  407. AVContentLightMetadata *const content =
  408. av_content_light_metadata_alloc(&content_size);
  409. content->MaxCLL = max_luminance;
  410. content->MaxFALL = max_luminance;
  411. av_stream_add_side_data(ffm->video_stream,
  412. AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
  413. (uint8_t *)content, content_size);
  414. AVMasteringDisplayMetadata *const mastering =
  415. av_mastering_display_metadata_alloc();
  416. mastering->display_primaries[0][0] = av_make_q(17, 25);
  417. mastering->display_primaries[0][1] = av_make_q(8, 25);
  418. mastering->display_primaries[1][0] = av_make_q(53, 200);
  419. mastering->display_primaries[1][1] = av_make_q(69, 100);
  420. mastering->display_primaries[2][0] = av_make_q(3, 20);
  421. mastering->display_primaries[2][1] = av_make_q(3, 50);
  422. mastering->white_point[0] = av_make_q(3127, 10000);
  423. mastering->white_point[1] = av_make_q(329, 1000);
  424. mastering->min_luminance = av_make_q(0, 1);
  425. mastering->max_luminance = av_make_q(max_luminance, 1);
  426. mastering->has_primaries = 1;
  427. mastering->has_luminance = 1;
  428. av_stream_add_side_data(ffm->video_stream,
  429. AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  430. (uint8_t *)mastering,
  431. sizeof(*mastering));
  432. }
  433. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  434. context->flags |= CODEC_FLAG_GLOBAL_H;
  435. avcodec_parameters_from_context(ffm->video_stream->codecpar, context);
  436. ffm->video_ctx = context;
  437. }
  438. static void create_audio_stream(struct ffmpeg_mux *ffm, int idx)
  439. {
  440. AVCodecContext *context;
  441. AVStream *stream;
  442. void *extradata = NULL;
  443. const char *name = ffm->params.acodec;
  444. int channels;
  445. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  446. if (!codec) {
  447. fprintf(stderr, "Couldn't find codec '%s'\n", name);
  448. return;
  449. }
  450. if (!new_stream(ffm, &stream, name))
  451. return;
  452. av_dict_set(&stream->metadata, "title", ffm->audio[idx].name, 0);
  453. stream->time_base = (AVRational){1, ffm->audio[idx].sample_rate};
  454. if (ffm->audio_header[idx].size) {
  455. extradata = av_memdup(ffm->audio_header[idx].data,
  456. ffm->audio_header[idx].size);
  457. }
  458. context = avcodec_alloc_context3(NULL);
  459. context->codec_type = codec->type;
  460. context->codec_id = codec->id;
  461. context->bit_rate = (int64_t)ffm->audio[idx].abitrate * 1000;
  462. channels = ffm->audio[idx].channels;
  463. #if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(57, 24, 100)
  464. context->channels = channels;
  465. #endif
  466. context->sample_rate = ffm->audio[idx].sample_rate;
  467. context->frame_size = ffm->audio[idx].frame_size;
  468. context->sample_fmt = AV_SAMPLE_FMT_S16;
  469. context->time_base = stream->time_base;
  470. context->extradata = extradata;
  471. context->extradata_size = ffm->audio_header[idx].size;
  472. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59, 24, 100)
  473. context->channel_layout = av_get_default_channel_layout(channels);
  474. //avutil default channel layout for 5 channels is 5.0 ; fix for 4.1
  475. if (channels == 5)
  476. context->channel_layout = av_get_channel_layout("4.1");
  477. #else
  478. av_channel_layout_default(&context->ch_layout, channels);
  479. //avutil default channel layout for 5 channels is 5.0 ; fix for 4.1
  480. if (channels == 5)
  481. context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1;
  482. #endif
  483. if (ffm->output->oformat->flags & AVFMT_GLOBALHEADER)
  484. context->flags |= CODEC_FLAG_GLOBAL_H;
  485. avcodec_parameters_from_context(stream->codecpar, context);
  486. ffm->audio_infos[ffm->num_audio_streams].stream = stream;
  487. ffm->audio_infos[ffm->num_audio_streams].ctx = context;
  488. ffm->num_audio_streams++;
  489. }
  490. static bool init_streams(struct ffmpeg_mux *ffm)
  491. {
  492. if (ffm->params.has_video)
  493. create_video_stream(ffm);
  494. if (ffm->params.tracks) {
  495. ffm->audio_infos =
  496. calloc(ffm->params.tracks, sizeof(*ffm->audio_infos));
  497. for (int i = 0; i < ffm->params.tracks; i++)
  498. create_audio_stream(ffm, i);
  499. }
  500. if (!ffm->video_stream && !ffm->num_audio_streams)
  501. return false;
  502. return true;
  503. }
  504. static void set_header(struct header *header, uint8_t *data, size_t size)
  505. {
  506. header->size = (int)size;
  507. header->data = malloc(size);
  508. memcpy(header->data, data, size);
  509. }
  510. static void ffmpeg_mux_header(struct ffmpeg_mux *ffm, uint8_t *data,
  511. struct ffm_packet_info *info)
  512. {
  513. if (info->type == FFM_PACKET_VIDEO) {
  514. set_header(&ffm->video_header, data, (size_t)info->size);
  515. } else {
  516. set_header(&ffm->audio_header[info->index], data,
  517. (size_t)info->size);
  518. }
  519. }
  520. static size_t safe_read(void *vdata, size_t size)
  521. {
  522. uint8_t *data = vdata;
  523. size_t total = size;
  524. while (size > 0) {
  525. size_t in_size = fread(data, 1, size, stdin);
  526. if (in_size == 0)
  527. return 0;
  528. size -= in_size;
  529. data += in_size;
  530. }
  531. return total;
  532. }
  533. static bool ffmpeg_mux_get_header(struct ffmpeg_mux *ffm)
  534. {
  535. struct ffm_packet_info info = {0};
  536. bool success = safe_read(&info, sizeof(info)) == sizeof(info);
  537. if (success) {
  538. uint8_t *data = malloc(info.size);
  539. if (safe_read(data, info.size) == info.size) {
  540. ffmpeg_mux_header(ffm, data, &info);
  541. } else {
  542. success = false;
  543. }
  544. free(data);
  545. }
  546. return success;
  547. }
  548. static inline bool ffmpeg_mux_get_extra_data(struct ffmpeg_mux *ffm)
  549. {
  550. if (ffm->params.has_video) {
  551. if (!ffmpeg_mux_get_header(ffm)) {
  552. return false;
  553. }
  554. }
  555. for (int i = 0; i < ffm->params.tracks; i++) {
  556. if (!ffmpeg_mux_get_header(ffm)) {
  557. return false;
  558. }
  559. }
  560. return true;
  561. }
  562. #ifdef _MSC_VER
  563. #pragma warning(disable : 4996)
  564. #endif
  565. #define CHUNK_SIZE 1048576
  566. static void *ffmpeg_mux_io_thread(void *data)
  567. {
  568. struct ffmpeg_mux *ffm = data;
  569. // Chunk collects the writes into a larger batch
  570. size_t chunk_used = 0;
  571. unsigned char *chunk = malloc(CHUNK_SIZE);
  572. if (!chunk) {
  573. os_atomic_set_bool(&ffm->io.output_error, true);
  574. fprintf(stderr, "Error allocating memory for output\n");
  575. goto error;
  576. }
  577. bool shutting_down;
  578. bool want_seek = false;
  579. bool force_flush_chunk = false;
  580. // current_seek_position is a virtual position updated as we read from
  581. // the buffer, if it becomes discontinuous due to a seek request from
  582. // ffmpeg, then we flush the chunk. next_seek_position is the actual
  583. // offset we should seek to when we write the chunk.
  584. uint64_t current_seek_position = 0;
  585. uint64_t next_seek_position;
  586. for (;;) {
  587. // Wait for ffmpeg to write data to the buffer
  588. os_event_wait(ffm->io.new_data_available_event);
  589. // Loop to write in chunk_size chunks
  590. for (;;) {
  591. shutting_down = os_atomic_load_bool(
  592. &ffm->io.shutdown_requested);
  593. pthread_mutex_lock(&ffm->io.data_mutex);
  594. // Fetch as many writes as possible from the circlebuf
  595. // and fill up our local chunk. This may involve seeking
  596. // if ffmpeg needs to, so take care of that as well.
  597. for (;;) {
  598. size_t available = ffm->io.data.size;
  599. // Buffer is empty (now) or was already empty (we got
  600. // woken up to exit)
  601. if (!available)
  602. break;
  603. // Get seek offset and data size
  604. struct io_header header;
  605. circlebuf_peek_front(&ffm->io.data, &header,
  606. sizeof(header));
  607. // Do we need to seek?
  608. if (header.seek_offset !=
  609. current_seek_position) {
  610. // If there's already part of a chunk pending,
  611. // flush it at the current offset. Similarly,
  612. // if we already plan to seek, then seek.
  613. if (chunk_used || want_seek) {
  614. force_flush_chunk = true;
  615. break;
  616. }
  617. // Mark that we need to seek and where to
  618. want_seek = true;
  619. next_seek_position = header.seek_offset;
  620. // Update our virtual position
  621. current_seek_position =
  622. header.seek_offset;
  623. }
  624. // Make sure there's enough room for the data, if
  625. // not then force a flush
  626. if (header.data_length + chunk_used >
  627. CHUNK_SIZE) {
  628. force_flush_chunk = true;
  629. break;
  630. }
  631. // Remove header that we already read
  632. circlebuf_pop_front(&ffm->io.data, NULL,
  633. sizeof(header));
  634. // Copy from the buffer to our local chunk
  635. circlebuf_pop_front(&ffm->io.data,
  636. chunk + chunk_used,
  637. header.data_length);
  638. // Update offsets
  639. chunk_used += header.data_length;
  640. current_seek_position += header.data_length;
  641. }
  642. // Signal that there is more room in the buffer
  643. os_event_signal(ffm->io.buffer_space_available_event);
  644. // Try to avoid lots of small writes unless this was the final
  645. // data left in the buffer. The buffer might be entirely empty
  646. // if we were woken up to exit.
  647. if (!force_flush_chunk &&
  648. (!chunk_used ||
  649. (chunk_used < 65536 && !shutting_down))) {
  650. os_event_reset(
  651. ffm->io.new_data_available_event);
  652. pthread_mutex_unlock(&ffm->io.data_mutex);
  653. break;
  654. }
  655. pthread_mutex_unlock(&ffm->io.data_mutex);
  656. // Seek if we need to
  657. if (want_seek) {
  658. os_fseeki64(ffm->io.output_file,
  659. next_seek_position, SEEK_SET);
  660. // Update the next virtual position, making sure to take
  661. // into account the size of the chunk we're about to write.
  662. current_seek_position =
  663. next_seek_position + chunk_used;
  664. want_seek = false;
  665. }
  666. // Write the current chunk to the output file
  667. if (fwrite(chunk, chunk_used, 1, ffm->io.output_file) !=
  668. 1) {
  669. os_atomic_set_bool(&ffm->io.output_error, true);
  670. fprintf(stderr, "Error writing to '%s', %s\n",
  671. ffm->params.printable_file.array,
  672. strerror(errno));
  673. goto error;
  674. }
  675. chunk_used = 0;
  676. force_flush_chunk = false;
  677. }
  678. // If this was the last chunk, time to exit
  679. if (shutting_down)
  680. break;
  681. }
  682. error:
  683. if (chunk)
  684. free(chunk);
  685. fclose(ffm->io.output_file);
  686. return NULL;
  687. }
  688. static int64_t ffmpeg_mux_seek_av_buffer(void *opaque, int64_t offset,
  689. int whence)
  690. {
  691. struct ffmpeg_mux *ffm = opaque;
  692. // If the output thread failed, signal that back up the stack
  693. if (os_atomic_load_bool(&ffm->io.output_error))
  694. return -1;
  695. // Update where the next write should go
  696. pthread_mutex_lock(&ffm->io.data_mutex);
  697. if (whence == SEEK_SET)
  698. ffm->io.next_pos = offset;
  699. else if (whence == SEEK_CUR)
  700. ffm->io.next_pos += offset;
  701. pthread_mutex_unlock(&ffm->io.data_mutex);
  702. return 0;
  703. }
  704. static int ffmpeg_mux_write_av_buffer(void *opaque, uint8_t *buf, int buf_size)
  705. {
  706. struct ffmpeg_mux *ffm = opaque;
  707. // If the output thread failed, signal that back up the stack
  708. if (os_atomic_load_bool(&ffm->io.output_error))
  709. return -1;
  710. for (;;) {
  711. pthread_mutex_lock(&ffm->io.data_mutex);
  712. // Avoid unbounded growth of the circlebuf, cap to 256 MB
  713. if (ffm->io.data.capacity >= 256 * 1048576 &&
  714. ffm->io.data.capacity - ffm->io.data.size <
  715. buf_size + sizeof(struct io_header)) {
  716. // No space, wait for the I/O thread to make space
  717. os_event_reset(ffm->io.buffer_space_available_event);
  718. pthread_mutex_unlock(&ffm->io.data_mutex);
  719. os_event_wait(ffm->io.buffer_space_available_event);
  720. } else {
  721. break;
  722. }
  723. }
  724. struct io_header header;
  725. header.data_length = buf_size;
  726. header.seek_offset = ffm->io.next_pos;
  727. // Copy the data into the buffer
  728. circlebuf_push_back(&ffm->io.data, &header, sizeof(header));
  729. circlebuf_push_back(&ffm->io.data, buf, buf_size);
  730. // Advance the next write position
  731. ffm->io.next_pos += buf_size;
  732. // Tell the I/O thread that there's new data to be written
  733. os_event_signal(ffm->io.new_data_available_event);
  734. pthread_mutex_unlock(&ffm->io.data_mutex);
  735. return buf_size;
  736. }
  737. #define SRT_PROTO "srt"
  738. #define UDP_PROTO "udp"
  739. #define TCP_PROTO "tcp"
  740. #define HTTP_PROTO "http"
  741. #define RIST_PROTO "rist"
  742. static bool ffmpeg_mux_is_network(struct ffmpeg_mux *ffm)
  743. {
  744. return !strncmp(ffm->params.file, SRT_PROTO, sizeof(SRT_PROTO) - 1) ||
  745. !strncmp(ffm->params.file, UDP_PROTO, sizeof(UDP_PROTO) - 1) ||
  746. !strncmp(ffm->params.file, TCP_PROTO, sizeof(TCP_PROTO) - 1) ||
  747. !strncmp(ffm->params.file, HTTP_PROTO, sizeof(HTTP_PROTO) - 1) ||
  748. !strncmp(ffm->params.file, RIST_PROTO, sizeof(RIST_PROTO) - 1);
  749. }
  750. static inline int open_output_file(struct ffmpeg_mux *ffm)
  751. {
  752. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  753. AVOutputFormat *format = ffm->output->oformat;
  754. #else
  755. const AVOutputFormat *format = ffm->output->oformat;
  756. #endif
  757. int ret;
  758. if ((format->flags & AVFMT_NOFILE) == 0) {
  759. if (!ffmpeg_mux_is_network(ffm)) {
  760. // If not outputting to a network, write to a circlebuf
  761. // instead of relying on ffmpeg disk output. This hopefully
  762. // works around too small buffers somewhere causing output
  763. // stalls when recording.
  764. // We're in charge of managing the actual file now
  765. ffm->io.output_file = os_fopen(ffm->params.file, "wb");
  766. if (!ffm->io.output_file) {
  767. fprintf(stderr, "Couldn't open '%s', %s\n",
  768. ffm->params.printable_file.array,
  769. strerror(errno));
  770. return FFM_ERROR;
  771. }
  772. // Start at 1MB, this can grow up to 256 MB depending
  773. // how fast data is going in and out (limited in
  774. // ffmpeg_mux_write_av_buffer)
  775. circlebuf_reserve(&ffm->io.data, 1048576);
  776. pthread_mutex_init(&ffm->io.data_mutex, NULL);
  777. os_event_init(&ffm->io.buffer_space_available_event,
  778. OS_EVENT_TYPE_AUTO);
  779. os_event_init(&ffm->io.new_data_available_event,
  780. OS_EVENT_TYPE_AUTO);
  781. pthread_create(&ffm->io.io_thread, NULL,
  782. ffmpeg_mux_io_thread, ffm);
  783. unsigned char *avio_ctx_buffer =
  784. av_malloc(AVIO_BUFFER_SIZE);
  785. ffm->output->pb = avio_alloc_context(
  786. avio_ctx_buffer, AVIO_BUFFER_SIZE, 1, ffm, NULL,
  787. ffmpeg_mux_write_av_buffer,
  788. ffmpeg_mux_seek_av_buffer);
  789. ffm->io.active = true;
  790. } else {
  791. ret = avio_open(&ffm->output->pb, ffm->params.file,
  792. AVIO_FLAG_WRITE);
  793. if (ret < 0) {
  794. fprintf(stderr, "Couldn't open '%s', %s\n",
  795. ffm->params.printable_file.array,
  796. av_err2str(ret));
  797. return FFM_ERROR;
  798. }
  799. }
  800. }
  801. AVDictionary *dict = NULL;
  802. if ((ret = av_dict_parse_string(&dict, ffm->params.muxer_settings, "=",
  803. " ", 0))) {
  804. fprintf(stderr, "Failed to parse muxer settings: %s\n%s\n",
  805. av_err2str(ret), ffm->params.muxer_settings);
  806. av_dict_free(&dict);
  807. }
  808. if (av_dict_count(dict) > 0) {
  809. printf("Using muxer settings:");
  810. AVDictionaryEntry *entry = NULL;
  811. while ((entry = av_dict_get(dict, "", entry,
  812. AV_DICT_IGNORE_SUFFIX)))
  813. printf("\n\t%s=%s", entry->key, entry->value);
  814. printf("\n");
  815. }
  816. ret = avformat_write_header(ffm->output, &dict);
  817. if (ret < 0) {
  818. fprintf(stderr, "Error opening '%s': %s",
  819. ffm->params.printable_file.array, av_err2str(ret));
  820. av_dict_free(&dict);
  821. return ret == -22 ? FFM_UNSUPPORTED : FFM_ERROR;
  822. }
  823. av_dict_free(&dict);
  824. return FFM_SUCCESS;
  825. }
  826. static int ffmpeg_mux_init_context(struct ffmpeg_mux *ffm)
  827. {
  828. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  829. AVOutputFormat *output_format;
  830. #else
  831. const AVOutputFormat *output_format;
  832. #endif
  833. int ret;
  834. bool is_http = false;
  835. is_http = (strncmp(ffm->params.file, HTTP_PROTO,
  836. sizeof(HTTP_PROTO) - 1) == 0);
  837. bool is_network = ffmpeg_mux_is_network(ffm);
  838. if (is_network) {
  839. avformat_network_init();
  840. }
  841. if (is_network && !is_http)
  842. output_format = av_guess_format("mpegts", NULL, "video/M2PT");
  843. else
  844. output_format = av_guess_format(NULL, ffm->params.file, NULL);
  845. if (output_format == NULL) {
  846. fprintf(stderr, "Couldn't find an appropriate muxer for '%s'\n",
  847. ffm->params.printable_file.array);
  848. return FFM_ERROR;
  849. }
  850. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  851. printf("info: Output format name and long_name: %s, %s\n",
  852. output_format->name ? output_format->name : "unknown",
  853. output_format->long_name ? output_format->long_name : "unknown");
  854. #endif
  855. ret = avformat_alloc_output_context2(&ffm->output, output_format, NULL,
  856. ffm->params.file);
  857. if (ret < 0) {
  858. fprintf(stderr, "Couldn't initialize output context: %s\n",
  859. av_err2str(ret));
  860. return FFM_ERROR;
  861. }
  862. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  863. ffm->output->oformat->video_codec = AV_CODEC_ID_NONE;
  864. ffm->output->oformat->audio_codec = AV_CODEC_ID_NONE;
  865. #endif
  866. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(60, 0, 100)
  867. /* Allow FLAC/OPUS in MP4 */
  868. ffm->output->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
  869. #endif
  870. if (!init_streams(ffm)) {
  871. free_avformat(ffm);
  872. return FFM_ERROR;
  873. }
  874. ret = open_output_file(ffm);
  875. if (ret != FFM_SUCCESS) {
  876. free_avformat(ffm);
  877. return ret;
  878. }
  879. return FFM_SUCCESS;
  880. }
  881. static int ffmpeg_mux_init_internal(struct ffmpeg_mux *ffm, int argc,
  882. char *argv[])
  883. {
  884. argc--;
  885. argv++;
  886. if (!init_params(&argc, &argv, &ffm->params, &ffm->audio))
  887. return FFM_ERROR;
  888. if (ffm->params.tracks) {
  889. ffm->audio_header =
  890. calloc(ffm->params.tracks, sizeof(*ffm->audio_header));
  891. }
  892. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  893. av_register_all();
  894. #endif
  895. if (!ffmpeg_mux_get_extra_data(ffm))
  896. return FFM_ERROR;
  897. ffm->packet = av_packet_alloc();
  898. /* ffmpeg does not have a way of telling what's supported
  899. * for a given output format, so we try each possibility */
  900. return ffmpeg_mux_init_context(ffm);
  901. }
  902. static int ffmpeg_mux_init(struct ffmpeg_mux *ffm, int argc, char *argv[])
  903. {
  904. int ret = ffmpeg_mux_init_internal(ffm, argc, argv);
  905. if (ret != FFM_SUCCESS) {
  906. ffmpeg_mux_free(ffm);
  907. return ret;
  908. }
  909. ffm->initialized = true;
  910. return ret;
  911. }
  912. static inline int get_index(struct ffmpeg_mux *ffm,
  913. struct ffm_packet_info *info)
  914. {
  915. if (info->type == FFM_PACKET_VIDEO) {
  916. if (ffm->video_stream) {
  917. return ffm->video_stream->id;
  918. }
  919. } else {
  920. if ((int)info->index < ffm->num_audio_streams) {
  921. return ffm->audio_infos[info->index].stream->id;
  922. }
  923. }
  924. return -1;
  925. }
  926. static AVCodecContext *get_codec_context(struct ffmpeg_mux *ffm,
  927. struct ffm_packet_info *info)
  928. {
  929. if (info->type == FFM_PACKET_VIDEO) {
  930. if (ffm->video_stream) {
  931. return ffm->video_ctx;
  932. }
  933. } else {
  934. if ((int)info->index < ffm->num_audio_streams) {
  935. return ffm->audio_infos[info->index].ctx;
  936. }
  937. }
  938. return NULL;
  939. }
  940. static inline AVStream *get_stream(struct ffmpeg_mux *ffm, int idx)
  941. {
  942. return ffm->output->streams[idx];
  943. }
  944. static inline int64_t rescale_ts(struct ffmpeg_mux *ffm,
  945. AVRational codec_time_base, int64_t val,
  946. int idx)
  947. {
  948. AVStream *stream = get_stream(ffm, idx);
  949. return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base,
  950. stream->time_base,
  951. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  952. }
  953. static inline bool ffmpeg_mux_packet(struct ffmpeg_mux *ffm, uint8_t *buf,
  954. struct ffm_packet_info *info)
  955. {
  956. int idx = get_index(ffm, info);
  957. /* The muxer might not support video/audio, or multiple audio tracks */
  958. if (idx == -1) {
  959. return true;
  960. }
  961. const AVRational codec_time_base =
  962. get_codec_context(ffm, info)->time_base;
  963. ffm->packet->data = buf;
  964. ffm->packet->size = (int)info->size;
  965. ffm->packet->stream_index = idx;
  966. ffm->packet->pts = rescale_ts(ffm, codec_time_base, info->pts, idx);
  967. ffm->packet->dts = rescale_ts(ffm, codec_time_base, info->dts, idx);
  968. if (info->keyframe)
  969. ffm->packet->flags = AV_PKT_FLAG_KEY;
  970. int ret = av_interleaved_write_frame(ffm->output, ffm->packet);
  971. /* Treat "Invalid data found when processing input" and "Invalid argument" as non-fatal */
  972. if (ret == AVERROR_INVALIDDATA || ret == -EINVAL) {
  973. return true;
  974. }
  975. if (ret < 0) {
  976. fprintf(stderr, "av_interleaved_write_frame failed: %d: %s\n",
  977. ret, av_err2str(ret));
  978. }
  979. return ret >= 0;
  980. }
  981. static inline bool read_change_file(struct ffmpeg_mux *ffm, uint32_t size,
  982. struct resize_buf *filename, int argc,
  983. char **argv)
  984. {
  985. resize_buf_resize(filename, size + 1);
  986. if (safe_read(filename->buf, size) != size) {
  987. return false;
  988. }
  989. filename->buf[size] = 0;
  990. #ifdef ENABLE_FFMPEG_MUX_DEBUG
  991. fprintf(stderr, "info: New output file name: %s\n", filename->buf);
  992. #endif
  993. int ret;
  994. char *argv1_backup = argv[1];
  995. argv[1] = (char *)filename->buf;
  996. ffmpeg_mux_free(ffm);
  997. ret = ffmpeg_mux_init(ffm, argc, argv);
  998. if (ret != FFM_SUCCESS) {
  999. fprintf(stderr, "Couldn't initialize muxer\n");
  1000. return false;
  1001. }
  1002. argv[1] = argv1_backup;
  1003. return true;
  1004. }
  1005. /* ------------------------------------------------------------------------- */
  1006. #ifdef _WIN32
  1007. int wmain(int argc, wchar_t *argv_w[])
  1008. #else
  1009. int main(int argc, char *argv[])
  1010. #endif
  1011. {
  1012. struct ffm_packet_info info = {0};
  1013. struct ffmpeg_mux ffm = {0};
  1014. struct resize_buf rb = {0};
  1015. struct resize_buf rb_filename = {0};
  1016. bool fail = false;
  1017. int ret;
  1018. #ifdef _WIN32
  1019. char **argv;
  1020. SetErrorMode(SEM_FAILCRITICALERRORS);
  1021. argv = malloc(argc * sizeof(char *));
  1022. for (int i = 0; i < argc; i++) {
  1023. size_t len = wcslen(argv_w[i]);
  1024. int size;
  1025. size = WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len,
  1026. NULL, 0, NULL, NULL);
  1027. argv[i] = malloc(size + 1);
  1028. WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len, argv[i],
  1029. size + 1, NULL, NULL);
  1030. argv[i][size] = 0;
  1031. }
  1032. _setmode(_fileno(stdin), O_BINARY);
  1033. #endif
  1034. setvbuf(stderr, NULL, _IONBF, 0);
  1035. ret = ffmpeg_mux_init(&ffm, argc, argv);
  1036. if (ret != FFM_SUCCESS) {
  1037. fprintf(stderr, "Couldn't initialize muxer\n");
  1038. return ret;
  1039. }
  1040. while (!fail && safe_read(&info, sizeof(info)) == sizeof(info)) {
  1041. if (info.type == FFM_PACKET_CHANGE_FILE) {
  1042. fail = !read_change_file(&ffm, info.size, &rb_filename,
  1043. argc, argv);
  1044. continue;
  1045. }
  1046. resize_buf_resize(&rb, info.size);
  1047. if (safe_read(rb.buf, info.size) == info.size) {
  1048. fail = !ffmpeg_mux_packet(&ffm, rb.buf, &info);
  1049. } else {
  1050. fail = true;
  1051. }
  1052. }
  1053. ffmpeg_mux_free(&ffm);
  1054. resize_buf_free(&rb);
  1055. resize_buf_free(&rb_filename);
  1056. #ifdef _WIN32
  1057. for (int i = 0; i < argc; i++)
  1058. free(argv[i]);
  1059. free(argv);
  1060. #endif
  1061. return 0;
  1062. }