obs-ffmpeg-output.c 30 KB

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