obs-ffmpeg-output.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  1. /******************************************************************************
  2. Copyright (C) 2014 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <obs-module.h>
  15. #include <util/circlebuf.h>
  16. #include <util/threading.h>
  17. #include <util/dstr.h>
  18. #include <util/darray.h>
  19. #include <util/platform.h>
  20. #include "obs-ffmpeg-output.h"
  21. #include "obs-ffmpeg-formats.h"
  22. #include "obs-ffmpeg-compat.h"
  23. struct ffmpeg_output {
  24. obs_output_t *output;
  25. volatile bool active;
  26. struct ffmpeg_data ff_data;
  27. bool connecting;
  28. pthread_t start_thread;
  29. uint64_t total_bytes;
  30. uint64_t audio_start_ts;
  31. uint64_t video_start_ts;
  32. uint64_t stop_ts;
  33. volatile bool stopping;
  34. bool write_thread_active;
  35. pthread_mutex_t write_mutex;
  36. pthread_t write_thread;
  37. os_sem_t *write_sem;
  38. os_event_t *stop_event;
  39. DARRAY(AVPacket) packets;
  40. };
  41. /* ------------------------------------------------------------------------- */
  42. static void ffmpeg_output_set_last_error(struct ffmpeg_data *data,
  43. const char *error)
  44. {
  45. if (data->last_error)
  46. bfree(data->last_error);
  47. data->last_error = bstrdup(error);
  48. }
  49. void ffmpeg_log_error(int log_level, struct ffmpeg_data *data,
  50. const char *format, ...)
  51. {
  52. va_list args;
  53. char out[4096];
  54. va_start(args, format);
  55. vsnprintf(out, sizeof(out), format, args);
  56. va_end(args);
  57. ffmpeg_output_set_last_error(data, out);
  58. blog(log_level, "%s", out);
  59. }
  60. static bool new_stream(struct ffmpeg_data *data, AVStream **stream,
  61. AVCodec **codec, enum AVCodecID id, const char *name)
  62. {
  63. *codec = (!!name && *name) ? avcodec_find_encoder_by_name(name)
  64. : avcodec_find_encoder(id);
  65. if (!*codec) {
  66. ffmpeg_log_error(LOG_WARNING, data,
  67. "Couldn't find encoder '%s'",
  68. avcodec_get_name(id));
  69. return false;
  70. }
  71. *stream = avformat_new_stream(data->output, *codec);
  72. if (!*stream) {
  73. ffmpeg_log_error(LOG_WARNING, data,
  74. "Couldn't create stream for encoder '%s'",
  75. avcodec_get_name(id));
  76. return false;
  77. }
  78. (*stream)->id = data->output->nb_streams - 1;
  79. return true;
  80. }
  81. static bool parse_params(AVCodecContext *context, char **opts)
  82. {
  83. bool ret = true;
  84. if (!context || !context->priv_data)
  85. return true;
  86. while (*opts) {
  87. char *opt = *opts;
  88. char *assign = strchr(opt, '=');
  89. if (assign) {
  90. char *name = opt;
  91. char *value;
  92. *assign = 0;
  93. value = assign + 1;
  94. if (av_opt_set(context, name, value,
  95. AV_OPT_SEARCH_CHILDREN)) {
  96. blog(LOG_WARNING, "Failed to set %s=%s", name,
  97. value);
  98. ret = false;
  99. }
  100. }
  101. opts++;
  102. }
  103. return ret;
  104. }
  105. static bool open_video_codec(struct ffmpeg_data *data)
  106. {
  107. AVCodecContext *const context = data->video_ctx;
  108. char **opts = strlist_split(data->config.video_settings, ' ', false);
  109. int ret;
  110. if (strcmp(data->vcodec->name, "libx264") == 0)
  111. av_opt_set(context->priv_data, "preset", "veryfast", 0);
  112. if (opts) {
  113. // libav requires x264 parameters in a special format which may be non-obvious
  114. if (!parse_params(context, opts) &&
  115. strcmp(data->vcodec->name, "libx264") == 0)
  116. blog(LOG_WARNING,
  117. "If you're trying to set x264 parameters, use x264-params=name=value:name=value");
  118. strlist_free(opts);
  119. }
  120. ret = avcodec_open2(context, data->vcodec, NULL);
  121. if (ret < 0) {
  122. ffmpeg_log_error(LOG_WARNING, data,
  123. "Failed to open video codec: %s",
  124. av_err2str(ret));
  125. return false;
  126. }
  127. data->vframe = av_frame_alloc();
  128. if (!data->vframe) {
  129. ffmpeg_log_error(LOG_WARNING, data,
  130. "Failed to allocate video frame");
  131. return false;
  132. }
  133. data->vframe->format = context->pix_fmt;
  134. data->vframe->width = context->width;
  135. data->vframe->height = context->height;
  136. data->vframe->color_range = data->config.color_range;
  137. data->vframe->color_primaries = data->config.color_primaries;
  138. data->vframe->color_trc = data->config.color_trc;
  139. data->vframe->colorspace = data->config.colorspace;
  140. ret = av_frame_get_buffer(data->vframe, base_get_alignment());
  141. if (ret < 0) {
  142. ffmpeg_log_error(LOG_WARNING, data,
  143. "Failed to allocate vframe: %s",
  144. av_err2str(ret));
  145. return false;
  146. }
  147. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  148. avcodec_parameters_from_context(data->video->codecpar, context);
  149. #endif
  150. return true;
  151. }
  152. static bool init_swscale(struct ffmpeg_data *data, AVCodecContext *context)
  153. {
  154. data->swscale = sws_getContext(
  155. data->config.width, data->config.height, data->config.format,
  156. data->config.scale_width, data->config.scale_height,
  157. context->pix_fmt, SWS_BICUBIC, NULL, NULL, NULL);
  158. if (!data->swscale) {
  159. ffmpeg_log_error(LOG_WARNING, data,
  160. "Could not initialize swscale");
  161. return false;
  162. }
  163. return true;
  164. }
  165. static bool create_video_stream(struct ffmpeg_data *data)
  166. {
  167. enum AVPixelFormat closest_format;
  168. AVCodecContext *context;
  169. struct obs_video_info ovi;
  170. if (!obs_get_video_info(&ovi)) {
  171. ffmpeg_log_error(LOG_WARNING, data, "No active video");
  172. return false;
  173. }
  174. if (!new_stream(data, &data->video, &data->vcodec,
  175. data->output->oformat->video_codec,
  176. data->config.video_encoder))
  177. return false;
  178. closest_format = data->config.format;
  179. if (data->vcodec->pix_fmts) {
  180. closest_format = avcodec_find_best_pix_fmt_of_list(
  181. data->vcodec->pix_fmts, data->config.format, 0, NULL);
  182. }
  183. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  184. context = avcodec_alloc_context3(data->vcodec);
  185. #else
  186. context = data->video->codec;
  187. #endif
  188. context->bit_rate = (int64_t)data->config.video_bitrate * 1000;
  189. context->width = data->config.scale_width;
  190. context->height = data->config.scale_height;
  191. context->time_base = (AVRational){ovi.fps_den, ovi.fps_num};
  192. context->gop_size = data->config.gop_size;
  193. context->pix_fmt = closest_format;
  194. context->color_range = data->config.color_range;
  195. context->color_primaries = data->config.color_primaries;
  196. context->color_trc = data->config.color_trc;
  197. context->colorspace = data->config.colorspace;
  198. context->thread_count = 0;
  199. data->video->time_base = context->time_base;
  200. if (data->output->oformat->flags & AVFMT_GLOBALHEADER)
  201. context->flags |= CODEC_FLAG_GLOBAL_H;
  202. data->video_ctx = context;
  203. if (!open_video_codec(data))
  204. return false;
  205. if (context->pix_fmt != data->config.format ||
  206. data->config.width != data->config.scale_width ||
  207. data->config.height != data->config.scale_height) {
  208. if (!init_swscale(data, context))
  209. return false;
  210. }
  211. return true;
  212. }
  213. static bool open_audio_codec(struct ffmpeg_data *data, int idx)
  214. {
  215. AVCodecContext *const context = data->audio_infos[idx].ctx;
  216. char **opts = strlist_split(data->config.audio_settings, ' ', false);
  217. int ret;
  218. if (opts) {
  219. parse_params(context, opts);
  220. strlist_free(opts);
  221. }
  222. data->aframe[idx] = av_frame_alloc();
  223. if (!data->aframe[idx]) {
  224. ffmpeg_log_error(LOG_WARNING, data,
  225. "Failed to allocate audio frame");
  226. return false;
  227. }
  228. data->aframe[idx]->format = context->sample_fmt;
  229. data->aframe[idx]->channels = context->channels;
  230. data->aframe[idx]->channel_layout = context->channel_layout;
  231. data->aframe[idx]->sample_rate = context->sample_rate;
  232. context->strict_std_compliance = -2;
  233. ret = avcodec_open2(context, data->acodec, NULL);
  234. if (ret < 0) {
  235. ffmpeg_log_error(LOG_WARNING, data,
  236. "Failed to open audio codec: %s",
  237. av_err2str(ret));
  238. return false;
  239. }
  240. data->frame_size = context->frame_size ? context->frame_size : 1024;
  241. ret = av_samples_alloc(data->samples[idx], NULL, context->channels,
  242. data->frame_size, context->sample_fmt, 0);
  243. if (ret < 0) {
  244. ffmpeg_log_error(LOG_WARNING, data,
  245. "Failed to create audio buffer: %s",
  246. av_err2str(ret));
  247. return false;
  248. }
  249. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  250. avcodec_parameters_from_context(data->audio_infos[idx].stream->codecpar,
  251. context);
  252. #endif
  253. return true;
  254. }
  255. static bool create_audio_stream(struct ffmpeg_data *data, int idx)
  256. {
  257. AVCodecContext *context;
  258. AVStream *stream;
  259. struct obs_audio_info aoi;
  260. if (!obs_get_audio_info(&aoi)) {
  261. ffmpeg_log_error(LOG_WARNING, data, "No active audio");
  262. return false;
  263. }
  264. if (!new_stream(data, &stream, &data->acodec,
  265. data->output->oformat->audio_codec,
  266. data->config.audio_encoder))
  267. return false;
  268. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  269. context = avcodec_alloc_context3(data->acodec);
  270. #else
  271. context = stream->codec;
  272. #endif
  273. context->bit_rate = (int64_t)data->config.audio_bitrate * 1000;
  274. context->time_base = (AVRational){1, aoi.samples_per_sec};
  275. context->channels = get_audio_channels(aoi.speakers);
  276. context->sample_rate = aoi.samples_per_sec;
  277. context->channel_layout =
  278. av_get_default_channel_layout(context->channels);
  279. //AVlib default channel layout for 5 channels is 5.0 ; fix for 4.1
  280. if (aoi.speakers == SPEAKERS_4POINT1)
  281. context->channel_layout = av_get_channel_layout("4.1");
  282. context->sample_fmt = data->acodec->sample_fmts
  283. ? data->acodec->sample_fmts[0]
  284. : AV_SAMPLE_FMT_FLTP;
  285. stream->time_base = context->time_base;
  286. data->audio_samplerate = aoi.samples_per_sec;
  287. data->audio_format = convert_ffmpeg_sample_format(context->sample_fmt);
  288. data->audio_planes = get_audio_planes(data->audio_format, aoi.speakers);
  289. data->audio_size = get_audio_size(data->audio_format, aoi.speakers, 1);
  290. if (data->output->oformat->flags & AVFMT_GLOBALHEADER)
  291. context->flags |= CODEC_FLAG_GLOBAL_H;
  292. data->audio_infos[idx].stream = stream;
  293. data->audio_infos[idx].ctx = context;
  294. return open_audio_codec(data, idx);
  295. }
  296. static inline bool init_streams(struct ffmpeg_data *data)
  297. {
  298. AVOutputFormat *format = data->output->oformat;
  299. if (format->video_codec != AV_CODEC_ID_NONE)
  300. if (!create_video_stream(data))
  301. return false;
  302. if (format->audio_codec != AV_CODEC_ID_NONE &&
  303. data->num_audio_streams) {
  304. data->audio_infos = calloc(data->num_audio_streams,
  305. sizeof(*data->audio_infos));
  306. for (int i = 0; i < data->num_audio_streams; i++) {
  307. if (!create_audio_stream(data, i))
  308. return false;
  309. }
  310. }
  311. return true;
  312. }
  313. static inline bool open_output_file(struct ffmpeg_data *data)
  314. {
  315. AVOutputFormat *format = data->output->oformat;
  316. int ret;
  317. AVDictionary *dict = NULL;
  318. if ((ret = av_dict_parse_string(&dict, data->config.muxer_settings, "=",
  319. " ", 0))) {
  320. ffmpeg_log_error(LOG_WARNING, data,
  321. "Failed to parse muxer settings: %s\n%s",
  322. av_err2str(ret), data->config.muxer_settings);
  323. av_dict_free(&dict);
  324. return false;
  325. }
  326. if (av_dict_count(dict) > 0) {
  327. struct dstr str = {0};
  328. AVDictionaryEntry *entry = NULL;
  329. while ((entry = av_dict_get(dict, "", entry,
  330. AV_DICT_IGNORE_SUFFIX)))
  331. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  332. blog(LOG_INFO, "Using muxer settings: %s", str.array);
  333. dstr_free(&str);
  334. }
  335. if ((format->flags & AVFMT_NOFILE) == 0) {
  336. ret = avio_open2(&data->output->pb, data->config.url,
  337. AVIO_FLAG_WRITE, NULL, &dict);
  338. if (ret < 0) {
  339. ffmpeg_log_error(LOG_WARNING, data,
  340. "Couldn't open '%s', %s",
  341. data->config.url, av_err2str(ret));
  342. av_dict_free(&dict);
  343. return false;
  344. }
  345. }
  346. ret = avformat_write_header(data->output, &dict);
  347. if (ret < 0) {
  348. ffmpeg_log_error(LOG_WARNING, data, "Error opening '%s': %s",
  349. data->config.url, av_err2str(ret));
  350. return false;
  351. }
  352. if (av_dict_count(dict) > 0) {
  353. struct dstr str = {0};
  354. AVDictionaryEntry *entry = NULL;
  355. while ((entry = av_dict_get(dict, "", entry,
  356. AV_DICT_IGNORE_SUFFIX)))
  357. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  358. blog(LOG_INFO, "Invalid muxer settings: %s", str.array);
  359. dstr_free(&str);
  360. }
  361. av_dict_free(&dict);
  362. return true;
  363. }
  364. static void close_video(struct ffmpeg_data *data)
  365. {
  366. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  367. avcodec_free_context(&data->video_ctx);
  368. #else
  369. avcodec_close(data->video->codec);
  370. #endif
  371. av_frame_unref(data->vframe);
  372. // This format for some reason derefs video frame
  373. // too many times
  374. if (data->vcodec->id == AV_CODEC_ID_A64_MULTI ||
  375. data->vcodec->id == AV_CODEC_ID_A64_MULTI5)
  376. return;
  377. av_frame_free(&data->vframe);
  378. }
  379. static void close_audio(struct ffmpeg_data *data)
  380. {
  381. for (int idx = 0; idx < data->num_audio_streams; idx++) {
  382. for (size_t i = 0; i < MAX_AV_PLANES; i++)
  383. circlebuf_free(&data->excess_frames[idx][i]);
  384. if (data->samples[idx][0])
  385. av_freep(&data->samples[idx][0]);
  386. if (data->audio_infos[idx].ctx) {
  387. #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
  388. avcodec_free_context(&data->audio_infos[idx].ctx);
  389. #else
  390. avcodec_close(data->audio_infos[idx].stream->codec);
  391. #endif
  392. }
  393. if (data->aframe[idx])
  394. av_frame_free(&data->aframe[idx]);
  395. }
  396. }
  397. void ffmpeg_data_free(struct ffmpeg_data *data)
  398. {
  399. if (data->initialized)
  400. av_write_trailer(data->output);
  401. if (data->video)
  402. close_video(data);
  403. if (data->audio_infos) {
  404. close_audio(data);
  405. free(data->audio_infos);
  406. data->audio_infos = NULL;
  407. }
  408. if (data->output) {
  409. if ((data->output->oformat->flags & AVFMT_NOFILE) == 0)
  410. avio_close(data->output->pb);
  411. avformat_free_context(data->output);
  412. }
  413. if (data->last_error)
  414. bfree(data->last_error);
  415. memset(data, 0, sizeof(struct ffmpeg_data));
  416. }
  417. static inline const char *safe_str(const char *s)
  418. {
  419. if (s == NULL)
  420. return "(NULL)";
  421. else
  422. return s;
  423. }
  424. static enum AVCodecID get_codec_id(const char *name, int id)
  425. {
  426. AVCodec *codec;
  427. if (id != 0)
  428. return (enum AVCodecID)id;
  429. if (!name || !*name)
  430. return AV_CODEC_ID_NONE;
  431. codec = avcodec_find_encoder_by_name(name);
  432. if (!codec)
  433. return AV_CODEC_ID_NONE;
  434. return codec->id;
  435. }
  436. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  437. static void set_encoder_ids(struct ffmpeg_data *data)
  438. {
  439. data->output->oformat->video_codec = get_codec_id(
  440. data->config.video_encoder, data->config.video_encoder_id);
  441. data->output->oformat->audio_codec = get_codec_id(
  442. data->config.audio_encoder, data->config.audio_encoder_id);
  443. }
  444. #endif
  445. bool ffmpeg_data_init(struct ffmpeg_data *data, struct ffmpeg_cfg *config)
  446. {
  447. bool is_rtmp = false;
  448. memset(data, 0, sizeof(struct ffmpeg_data));
  449. data->config = *config;
  450. data->num_audio_streams = config->audio_mix_count;
  451. data->audio_tracks = config->audio_tracks;
  452. if (!config->url || !*config->url)
  453. return false;
  454. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  455. av_register_all();
  456. #endif
  457. avformat_network_init();
  458. is_rtmp = (astrcmpi_n(config->url, "rtmp://", 7) == 0);
  459. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  460. AVOutputFormat *output_format;
  461. #else
  462. const AVOutputFormat *output_format;
  463. #endif
  464. output_format = av_guess_format(
  465. is_rtmp ? "flv" : data->config.format_name, data->config.url,
  466. is_rtmp ? NULL : data->config.format_mime_type);
  467. if (output_format == NULL) {
  468. ffmpeg_log_error(
  469. LOG_WARNING, data,
  470. "Couldn't find matching output format with "
  471. "parameters: name=%s, url=%s, mime=%s",
  472. safe_str(is_rtmp ? "flv" : data->config.format_name),
  473. safe_str(data->config.url),
  474. safe_str(is_rtmp ? NULL
  475. : data->config.format_mime_type));
  476. goto fail;
  477. }
  478. avformat_alloc_output_context2(&data->output, output_format, NULL,
  479. data->config.url);
  480. if (!data->output) {
  481. ffmpeg_log_error(LOG_WARNING, data,
  482. "Couldn't create avformat context");
  483. goto fail;
  484. }
  485. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  486. if (is_rtmp) {
  487. data->output->oformat->video_codec = AV_CODEC_ID_H264;
  488. data->output->oformat->audio_codec = AV_CODEC_ID_AAC;
  489. } else {
  490. if (data->config.format_name)
  491. set_encoder_ids(data);
  492. }
  493. #else
  494. if (is_rtmp) {
  495. data->config.audio_encoder = "aac";
  496. data->config.audio_encoder_id = AV_CODEC_ID_AAC;
  497. data->config.video_encoder = "libx264";
  498. data->config.video_encoder_id = AV_CODEC_ID_H264;
  499. }
  500. #endif
  501. if (!init_streams(data))
  502. goto fail;
  503. if (!open_output_file(data))
  504. goto fail;
  505. av_dump_format(data->output, 0, NULL, 1);
  506. data->initialized = true;
  507. return true;
  508. fail:
  509. blog(LOG_WARNING, "ffmpeg_data_init failed");
  510. return false;
  511. }
  512. /* ------------------------------------------------------------------------- */
  513. static inline bool stopping(struct ffmpeg_output *output)
  514. {
  515. return os_atomic_load_bool(&output->stopping);
  516. }
  517. static const char *ffmpeg_output_getname(void *unused)
  518. {
  519. UNUSED_PARAMETER(unused);
  520. return obs_module_text("FFmpegOutput");
  521. }
  522. static void ffmpeg_log_callback(void *param, int level, const char *format,
  523. va_list args)
  524. {
  525. if (level <= AV_LOG_INFO)
  526. blogva(LOG_DEBUG, format, args);
  527. UNUSED_PARAMETER(param);
  528. }
  529. static void *ffmpeg_output_create(obs_data_t *settings, obs_output_t *output)
  530. {
  531. struct ffmpeg_output *data = bzalloc(sizeof(struct ffmpeg_output));
  532. pthread_mutex_init_value(&data->write_mutex);
  533. data->output = output;
  534. if (pthread_mutex_init(&data->write_mutex, NULL) != 0)
  535. goto fail;
  536. if (os_event_init(&data->stop_event, OS_EVENT_TYPE_AUTO) != 0)
  537. goto fail;
  538. if (os_sem_init(&data->write_sem, 0) != 0)
  539. goto fail;
  540. av_log_set_callback(ffmpeg_log_callback);
  541. UNUSED_PARAMETER(settings);
  542. return data;
  543. fail:
  544. pthread_mutex_destroy(&data->write_mutex);
  545. os_event_destroy(data->stop_event);
  546. bfree(data);
  547. return NULL;
  548. }
  549. static void ffmpeg_output_full_stop(void *data);
  550. static void ffmpeg_deactivate(struct ffmpeg_output *output);
  551. static void ffmpeg_output_destroy(void *data)
  552. {
  553. struct ffmpeg_output *output = data;
  554. if (output) {
  555. if (output->connecting)
  556. pthread_join(output->start_thread, NULL);
  557. ffmpeg_output_full_stop(output);
  558. pthread_mutex_destroy(&output->write_mutex);
  559. os_sem_destroy(output->write_sem);
  560. os_event_destroy(output->stop_event);
  561. bfree(data);
  562. }
  563. }
  564. static inline void copy_data(AVFrame *pic, const struct video_data *frame,
  565. int height, enum AVPixelFormat format)
  566. {
  567. int h_chroma_shift, v_chroma_shift;
  568. av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift,
  569. &v_chroma_shift);
  570. for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
  571. if (!frame->data[plane])
  572. continue;
  573. int frame_rowsize = (int)frame->linesize[plane];
  574. int pic_rowsize = pic->linesize[plane];
  575. int bytes = frame_rowsize < pic_rowsize ? frame_rowsize
  576. : pic_rowsize;
  577. int plane_height = height >> (plane ? v_chroma_shift : 0);
  578. for (int y = 0; y < plane_height; y++) {
  579. int pos_frame = y * frame_rowsize;
  580. int pos_pic = y * pic_rowsize;
  581. memcpy(pic->data[plane] + pos_pic,
  582. frame->data[plane] + pos_frame, bytes);
  583. }
  584. }
  585. }
  586. static void receive_video(void *param, struct video_data *frame)
  587. {
  588. struct ffmpeg_output *output = param;
  589. struct ffmpeg_data *data = &output->ff_data;
  590. // codec doesn't support video or none configured
  591. if (!data->video)
  592. return;
  593. AVCodecContext *context = data->video_ctx;
  594. AVPacket packet = {0};
  595. int ret = 0, got_packet;
  596. av_init_packet(&packet);
  597. if (!output->video_start_ts)
  598. output->video_start_ts = frame->timestamp;
  599. if (!data->start_timestamp)
  600. data->start_timestamp = frame->timestamp;
  601. ret = av_frame_make_writable(data->vframe);
  602. if (ret < 0) {
  603. blog(LOG_WARNING,
  604. "receive_video: Error obtaining writable "
  605. "AVFrame: %s",
  606. av_err2str(ret));
  607. //FIXME: stop the encode with an error
  608. return;
  609. }
  610. if (!!data->swscale)
  611. sws_scale(data->swscale, (const uint8_t *const *)frame->data,
  612. (const int *)frame->linesize, 0, data->config.height,
  613. data->vframe->data, data->vframe->linesize);
  614. else
  615. copy_data(data->vframe, frame, context->height,
  616. context->pix_fmt);
  617. #if LIBAVFORMAT_VERSION_MAJOR < 58
  618. if (data->output->flags & AVFMT_RAWPICTURE) {
  619. packet.flags |= AV_PKT_FLAG_KEY;
  620. packet.stream_index = data->video->index;
  621. packet.data = data->vframe->data[0];
  622. packet.size = sizeof(AVPicture);
  623. pthread_mutex_lock(&output->write_mutex);
  624. da_push_back(output->packets, &packet);
  625. pthread_mutex_unlock(&output->write_mutex);
  626. os_sem_post(output->write_sem);
  627. } else {
  628. #endif
  629. data->vframe->pts = data->total_frames;
  630. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  631. ret = avcodec_send_frame(context, data->vframe);
  632. if (ret == 0)
  633. ret = avcodec_receive_packet(context, &packet);
  634. got_packet = (ret == 0);
  635. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  636. ret = 0;
  637. #else
  638. ret = avcodec_encode_video2(context, &packet, data->vframe,
  639. &got_packet);
  640. #endif
  641. if (ret < 0) {
  642. blog(LOG_WARNING,
  643. "receive_video: Error encoding "
  644. "video: %s",
  645. av_err2str(ret));
  646. //FIXME: stop the encode with an error
  647. return;
  648. }
  649. if (!ret && got_packet && packet.size) {
  650. packet.pts = rescale_ts(packet.pts, context,
  651. data->video->time_base);
  652. packet.dts = rescale_ts(packet.dts, context,
  653. data->video->time_base);
  654. packet.duration = (int)av_rescale_q(
  655. packet.duration, context->time_base,
  656. data->video->time_base);
  657. pthread_mutex_lock(&output->write_mutex);
  658. da_push_back(output->packets, &packet);
  659. pthread_mutex_unlock(&output->write_mutex);
  660. os_sem_post(output->write_sem);
  661. } else {
  662. ret = 0;
  663. }
  664. #if LIBAVFORMAT_VERSION_MAJOR < 58
  665. }
  666. #endif
  667. if (ret != 0) {
  668. blog(LOG_WARNING, "receive_video: Error writing video: %s",
  669. av_err2str(ret));
  670. //FIXME: stop the encode with an error
  671. }
  672. data->total_frames++;
  673. }
  674. static void encode_audio(struct ffmpeg_output *output, int idx,
  675. struct AVCodecContext *context, size_t block_size)
  676. {
  677. struct ffmpeg_data *data = &output->ff_data;
  678. AVPacket packet = {0};
  679. int ret, got_packet;
  680. size_t total_size = data->frame_size * block_size * context->channels;
  681. data->aframe[idx]->nb_samples = data->frame_size;
  682. data->aframe[idx]->pts = av_rescale_q(
  683. data->total_samples[idx], (AVRational){1, context->sample_rate},
  684. context->time_base);
  685. ret = avcodec_fill_audio_frame(data->aframe[idx], context->channels,
  686. context->sample_fmt,
  687. data->samples[idx][0], (int)total_size,
  688. 1);
  689. if (ret < 0) {
  690. blog(LOG_WARNING,
  691. "encode_audio: avcodec_fill_audio_frame "
  692. "failed: %s",
  693. av_err2str(ret));
  694. //FIXME: stop the encode with an error
  695. return;
  696. }
  697. data->total_samples[idx] += data->frame_size;
  698. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  699. ret = avcodec_send_frame(context, data->aframe[idx]);
  700. if (ret == 0)
  701. ret = avcodec_receive_packet(context, &packet);
  702. got_packet = (ret == 0);
  703. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  704. ret = 0;
  705. #else
  706. ret = avcodec_encode_audio2(context, &packet, data->aframe[idx],
  707. &got_packet);
  708. #endif
  709. if (ret < 0) {
  710. blog(LOG_WARNING, "encode_audio: Error encoding audio: %s",
  711. av_err2str(ret));
  712. //FIXME: stop the encode with an error
  713. return;
  714. }
  715. if (!got_packet)
  716. return;
  717. packet.pts = rescale_ts(packet.pts, context,
  718. data->audio_infos[idx].stream->time_base);
  719. packet.dts = rescale_ts(packet.dts, context,
  720. data->audio_infos[idx].stream->time_base);
  721. packet.duration =
  722. (int)av_rescale_q(packet.duration, context->time_base,
  723. data->audio_infos[idx].stream->time_base);
  724. packet.stream_index = data->audio_infos[idx].stream->index;
  725. pthread_mutex_lock(&output->write_mutex);
  726. da_push_back(output->packets, &packet);
  727. pthread_mutex_unlock(&output->write_mutex);
  728. os_sem_post(output->write_sem);
  729. }
  730. /* Given a bitmask for the selected tracks and the mix index,
  731. * this returns the stream index which will be passed to the muxer. */
  732. static int get_track_order(int track_config, size_t mix_index)
  733. {
  734. int position = 0;
  735. for (size_t i = 0; i < mix_index; i++) {
  736. if (track_config & 1 << i)
  737. position++;
  738. }
  739. return position;
  740. }
  741. static void receive_audio(void *param, size_t mix_idx, struct audio_data *frame)
  742. {
  743. struct ffmpeg_output *output = param;
  744. struct ffmpeg_data *data = &output->ff_data;
  745. size_t frame_size_bytes;
  746. struct audio_data in = *frame;
  747. int track_order;
  748. // codec doesn't support audio or none configured
  749. if (!data->audio_infos)
  750. return;
  751. /* check that the track was selected */
  752. if ((data->audio_tracks & (1 << mix_idx)) == 0)
  753. return;
  754. /* get track order (first selected, etc ...) */
  755. track_order = get_track_order(data->audio_tracks, mix_idx);
  756. AVCodecContext *context = data->audio_infos[track_order].ctx;
  757. if (!data->start_timestamp && data->video)
  758. return;
  759. if (!output->audio_start_ts)
  760. output->audio_start_ts = in.timestamp;
  761. frame_size_bytes = (size_t)data->frame_size * data->audio_size;
  762. for (size_t i = 0; i < data->audio_planes; i++)
  763. circlebuf_push_back(&data->excess_frames[track_order][i],
  764. in.data[i], in.frames * data->audio_size);
  765. while (data->excess_frames[track_order][0].size >= frame_size_bytes) {
  766. for (size_t i = 0; i < data->audio_planes; i++)
  767. circlebuf_pop_front(
  768. &data->excess_frames[track_order][i],
  769. data->samples[track_order][i],
  770. frame_size_bytes);
  771. encode_audio(output, track_order, context, data->audio_size);
  772. }
  773. }
  774. static uint64_t get_packet_sys_dts(struct ffmpeg_output *output,
  775. AVPacket *packet)
  776. {
  777. struct ffmpeg_data *data = &output->ff_data;
  778. uint64_t pause_offset = obs_output_get_pause_offset(output->output);
  779. uint64_t start_ts;
  780. AVRational time_base;
  781. if (data->video && data->video->index == packet->stream_index) {
  782. time_base = data->video->time_base;
  783. start_ts = output->video_start_ts;
  784. } else {
  785. time_base = data->audio_infos[0].stream->time_base;
  786. start_ts = output->audio_start_ts;
  787. }
  788. return start_ts + pause_offset +
  789. (uint64_t)av_rescale_q(packet->dts, time_base,
  790. (AVRational){1, 1000000000});
  791. }
  792. static int process_packet(struct ffmpeg_output *output)
  793. {
  794. AVPacket packet;
  795. bool new_packet = false;
  796. int ret;
  797. pthread_mutex_lock(&output->write_mutex);
  798. if (output->packets.num) {
  799. packet = output->packets.array[0];
  800. da_erase(output->packets, 0);
  801. new_packet = true;
  802. }
  803. pthread_mutex_unlock(&output->write_mutex);
  804. if (!new_packet)
  805. return 0;
  806. /*blog(LOG_DEBUG, "size = %d, flags = %lX, stream = %d, "
  807. "packets queued: %lu",
  808. packet.size, packet.flags,
  809. packet.stream_index, output->packets.num);*/
  810. if (stopping(output)) {
  811. uint64_t sys_ts = get_packet_sys_dts(output, &packet);
  812. if (sys_ts >= output->stop_ts)
  813. return 0;
  814. }
  815. output->total_bytes += packet.size;
  816. ret = av_interleaved_write_frame(output->ff_data.output, &packet);
  817. if (ret < 0) {
  818. av_free_packet(&packet);
  819. ffmpeg_log_error(LOG_WARNING, &output->ff_data,
  820. "process_packet: Error writing packet: %s",
  821. av_err2str(ret));
  822. return ret;
  823. }
  824. return 0;
  825. }
  826. static void *write_thread(void *data)
  827. {
  828. struct ffmpeg_output *output = data;
  829. while (os_sem_wait(output->write_sem) == 0) {
  830. /* check to see if shutting down */
  831. if (os_event_try(output->stop_event) == 0)
  832. break;
  833. int ret = process_packet(output);
  834. if (ret != 0) {
  835. int code = OBS_OUTPUT_ERROR;
  836. pthread_detach(output->write_thread);
  837. output->write_thread_active = false;
  838. if (ret == -ENOSPC)
  839. code = OBS_OUTPUT_NO_SPACE;
  840. obs_output_signal_stop(output->output, code);
  841. ffmpeg_deactivate(output);
  842. break;
  843. }
  844. }
  845. output->active = false;
  846. return NULL;
  847. }
  848. static inline const char *get_string_or_null(obs_data_t *settings,
  849. const char *name)
  850. {
  851. const char *value = obs_data_get_string(settings, name);
  852. if (!value || !strlen(value))
  853. return NULL;
  854. return value;
  855. }
  856. static int get_audio_mix_count(int audio_mix_mask)
  857. {
  858. int mix_count = 0;
  859. for (int i = 0; i < MAX_AUDIO_MIXES; i++) {
  860. if ((audio_mix_mask & (1 << i)) != 0) {
  861. mix_count++;
  862. }
  863. }
  864. return mix_count;
  865. }
  866. static bool try_connect(struct ffmpeg_output *output)
  867. {
  868. video_t *video = obs_output_video(output->output);
  869. const struct video_output_info *voi = video_output_get_info(video);
  870. struct ffmpeg_cfg config;
  871. obs_data_t *settings;
  872. bool success;
  873. int ret;
  874. settings = obs_output_get_settings(output->output);
  875. obs_data_set_default_int(settings, "gop_size", 120);
  876. config.url = obs_data_get_string(settings, "url");
  877. config.format_name = get_string_or_null(settings, "format_name");
  878. config.format_mime_type =
  879. get_string_or_null(settings, "format_mime_type");
  880. config.muxer_settings = obs_data_get_string(settings, "muxer_settings");
  881. config.video_bitrate = (int)obs_data_get_int(settings, "video_bitrate");
  882. config.audio_bitrate = (int)obs_data_get_int(settings, "audio_bitrate");
  883. config.gop_size = (int)obs_data_get_int(settings, "gop_size");
  884. config.video_encoder = get_string_or_null(settings, "video_encoder");
  885. config.video_encoder_id =
  886. (int)obs_data_get_int(settings, "video_encoder_id");
  887. config.audio_encoder = get_string_or_null(settings, "audio_encoder");
  888. config.audio_encoder_id =
  889. (int)obs_data_get_int(settings, "audio_encoder_id");
  890. config.video_settings = obs_data_get_string(settings, "video_settings");
  891. config.audio_settings = obs_data_get_string(settings, "audio_settings");
  892. config.scale_width = (int)obs_data_get_int(settings, "scale_width");
  893. config.scale_height = (int)obs_data_get_int(settings, "scale_height");
  894. config.width = (int)obs_output_get_width(output->output);
  895. config.height = (int)obs_output_get_height(output->output);
  896. config.format =
  897. obs_to_ffmpeg_video_format(video_output_get_format(video));
  898. config.audio_tracks = (int)obs_output_get_mixers(output->output);
  899. config.audio_mix_count = get_audio_mix_count(config.audio_tracks);
  900. config.color_range = voi->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG
  901. : AVCOL_RANGE_MPEG;
  902. switch (voi->colorspace) {
  903. case VIDEO_CS_601:
  904. config.color_primaries = AVCOL_PRI_SMPTE170M;
  905. config.color_trc = AVCOL_TRC_SMPTE170M;
  906. break;
  907. case VIDEO_CS_DEFAULT:
  908. case VIDEO_CS_709:
  909. config.color_primaries = AVCOL_PRI_BT709;
  910. config.color_trc = AVCOL_TRC_BT709;
  911. break;
  912. case VIDEO_CS_SRGB:
  913. config.color_primaries = AVCOL_PRI_BT709;
  914. config.color_trc = AVCOL_TRC_IEC61966_2_1;
  915. break;
  916. }
  917. if (format_is_yuv(voi->format)) {
  918. config.colorspace = (voi->colorspace == VIDEO_CS_601)
  919. ? AVCOL_SPC_SMPTE170M
  920. : AVCOL_SPC_BT709;
  921. } else {
  922. config.colorspace = AVCOL_SPC_RGB;
  923. }
  924. if (config.format == AV_PIX_FMT_NONE) {
  925. blog(LOG_DEBUG, "invalid pixel format used for FFmpeg output");
  926. return false;
  927. }
  928. if (!config.scale_width)
  929. config.scale_width = config.width;
  930. if (!config.scale_height)
  931. config.scale_height = config.height;
  932. success = ffmpeg_data_init(&output->ff_data, &config);
  933. obs_data_release(settings);
  934. if (!success) {
  935. if (output->ff_data.last_error) {
  936. obs_output_set_last_error(output->output,
  937. output->ff_data.last_error);
  938. }
  939. ffmpeg_data_free(&output->ff_data);
  940. return false;
  941. }
  942. struct audio_convert_info aci = {.format =
  943. output->ff_data.audio_format};
  944. output->active = true;
  945. if (!obs_output_can_begin_data_capture(output->output, 0))
  946. return false;
  947. ret = pthread_create(&output->write_thread, NULL, write_thread, output);
  948. if (ret != 0) {
  949. ffmpeg_log_error(LOG_WARNING, &output->ff_data,
  950. "ffmpeg_output_start: failed to create write "
  951. "thread.");
  952. ffmpeg_output_full_stop(output);
  953. return false;
  954. }
  955. obs_output_set_video_conversion(output->output, NULL);
  956. obs_output_set_audio_conversion(output->output, &aci);
  957. obs_output_begin_data_capture(output->output, 0);
  958. output->write_thread_active = true;
  959. return true;
  960. }
  961. static void *start_thread(void *data)
  962. {
  963. struct ffmpeg_output *output = data;
  964. if (!try_connect(output))
  965. obs_output_signal_stop(output->output,
  966. OBS_OUTPUT_CONNECT_FAILED);
  967. output->connecting = false;
  968. return NULL;
  969. }
  970. static bool ffmpeg_output_start(void *data)
  971. {
  972. struct ffmpeg_output *output = data;
  973. int ret;
  974. if (output->connecting)
  975. return false;
  976. os_atomic_set_bool(&output->stopping, false);
  977. output->audio_start_ts = 0;
  978. output->video_start_ts = 0;
  979. output->total_bytes = 0;
  980. ret = pthread_create(&output->start_thread, NULL, start_thread, output);
  981. return (output->connecting = (ret == 0));
  982. }
  983. static void ffmpeg_output_full_stop(void *data)
  984. {
  985. struct ffmpeg_output *output = data;
  986. if (output->active) {
  987. obs_output_end_data_capture(output->output);
  988. ffmpeg_deactivate(output);
  989. }
  990. }
  991. static void ffmpeg_output_stop(void *data, uint64_t ts)
  992. {
  993. struct ffmpeg_output *output = data;
  994. if (output->active) {
  995. if (ts > 0) {
  996. output->stop_ts = ts;
  997. os_atomic_set_bool(&output->stopping, true);
  998. }
  999. ffmpeg_output_full_stop(output);
  1000. }
  1001. }
  1002. static void ffmpeg_deactivate(struct ffmpeg_output *output)
  1003. {
  1004. if (output->write_thread_active) {
  1005. os_event_signal(output->stop_event);
  1006. os_sem_post(output->write_sem);
  1007. pthread_join(output->write_thread, NULL);
  1008. output->write_thread_active = false;
  1009. }
  1010. pthread_mutex_lock(&output->write_mutex);
  1011. for (size_t i = 0; i < output->packets.num; i++)
  1012. av_free_packet(output->packets.array + i);
  1013. da_free(output->packets);
  1014. pthread_mutex_unlock(&output->write_mutex);
  1015. ffmpeg_data_free(&output->ff_data);
  1016. }
  1017. static uint64_t ffmpeg_output_total_bytes(void *data)
  1018. {
  1019. struct ffmpeg_output *output = data;
  1020. return output->total_bytes;
  1021. }
  1022. struct obs_output_info ffmpeg_output = {
  1023. .id = "ffmpeg_output",
  1024. .flags = OBS_OUTPUT_AUDIO | OBS_OUTPUT_VIDEO | OBS_OUTPUT_MULTI_TRACK |
  1025. OBS_OUTPUT_CAN_PAUSE,
  1026. .get_name = ffmpeg_output_getname,
  1027. .create = ffmpeg_output_create,
  1028. .destroy = ffmpeg_output_destroy,
  1029. .start = ffmpeg_output_start,
  1030. .stop = ffmpeg_output_stop,
  1031. .raw_video = receive_video,
  1032. .raw_audio2 = receive_audio,
  1033. .get_total_bytes = ffmpeg_output_total_bytes,
  1034. };