ffmpeg-mux.c 32 KB

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