obs-ffmpeg-mpegts.c 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain 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. #include "obs-ffmpeg-rist.h"
  24. #include "obs-ffmpeg-srt.h"
  25. #include <libavutil/channel_layout.h>
  26. #include <libavutil/mastering_display_metadata.h>
  27. /* ------------------------------------------------------------------------- */
  28. #define do_log(level, format, ...) \
  29. blog(level, "[obs-ffmpeg mpegts muxer: '%s']: " format, \
  30. obs_output_get_name(stream->output), ##__VA_ARGS__)
  31. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  32. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  33. #define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__)
  34. static void ffmpeg_mpegts_set_last_error(struct ffmpeg_data *data,
  35. const char *error)
  36. {
  37. if (data->last_error)
  38. bfree(data->last_error);
  39. data->last_error = bstrdup(error);
  40. }
  41. void ffmpeg_mpegts_log_error(int log_level, struct ffmpeg_data *data,
  42. const char *format, ...)
  43. {
  44. va_list args;
  45. char out[4096];
  46. va_start(args, format);
  47. vsnprintf(out, sizeof(out), format, args);
  48. va_end(args);
  49. ffmpeg_mpegts_set_last_error(data, out);
  50. blog(log_level, "%s", out);
  51. }
  52. static bool is_rist(struct ffmpeg_output *stream)
  53. {
  54. return !strncmp(stream->ff_data.config.url, RIST_PROTO,
  55. sizeof(RIST_PROTO) - 1);
  56. }
  57. static bool is_srt(struct ffmpeg_output *stream)
  58. {
  59. return !strncmp(stream->ff_data.config.url, SRT_PROTO,
  60. sizeof(SRT_PROTO) - 1);
  61. }
  62. static bool proto_is_allowed(struct ffmpeg_output *stream)
  63. {
  64. return !strncmp(stream->ff_data.config.url, UDP_PROTO,
  65. sizeof(UDP_PROTO) - 1) ||
  66. !strncmp(stream->ff_data.config.url, TCP_PROTO,
  67. sizeof(TCP_PROTO) - 1) ||
  68. !strncmp(stream->ff_data.config.url, HTTP_PROTO,
  69. sizeof(HTTP_PROTO) - 1);
  70. }
  71. static bool new_stream(struct ffmpeg_data *data, AVStream **stream,
  72. const char *name)
  73. {
  74. *stream = avformat_new_stream(data->output, NULL);
  75. if (!*stream) {
  76. ffmpeg_mpegts_log_error(
  77. LOG_WARNING, data,
  78. "Couldn't create stream for encoder '%s'", name);
  79. return false;
  80. }
  81. (*stream)->id = data->output->nb_streams - 1;
  82. return true;
  83. }
  84. static bool get_audio_headers(struct ffmpeg_output *stream,
  85. struct ffmpeg_data *data, int idx)
  86. {
  87. AVCodecParameters *par = data->audio_infos[idx].stream->codecpar;
  88. obs_encoder_t *aencoder =
  89. obs_output_get_audio_encoder(stream->output, idx);
  90. struct encoder_packet packet = {.type = OBS_ENCODER_AUDIO,
  91. .timebase_den = 1,
  92. .track_idx = idx};
  93. if (obs_encoder_get_extra_data(aencoder, &packet.data, &packet.size)) {
  94. par->extradata = av_memdup(packet.data, packet.size);
  95. par->extradata_size = (int)packet.size;
  96. avcodec_parameters_to_context(data->audio_infos[idx].ctx, par);
  97. return 1;
  98. }
  99. return 0;
  100. }
  101. static bool get_video_headers(struct ffmpeg_output *stream,
  102. struct ffmpeg_data *data)
  103. {
  104. AVCodecParameters *par = data->video->codecpar;
  105. obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output);
  106. struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO,
  107. .timebase_den = 1};
  108. if (obs_encoder_get_extra_data(vencoder, &packet.data, &packet.size)) {
  109. par->extradata = av_memdup(packet.data, packet.size);
  110. par->extradata_size = (int)packet.size;
  111. avcodec_parameters_to_context(data->video_ctx,
  112. data->video->codecpar);
  113. return 1;
  114. }
  115. return 0;
  116. }
  117. static bool create_video_stream(struct ffmpeg_output *stream,
  118. struct ffmpeg_data *data)
  119. {
  120. AVCodecContext *context;
  121. struct obs_video_info ovi;
  122. if (!obs_get_video_info(&ovi)) {
  123. ffmpeg_mpegts_log_error(LOG_WARNING, data, "No active video");
  124. return false;
  125. }
  126. const char *name = data->config.video_encoder;
  127. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  128. if (!codec) {
  129. error("Couldn't find codec '%s'", name);
  130. return false;
  131. }
  132. if (!new_stream(data, &data->video, name))
  133. return false;
  134. const bool pq = data->config.color_trc == AVCOL_TRC_SMPTE2084;
  135. const bool hlg = data->config.color_trc == AVCOL_TRC_ARIB_STD_B67;
  136. if (pq || hlg) {
  137. const int hdr_nominal_peak_level =
  138. pq ? (int)obs_get_video_hdr_nominal_peak_level()
  139. : (hlg ? 1000 : 0);
  140. size_t content_size;
  141. AVContentLightMetadata *const content =
  142. av_content_light_metadata_alloc(&content_size);
  143. content->MaxCLL = hdr_nominal_peak_level;
  144. content->MaxFALL = hdr_nominal_peak_level;
  145. av_stream_add_side_data(data->video,
  146. AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
  147. (uint8_t *)content, content_size);
  148. AVMasteringDisplayMetadata *const mastering =
  149. av_mastering_display_metadata_alloc();
  150. mastering->display_primaries[0][0] = av_make_q(17, 25);
  151. mastering->display_primaries[0][1] = av_make_q(8, 25);
  152. mastering->display_primaries[1][0] = av_make_q(53, 200);
  153. mastering->display_primaries[1][1] = av_make_q(69, 100);
  154. mastering->display_primaries[2][0] = av_make_q(3, 20);
  155. mastering->display_primaries[2][1] = av_make_q(3, 50);
  156. mastering->white_point[0] = av_make_q(3127, 10000);
  157. mastering->white_point[1] = av_make_q(329, 1000);
  158. mastering->min_luminance = av_make_q(0, 1);
  159. mastering->max_luminance = av_make_q(hdr_nominal_peak_level, 1);
  160. mastering->has_primaries = 1;
  161. mastering->has_luminance = 1;
  162. av_stream_add_side_data(data->video,
  163. AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  164. (uint8_t *)mastering,
  165. sizeof(*mastering));
  166. }
  167. context = avcodec_alloc_context3(NULL);
  168. context->codec_type = codec->type;
  169. context->codec_id = codec->id;
  170. context->bit_rate = (int64_t)data->config.video_bitrate * 1000;
  171. context->width = data->config.scale_width;
  172. context->height = data->config.scale_height;
  173. context->coded_width = data->config.scale_width;
  174. context->coded_height = data->config.scale_height;
  175. context->time_base = (AVRational){ovi.fps_den, ovi.fps_num};
  176. context->gop_size = data->config.gop_size;
  177. context->pix_fmt = data->config.format;
  178. context->color_range = data->config.color_range;
  179. context->color_primaries = data->config.color_primaries;
  180. context->color_trc = data->config.color_trc;
  181. context->colorspace = data->config.colorspace;
  182. context->chroma_sample_location = determine_chroma_location(
  183. data->config.format, data->config.colorspace);
  184. context->thread_count = 0;
  185. data->video->time_base = context->time_base;
  186. #if LIBAVFORMAT_VERSION_MAJOR < 59
  187. data->video->codec->time_base = context->time_base;
  188. #endif
  189. data->video->avg_frame_rate = av_inv_q(context->time_base);
  190. data->video_ctx = context;
  191. data->config.width = data->config.scale_width;
  192. data->config.height = data->config.scale_height;
  193. avcodec_parameters_from_context(data->video->codecpar, context);
  194. return true;
  195. }
  196. static bool create_audio_stream(struct ffmpeg_output *stream,
  197. struct ffmpeg_data *data, int idx)
  198. {
  199. AVCodecContext *context;
  200. AVStream *avstream;
  201. struct obs_audio_info aoi;
  202. const char *name = data->config.audio_encoder;
  203. int channels;
  204. const AVCodecDescriptor *codec = avcodec_descriptor_get_by_name(name);
  205. if (!codec) {
  206. warn("Couldn't find codec '%s'", name);
  207. return false;
  208. }
  209. if (!obs_get_audio_info(&aoi)) {
  210. ffmpeg_mpegts_log_error(LOG_WARNING, data, "No active audio");
  211. return false;
  212. }
  213. if (!new_stream(data, &avstream, data->config.audio_encoder))
  214. return false;
  215. context = avcodec_alloc_context3(NULL);
  216. context->codec_type = codec->type;
  217. context->codec_id = codec->id;
  218. context->bit_rate = (int64_t)data->config.audio_bitrate * 1000;
  219. context->time_base = (AVRational){1, aoi.samples_per_sec};
  220. channels = get_audio_channels(aoi.speakers);
  221. #if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(57, 24, 100)
  222. context->channels = get_audio_channels(aoi.speakers);
  223. #endif
  224. context->sample_rate = aoi.samples_per_sec;
  225. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59, 24, 100)
  226. context->channel_layout =
  227. av_get_default_channel_layout(context->channels);
  228. //avutil default channel layout for 5 channels is 5.0 ; fix for 4.1
  229. if (aoi.speakers == SPEAKERS_4POINT1)
  230. context->channel_layout = av_get_channel_layout("4.1");
  231. #else
  232. av_channel_layout_default(&context->ch_layout, channels);
  233. if (aoi.speakers == SPEAKERS_4POINT1)
  234. context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1;
  235. #endif
  236. context->sample_fmt = AV_SAMPLE_FMT_S16;
  237. context->frame_size = data->config.frame_size;
  238. avstream->time_base = context->time_base;
  239. data->audio_samplerate = aoi.samples_per_sec;
  240. data->audio_format = convert_ffmpeg_sample_format(context->sample_fmt);
  241. data->audio_planes = get_audio_planes(data->audio_format, aoi.speakers);
  242. data->audio_size = get_audio_size(data->audio_format, aoi.speakers, 1);
  243. data->audio_infos[idx].stream = avstream;
  244. data->audio_infos[idx].ctx = context;
  245. avcodec_parameters_from_context(data->audio_infos[idx].stream->codecpar,
  246. context);
  247. return true;
  248. }
  249. static inline bool init_streams(struct ffmpeg_output *stream,
  250. struct ffmpeg_data *data)
  251. {
  252. if (!create_video_stream(stream, data))
  253. return false;
  254. if (data->num_audio_streams) {
  255. data->audio_infos = calloc(data->num_audio_streams,
  256. sizeof(*data->audio_infos));
  257. for (int i = 0; i < data->num_audio_streams; i++) {
  258. if (!create_audio_stream(stream, data, i))
  259. return false;
  260. }
  261. }
  262. return true;
  263. }
  264. int ff_network_init(void)
  265. {
  266. #if HAVE_WINSOCK2_H
  267. WSADATA wsaData;
  268. if (WSAStartup(MAKEWORD(1, 1), &wsaData))
  269. return 0;
  270. #endif
  271. return 1;
  272. }
  273. static inline int connect_mpegts_url(struct ffmpeg_output *stream, bool is_rist)
  274. {
  275. int err = 0;
  276. const char *url = stream->ff_data.config.url;
  277. if (!ff_network_init()) {
  278. ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data,
  279. "Couldn't initialize network");
  280. return AVERROR(EIO);
  281. }
  282. URLContext *uc = av_mallocz(sizeof(URLContext) + strlen(url) + 1);
  283. if (!uc) {
  284. ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data,
  285. "Couldn't allocate memory");
  286. goto fail;
  287. }
  288. uc->url = (char *)url;
  289. uc->max_packet_size = is_rist ? RIST_MAX_PAYLOAD_SIZE
  290. : SRT_LIVE_DEFAULT_PAYLOAD_SIZE;
  291. uc->priv_data = is_rist ? av_mallocz(sizeof(RISTContext))
  292. : av_mallocz(sizeof(SRTContext));
  293. if (!uc->priv_data) {
  294. ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data,
  295. "Couldn't allocate memory");
  296. goto fail;
  297. }
  298. /* For SRT, pass streamid & passphrase; for RIST, pass passphrase, username
  299. * & password.
  300. */
  301. if (!is_rist) {
  302. SRTContext *context = (SRTContext *)uc->priv_data;
  303. context->streamid = NULL;
  304. if (stream->ff_data.config.stream_id != NULL) {
  305. if (strlen(stream->ff_data.config.stream_id))
  306. context->streamid = av_strdup(
  307. stream->ff_data.config.stream_id);
  308. }
  309. context->passphrase = NULL;
  310. if (stream->ff_data.config.encrypt_passphrase != NULL) {
  311. if (strlen(stream->ff_data.config.encrypt_passphrase))
  312. context->passphrase =
  313. av_strdup(stream->ff_data.config
  314. .encrypt_passphrase);
  315. }
  316. } else {
  317. RISTContext *context = (RISTContext *)uc->priv_data;
  318. context->secret = NULL;
  319. if (stream->ff_data.config.encrypt_passphrase != NULL) {
  320. if (strlen(stream->ff_data.config.encrypt_passphrase))
  321. context->secret =
  322. bstrdup(stream->ff_data.config
  323. .encrypt_passphrase);
  324. }
  325. context->username = NULL;
  326. if (stream->ff_data.config.username != NULL) {
  327. if (strlen(stream->ff_data.config.username))
  328. context->username = bstrdup(
  329. stream->ff_data.config.username);
  330. }
  331. context->password = NULL;
  332. if (stream->ff_data.config.password != NULL) {
  333. if (strlen(stream->ff_data.config.password))
  334. context->password = bstrdup(
  335. stream->ff_data.config.password);
  336. }
  337. }
  338. stream->h = uc;
  339. if (is_rist)
  340. err = librist_open(uc, uc->url);
  341. else
  342. err = libsrt_open(uc, uc->url);
  343. if (err < 0)
  344. goto fail;
  345. return 0;
  346. fail:
  347. if (uc)
  348. av_freep(&uc->priv_data);
  349. av_freep(&uc);
  350. #if HAVE_WINSOCK2_H
  351. WSACleanup();
  352. #endif
  353. return err;
  354. }
  355. static inline int allocate_custom_aviocontext(struct ffmpeg_output *stream,
  356. bool is_rist)
  357. {
  358. /* allocate buffers */
  359. uint8_t *buffer = NULL;
  360. int buffer_size;
  361. URLContext *h = stream->h;
  362. AVIOContext *s = NULL;
  363. buffer_size = UDP_DEFAULT_PAYLOAD_SIZE;
  364. buffer = av_malloc(buffer_size);
  365. if (!buffer)
  366. return AVERROR(ENOMEM);
  367. /* allocate custom avio_context */
  368. if (is_rist)
  369. s = avio_alloc_context(
  370. buffer, buffer_size, AVIO_FLAG_WRITE, h, NULL,
  371. (int (*)(void *, uint8_t *, int))librist_write, NULL);
  372. else
  373. s = avio_alloc_context(
  374. buffer, buffer_size, AVIO_FLAG_WRITE, h, NULL,
  375. (int (*)(void *, uint8_t *, int))libsrt_write, NULL);
  376. if (!s)
  377. goto fail;
  378. s->max_packet_size = h->max_packet_size;
  379. s->opaque = h;
  380. stream->s = s;
  381. stream->ff_data.output->pb = s;
  382. return 0;
  383. fail:
  384. av_freep(&buffer);
  385. return AVERROR(ENOMEM);
  386. }
  387. static inline int open_output_file(struct ffmpeg_output *stream,
  388. struct ffmpeg_data *data)
  389. {
  390. int ret;
  391. bool rist = is_rist(stream);
  392. bool srt = is_srt(stream);
  393. bool allowed_proto = proto_is_allowed(stream);
  394. AVDictionary *dict = NULL;
  395. /* Retrieve protocol settings for udp, tcp, rtp ... (not srt or rist).
  396. * These options will be passed to protocol by avio_open2 through dict.
  397. * The invalid options will be left in dict. */
  398. if (!rist && !srt) {
  399. if ((ret = av_dict_parse_string(&dict,
  400. data->config.protocol_settings,
  401. "=", " ", 0))) {
  402. ffmpeg_mpegts_log_error(
  403. LOG_WARNING, data,
  404. "Failed to parse protocol settings: %s, %s",
  405. data->config.protocol_settings,
  406. av_err2str(ret));
  407. av_dict_free(&dict);
  408. return OBS_OUTPUT_INVALID_STREAM;
  409. }
  410. if (av_dict_count(dict) > 0) {
  411. struct dstr str = {0};
  412. AVDictionaryEntry *entry = NULL;
  413. while ((entry = av_dict_get(dict, "", entry,
  414. AV_DICT_IGNORE_SUFFIX)))
  415. dstr_catf(&str, "\n\t%s=%s", entry->key,
  416. entry->value);
  417. info("Using protocol settings: %s", str.array);
  418. dstr_free(&str);
  419. }
  420. }
  421. /* Ensure h264 bitstream auto conversion from avcc to annex B */
  422. data->output->flags |= AVFMT_FLAG_AUTO_BSF;
  423. /* Open URL for rist, srt or other protocols compatible with mpegts
  424. * muxer supported by avformat (udp, tcp, rtp ...).
  425. */
  426. if (rist) {
  427. ret = connect_mpegts_url(stream, true);
  428. } else if (srt) {
  429. ret = connect_mpegts_url(stream, false);
  430. } else if (allowed_proto) {
  431. ret = avio_open2(&data->output->pb, data->config.url,
  432. AVIO_FLAG_WRITE, NULL, &dict);
  433. } else {
  434. info("[ffmpeg mpegts muxer]: Invalid protocol: %s",
  435. data->config.url);
  436. return OBS_OUTPUT_BAD_PATH;
  437. }
  438. if (ret < 0) {
  439. if ((rist || srt) && (ret == OBS_OUTPUT_CONNECT_FAILED ||
  440. ret == OBS_OUTPUT_INVALID_STREAM)) {
  441. error("Failed to open the url or invalid stream");
  442. } else {
  443. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  444. "Couldn't open '%s', %s",
  445. data->config.url,
  446. av_err2str(ret));
  447. av_dict_free(&dict);
  448. }
  449. return ret;
  450. }
  451. /* Log invalid protocol settings for all protocols except srt or rist.
  452. * Or for srt & rist, allocate custom avio_ctx which will host the
  453. * protocols write callbacks.
  454. */
  455. if (!rist && !srt) {
  456. if (av_dict_count(dict) > 0) {
  457. struct dstr str = {0};
  458. AVDictionaryEntry *entry = NULL;
  459. while ((entry = av_dict_get(dict, "", entry,
  460. AV_DICT_IGNORE_SUFFIX)))
  461. dstr_catf(&str, "\n\t%s=%s", entry->key,
  462. entry->value);
  463. info("[ffmpeg mpegts muxer]: Invalid protocol settings: %s",
  464. str.array);
  465. dstr_free(&str);
  466. }
  467. av_dict_free(&dict);
  468. } else {
  469. ret = allocate_custom_aviocontext(stream, rist);
  470. if (ret < 0) {
  471. info("Couldn't allocate custom avio_context for url: '%s', %s",
  472. data->config.url, av_err2str(ret));
  473. return OBS_OUTPUT_INVALID_STREAM;
  474. }
  475. }
  476. return 0;
  477. }
  478. static void close_video(struct ffmpeg_data *data)
  479. {
  480. avcodec_free_context(&data->video_ctx);
  481. }
  482. static void close_audio(struct ffmpeg_data *data)
  483. {
  484. for (int idx = 0; idx < data->num_audio_streams; idx++) {
  485. for (size_t i = 0; i < MAX_AV_PLANES; i++)
  486. circlebuf_free(&data->excess_frames[idx][i]);
  487. if (data->samples[idx][0])
  488. av_freep(&data->samples[idx][0]);
  489. if (data->audio_infos[idx].ctx) {
  490. avcodec_free_context(&data->audio_infos[idx].ctx);
  491. }
  492. if (data->aframe[idx])
  493. av_frame_free(&data->aframe[idx]);
  494. }
  495. }
  496. static void close_mpegts_url(struct ffmpeg_output *stream, bool is_rist)
  497. {
  498. int err = 0;
  499. AVIOContext *s = stream->s;
  500. if (!s)
  501. return;
  502. URLContext *h = s->opaque;
  503. if (!h)
  504. return; /* can happen when opening the url fails */
  505. /* close rist or srt URLs ; free URLContext */
  506. if (is_rist) {
  507. err = librist_close(h);
  508. } else {
  509. err = libsrt_close(h);
  510. }
  511. av_freep(&h->priv_data);
  512. av_freep(h);
  513. /* close custom avio_context for srt or rist */
  514. avio_flush(stream->s);
  515. stream->s->opaque = NULL;
  516. av_freep(&stream->s->buffer);
  517. avio_context_free(&stream->s);
  518. if (err)
  519. info("[ffmpeg mpegts muxer]: Error closing URL %s",
  520. stream->ff_data.config.url);
  521. }
  522. void ffmpeg_mpegts_data_free(struct ffmpeg_output *stream,
  523. struct ffmpeg_data *data)
  524. {
  525. if (data->initialized)
  526. av_write_trailer(data->output);
  527. if (data->video)
  528. close_video(data);
  529. if (data->audio_infos) {
  530. close_audio(data);
  531. free(data->audio_infos);
  532. }
  533. if (data->output) {
  534. if (is_rist(stream) || is_srt(stream)) {
  535. close_mpegts_url(stream, is_rist(stream));
  536. } else {
  537. avio_close(data->output->pb);
  538. }
  539. avformat_free_context(data->output);
  540. data->video = NULL;
  541. data->audio_infos = NULL;
  542. data->output = NULL;
  543. data->num_audio_streams = 0;
  544. }
  545. if (data->last_error)
  546. bfree(data->last_error);
  547. memset(data, 0, sizeof(struct ffmpeg_data));
  548. }
  549. static inline const char *safe_str(const char *s)
  550. {
  551. if (s == NULL)
  552. return "(NULL)";
  553. else
  554. return s;
  555. }
  556. bool ffmpeg_mpegts_data_init(struct ffmpeg_output *stream,
  557. struct ffmpeg_data *data,
  558. struct ffmpeg_cfg *config)
  559. {
  560. memset(data, 0, sizeof(struct ffmpeg_data));
  561. data->config = *config;
  562. data->num_audio_streams = config->audio_mix_count;
  563. data->audio_tracks = config->audio_tracks;
  564. if (!config->url || !*config->url)
  565. return false;
  566. avformat_network_init();
  567. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59, 0, 100)
  568. AVOutputFormat *output_format;
  569. #else
  570. const AVOutputFormat *output_format;
  571. #endif
  572. output_format = av_guess_format("mpegts", NULL, "video/M2PT");
  573. if (output_format == NULL) {
  574. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  575. "Couldn't set output format to mpegts");
  576. goto fail;
  577. } else {
  578. info("Output format name and long_name: %s, %s",
  579. output_format->name ? output_format->name : "unknown",
  580. output_format->long_name ? output_format->long_name
  581. : "unknown");
  582. }
  583. avformat_alloc_output_context2(&data->output, output_format, NULL,
  584. data->config.url);
  585. if (!data->output) {
  586. ffmpeg_mpegts_log_error(LOG_WARNING, data,
  587. "Couldn't create avformat context");
  588. goto fail;
  589. }
  590. return true;
  591. fail:
  592. warn("ffmpeg_data_init failed");
  593. return false;
  594. }
  595. /* ------------------------------------------------------------------------- */
  596. static inline bool stopping(struct ffmpeg_output *output)
  597. {
  598. return os_atomic_load_bool(&output->stopping);
  599. }
  600. static const char *ffmpeg_mpegts_getname(void *unused)
  601. {
  602. UNUSED_PARAMETER(unused);
  603. return obs_module_text("FFmpegMpegts");
  604. }
  605. static void ffmpeg_mpegts_log_callback(void *param, int level,
  606. const char *format, va_list args)
  607. {
  608. if (level <= AV_LOG_INFO)
  609. blogva(LOG_DEBUG, format, args);
  610. UNUSED_PARAMETER(param);
  611. }
  612. static void *ffmpeg_mpegts_create(obs_data_t *settings, obs_output_t *output)
  613. {
  614. struct ffmpeg_output *data = bzalloc(sizeof(struct ffmpeg_output));
  615. pthread_mutex_init_value(&data->write_mutex);
  616. data->output = output;
  617. if (pthread_mutex_init(&data->write_mutex, NULL) != 0)
  618. goto fail;
  619. if (os_event_init(&data->stop_event, OS_EVENT_TYPE_AUTO) != 0)
  620. goto fail;
  621. if (os_sem_init(&data->write_sem, 0) != 0)
  622. goto fail;
  623. av_log_set_callback(ffmpeg_mpegts_log_callback);
  624. UNUSED_PARAMETER(settings);
  625. return data;
  626. fail:
  627. pthread_mutex_destroy(&data->write_mutex);
  628. os_event_destroy(data->stop_event);
  629. bfree(data);
  630. return NULL;
  631. }
  632. static void ffmpeg_mpegts_full_stop(void *data);
  633. static void ffmpeg_mpegts_deactivate(struct ffmpeg_output *output);
  634. static void ffmpeg_mpegts_destroy(void *data)
  635. {
  636. struct ffmpeg_output *output = data;
  637. if (output) {
  638. if (output->connecting)
  639. pthread_join(output->start_thread, NULL);
  640. ffmpeg_mpegts_full_stop(output);
  641. pthread_mutex_destroy(&output->write_mutex);
  642. os_sem_destroy(output->write_sem);
  643. os_event_destroy(output->stop_event);
  644. bfree(data);
  645. }
  646. }
  647. static uint64_t get_packet_sys_dts(struct ffmpeg_output *output,
  648. AVPacket *packet)
  649. {
  650. struct ffmpeg_data *data = &output->ff_data;
  651. uint64_t pause_offset = obs_output_get_pause_offset(output->output);
  652. uint64_t start_ts;
  653. AVRational time_base;
  654. if (data->video && data->video->index == packet->stream_index) {
  655. time_base = data->video->time_base;
  656. start_ts = output->video_start_ts;
  657. } else {
  658. time_base = data->audio_infos[0].stream->time_base;
  659. start_ts = output->audio_start_ts;
  660. }
  661. return start_ts + pause_offset +
  662. (uint64_t)av_rescale_q(packet->dts, time_base,
  663. (AVRational){1, 1000000000});
  664. }
  665. static int mpegts_process_packet(struct ffmpeg_output *output)
  666. {
  667. AVPacket *packet = NULL;
  668. int ret = 0;
  669. pthread_mutex_lock(&output->write_mutex);
  670. if (output->packets.num) {
  671. packet = output->packets.array[0];
  672. da_erase(output->packets, 0);
  673. }
  674. pthread_mutex_unlock(&output->write_mutex);
  675. if (!packet)
  676. return 0;
  677. //blog(LOG_DEBUG,
  678. // "size = %d, flags = %lX, stream = %d, "
  679. // "packets queued: %lu",
  680. // packet->size, packet->flags, packet->stream_index,
  681. // output->packets.num);
  682. if (stopping(output)) {
  683. uint64_t sys_ts = get_packet_sys_dts(output, packet);
  684. if (sys_ts >= output->stop_ts) {
  685. ret = 0;
  686. goto end;
  687. }
  688. }
  689. output->total_bytes += packet->size;
  690. uint8_t *buf = packet->data;
  691. ret = av_interleaved_write_frame(output->ff_data.output, packet);
  692. av_freep(&buf);
  693. if (ret < 0) {
  694. ffmpeg_mpegts_log_error(
  695. LOG_WARNING, &output->ff_data,
  696. "process_packet: Error writing packet: %s",
  697. av_err2str(ret));
  698. /* Treat "Invalid data found when processing input" and
  699. * "Invalid argument" as non-fatal */
  700. if (ret == AVERROR_INVALIDDATA || ret == -EINVAL) {
  701. ret = 0;
  702. }
  703. }
  704. end:
  705. av_packet_free(&packet);
  706. return ret;
  707. }
  708. static void *write_thread(void *data)
  709. {
  710. struct ffmpeg_output *output = data;
  711. while (os_sem_wait(output->write_sem) == 0) {
  712. /* check to see if shutting down */
  713. if (os_event_try(output->stop_event) == 0)
  714. break;
  715. int ret = mpegts_process_packet(output);
  716. if (ret != 0) {
  717. int code = OBS_OUTPUT_DISCONNECTED;
  718. pthread_detach(output->write_thread);
  719. output->write_thread_active = false;
  720. if (ret == -ENOSPC)
  721. code = OBS_OUTPUT_NO_SPACE;
  722. obs_output_signal_stop(output->output, code);
  723. ffmpeg_mpegts_deactivate(output);
  724. break;
  725. }
  726. }
  727. os_atomic_set_bool(&output->active, false);
  728. return NULL;
  729. }
  730. static bool get_extradata(struct ffmpeg_output *stream)
  731. {
  732. struct ffmpeg_data *ff_data = &stream->ff_data;
  733. /* get extradata for av headers from encoders */
  734. if (!get_video_headers(stream, ff_data))
  735. return false;
  736. for (int i = 0; i < ff_data->num_audio_streams; i++) {
  737. if (!get_audio_headers(stream, ff_data, i))
  738. return false;
  739. }
  740. return true;
  741. }
  742. /* set ffmpeg_config & init write_thread & capture */
  743. static bool set_config(struct ffmpeg_output *stream)
  744. {
  745. struct ffmpeg_cfg config;
  746. bool success;
  747. int ret;
  748. int code;
  749. /* 1. Get URL/username/password from service & set format + mime-type. */
  750. obs_service_t *service;
  751. service = obs_output_get_service(stream->output);
  752. if (!service)
  753. return false;
  754. config.url = obs_service_get_connect_info(
  755. service, OBS_SERVICE_CONNECT_INFO_SERVER_URL);
  756. config.username = obs_service_get_connect_info(
  757. service, OBS_SERVICE_CONNECT_INFO_USERNAME);
  758. config.password = obs_service_get_connect_info(
  759. service, OBS_SERVICE_CONNECT_INFO_PASSWORD);
  760. config.stream_id = obs_service_get_connect_info(
  761. service, OBS_SERVICE_CONNECT_INFO_STREAM_ID);
  762. config.encrypt_passphrase = obs_service_get_connect_info(
  763. service, OBS_SERVICE_CONNECT_INFO_ENCRYPT_PASSPHRASE);
  764. config.format_name = "mpegts";
  765. config.format_mime_type = "video/M2PT";
  766. /* 2. video settings */
  767. // 2.a) set video format from obs to FFmpeg
  768. video_t *video = obs_output_video(stream->output);
  769. config.format =
  770. obs_to_ffmpeg_video_format(video_output_get_format(video));
  771. if (config.format == AV_PIX_FMT_NONE) {
  772. blog(LOG_WARNING,
  773. "Invalid pixel format used for mpegts output");
  774. return false;
  775. }
  776. // 2.b) set colorspace, color_range & transfer characteristic (from voi)
  777. const struct video_output_info *voi = video_output_get_info(video);
  778. config.color_range = voi->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG
  779. : AVCOL_RANGE_MPEG;
  780. config.colorspace = format_is_yuv(voi->format) ? AVCOL_SPC_BT709
  781. : AVCOL_SPC_RGB;
  782. switch (voi->colorspace) {
  783. case VIDEO_CS_601:
  784. config.color_primaries = AVCOL_PRI_SMPTE170M;
  785. config.color_trc = AVCOL_TRC_SMPTE170M;
  786. config.colorspace = AVCOL_SPC_SMPTE170M;
  787. break;
  788. case VIDEO_CS_DEFAULT:
  789. case VIDEO_CS_709:
  790. config.color_primaries = AVCOL_PRI_BT709;
  791. config.color_trc = AVCOL_TRC_BT709;
  792. config.colorspace = AVCOL_SPC_BT709;
  793. break;
  794. case VIDEO_CS_SRGB:
  795. config.color_primaries = AVCOL_PRI_BT709;
  796. config.color_trc = AVCOL_TRC_IEC61966_2_1;
  797. config.colorspace = AVCOL_SPC_BT709;
  798. break;
  799. case VIDEO_CS_2100_PQ:
  800. config.color_primaries = AVCOL_PRI_BT2020;
  801. config.color_trc = AVCOL_TRC_SMPTE2084;
  802. config.colorspace = AVCOL_SPC_BT2020_NCL;
  803. break;
  804. case VIDEO_CS_2100_HLG:
  805. config.color_primaries = AVCOL_PRI_BT2020;
  806. config.color_trc = AVCOL_TRC_ARIB_STD_B67;
  807. config.colorspace = AVCOL_SPC_BT2020_NCL;
  808. }
  809. // 2.c) set width & height
  810. config.width = (int)obs_output_get_width(stream->output);
  811. config.height = (int)obs_output_get_height(stream->output);
  812. config.scale_width = config.width;
  813. config.scale_height = config.height;
  814. // 2.d) set video codec & id from video encoder
  815. obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output);
  816. config.video_encoder = obs_encoder_get_codec(vencoder);
  817. if (strcmp(config.video_encoder, "h264") == 0)
  818. config.video_encoder_id = AV_CODEC_ID_H264;
  819. else
  820. config.video_encoder_id = AV_CODEC_ID_AV1;
  821. // 2.e) set video bitrate & gop through video encoder settings
  822. obs_data_t *settings = obs_encoder_get_settings(vencoder);
  823. config.video_bitrate = (int)obs_data_get_int(settings, "bitrate");
  824. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  825. config.gop_size = keyint_sec ? keyint_sec * voi->fps_num / voi->fps_den
  826. : 250;
  827. obs_data_release(settings);
  828. /* 3. Audio settings */
  829. // 3.a) set audio codec & id from audio encoder
  830. obs_encoder_t *aencoder =
  831. obs_output_get_audio_encoder(stream->output, 0);
  832. config.audio_encoder = obs_encoder_get_codec(aencoder);
  833. if (strcmp(config.audio_encoder, "aac") == 0)
  834. config.audio_encoder_id = AV_CODEC_ID_AAC;
  835. else if (strcmp(config.audio_encoder, "opus") == 0)
  836. config.audio_encoder_id = AV_CODEC_ID_OPUS;
  837. // 3.b) get audio bitrate from the audio encoder.
  838. settings = obs_encoder_get_settings(aencoder);
  839. config.audio_bitrate = (int)obs_data_get_int(settings, "bitrate");
  840. obs_data_release(settings);
  841. // 3.c set audio frame size
  842. config.frame_size = (int)obs_encoder_get_frame_size(aencoder);
  843. // 3.d) set the number of tracks
  844. // The UI for multiple tracks is not written for streaming outputs.
  845. // When it is, modify write_packet & uncomment :
  846. // config.audio_tracks = (int)obs_output_get_mixers(stream->output);
  847. // config.audio_mix_count = get_audio_mix_count(config.audio_tracks);
  848. config.audio_tracks = 1;
  849. config.audio_mix_count = 1;
  850. /* 4. Muxer & protocol settings */
  851. // This requires some UI to be written for the output.
  852. // at the service level unless one can load the output in the settings/stream screen.
  853. settings = obs_output_get_settings(stream->output);
  854. obs_data_set_default_string(settings, "muxer_settings", "");
  855. config.muxer_settings = obs_data_get_string(settings, "muxer_settings");
  856. obs_data_release(settings);
  857. config.protocol_settings = "";
  858. /* 5. unused ffmpeg codec settings */
  859. config.video_settings = "";
  860. config.audio_settings = "";
  861. success = ffmpeg_mpegts_data_init(stream, &stream->ff_data, &config);
  862. if (!success) {
  863. if (stream->ff_data.last_error) {
  864. obs_output_set_last_error(stream->output,
  865. stream->ff_data.last_error);
  866. }
  867. ffmpeg_mpegts_data_free(stream, &stream->ff_data);
  868. code = OBS_OUTPUT_INVALID_STREAM;
  869. goto fail;
  870. }
  871. struct ffmpeg_data *ff_data = &stream->ff_data;
  872. if (!stream->got_headers) {
  873. if (!init_streams(stream, ff_data)) {
  874. error("mpegts avstream failed to be created");
  875. code = OBS_OUTPUT_INVALID_STREAM;
  876. goto fail;
  877. }
  878. code = open_output_file(stream, ff_data);
  879. if (code != 0) {
  880. error("Failed to open the url");
  881. goto fail;
  882. }
  883. av_dump_format(ff_data->output, 0, NULL, 1);
  884. }
  885. if (!obs_output_can_begin_data_capture(stream->output, 0))
  886. return false;
  887. if (!obs_output_initialize_encoders(stream->output, 0))
  888. return false;
  889. ret = pthread_create(&stream->write_thread, NULL, write_thread, stream);
  890. if (ret != 0) {
  891. ffmpeg_mpegts_log_error(
  892. LOG_WARNING, &stream->ff_data,
  893. "ffmpeg_output_start: Failed to create write "
  894. "thread.");
  895. code = OBS_OUTPUT_ERROR;
  896. goto fail;
  897. }
  898. os_atomic_set_bool(&stream->active, true);
  899. stream->write_thread_active = true;
  900. stream->total_bytes = 0;
  901. obs_output_begin_data_capture(stream->output, 0);
  902. return true;
  903. fail:
  904. obs_output_signal_stop(stream->output, code);
  905. ffmpeg_mpegts_full_stop(stream);
  906. return false;
  907. }
  908. static void *start_thread(void *data)
  909. {
  910. struct ffmpeg_output *output = data;
  911. set_config(output);
  912. output->connecting = false;
  913. return NULL;
  914. }
  915. static bool ffmpeg_mpegts_start(void *data)
  916. {
  917. struct ffmpeg_output *output = data;
  918. int ret;
  919. if (output->connecting)
  920. return false;
  921. os_atomic_set_bool(&output->stopping, false);
  922. output->audio_start_ts = 0;
  923. output->video_start_ts = 0;
  924. output->total_bytes = 0;
  925. output->got_headers = false;
  926. ret = pthread_create(&output->start_thread, NULL, start_thread, output);
  927. return (output->connecting = (ret == 0));
  928. }
  929. static void ffmpeg_mpegts_full_stop(void *data)
  930. {
  931. struct ffmpeg_output *output = data;
  932. if (output->active) {
  933. obs_output_end_data_capture(output->output);
  934. ffmpeg_mpegts_deactivate(output);
  935. }
  936. }
  937. static void ffmpeg_mpegts_stop(void *data, uint64_t ts)
  938. {
  939. struct ffmpeg_output *output = data;
  940. if (output->active) {
  941. if (ts > 0) {
  942. output->stop_ts = ts;
  943. os_atomic_set_bool(&output->stopping, true);
  944. }
  945. ffmpeg_mpegts_full_stop(output);
  946. } else {
  947. obs_output_signal_stop(output->output, OBS_OUTPUT_SUCCESS);
  948. }
  949. }
  950. static void ffmpeg_mpegts_deactivate(struct ffmpeg_output *output)
  951. {
  952. if (output->write_thread_active) {
  953. os_event_signal(output->stop_event);
  954. os_sem_post(output->write_sem);
  955. pthread_join(output->write_thread, NULL);
  956. output->write_thread_active = false;
  957. }
  958. pthread_mutex_lock(&output->write_mutex);
  959. for (size_t i = 0; i < output->packets.num; i++)
  960. av_packet_free(output->packets.array + i);
  961. da_free(output->packets);
  962. pthread_mutex_unlock(&output->write_mutex);
  963. ffmpeg_mpegts_data_free(output, &output->ff_data);
  964. }
  965. static uint64_t ffmpeg_mpegts_total_bytes(void *data)
  966. {
  967. struct ffmpeg_output *output = data;
  968. return output->total_bytes;
  969. }
  970. static inline int64_t rescale_ts2(AVStream *stream, AVRational codec_time_base,
  971. int64_t val)
  972. {
  973. return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base,
  974. stream->time_base,
  975. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  976. }
  977. /* Convert obs encoder_packet to FFmpeg AVPacket and write to circular buffer
  978. * where it will be processed in the write_thread by process_packet.
  979. */
  980. void mpegts_write_packet(struct ffmpeg_output *stream,
  981. struct encoder_packet *encpacket)
  982. {
  983. if (stopping(stream) || !stream->ff_data.video ||
  984. !stream->ff_data.video_ctx || !stream->ff_data.audio_infos)
  985. return;
  986. if (!stream->ff_data.audio_infos[encpacket->track_idx].stream)
  987. return;
  988. bool is_video = encpacket->type == OBS_ENCODER_VIDEO;
  989. AVStream *avstream =
  990. is_video ? stream->ff_data.video
  991. : stream->ff_data.audio_infos[encpacket->track_idx]
  992. .stream;
  993. AVPacket *packet = NULL;
  994. const AVRational codec_time_base =
  995. is_video ? stream->ff_data.video_ctx->time_base
  996. : stream->ff_data.audio_infos[encpacket->track_idx]
  997. .ctx->time_base;
  998. packet = av_packet_alloc();
  999. packet->data = av_memdup(encpacket->data, (int)encpacket->size);
  1000. if (packet->data == NULL) {
  1001. error("Couldn't allocate packet data");
  1002. goto fail;
  1003. }
  1004. packet->size = (int)encpacket->size;
  1005. packet->stream_index = avstream->id;
  1006. packet->pts = rescale_ts2(avstream, codec_time_base, encpacket->pts);
  1007. packet->dts = rescale_ts2(avstream, codec_time_base, encpacket->dts);
  1008. if (encpacket->keyframe)
  1009. packet->flags = AV_PKT_FLAG_KEY;
  1010. pthread_mutex_lock(&stream->write_mutex);
  1011. da_push_back(stream->packets, &packet);
  1012. pthread_mutex_unlock(&stream->write_mutex);
  1013. os_sem_post(stream->write_sem);
  1014. return;
  1015. fail:
  1016. av_packet_free(&packet);
  1017. }
  1018. static bool write_header(struct ffmpeg_output *stream, struct ffmpeg_data *data)
  1019. {
  1020. AVDictionary *dict = NULL;
  1021. int ret;
  1022. /* get mpegts muxer settings (can be used with rist, srt, rtp, etc ... */
  1023. if ((ret = av_dict_parse_string(&dict, data->config.muxer_settings, "=",
  1024. " ", 0))) {
  1025. ffmpeg_mpegts_log_error(
  1026. LOG_WARNING, data,
  1027. "Failed to parse muxer settings: %s, %s",
  1028. data->config.muxer_settings, av_err2str(ret));
  1029. av_dict_free(&dict);
  1030. return false;
  1031. }
  1032. if (av_dict_count(dict) > 0) {
  1033. struct dstr str = {0};
  1034. AVDictionaryEntry *entry = NULL;
  1035. while ((entry = av_dict_get(dict, "", entry,
  1036. AV_DICT_IGNORE_SUFFIX)))
  1037. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  1038. info("Using muxer settings: %s", str.array);
  1039. dstr_free(&str);
  1040. }
  1041. /* Allocate the stream private data and write the stream header. */
  1042. ret = avformat_write_header(data->output, &dict);
  1043. if (ret < 0) {
  1044. ffmpeg_mpegts_log_error(
  1045. LOG_WARNING, data,
  1046. "Error setting stream header for '%s': %s",
  1047. data->config.url, av_err2str(ret));
  1048. return false;
  1049. }
  1050. /* Log invalid muxer settings. */
  1051. if (av_dict_count(dict) > 0) {
  1052. struct dstr str = {0};
  1053. AVDictionaryEntry *entry = NULL;
  1054. while ((entry = av_dict_get(dict, "", entry,
  1055. AV_DICT_IGNORE_SUFFIX)))
  1056. dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
  1057. info("[ffmpeg mpegts muxer]: Invalid mpegts muxer settings: %s",
  1058. str.array);
  1059. dstr_free(&str);
  1060. }
  1061. av_dict_free(&dict);
  1062. return true;
  1063. }
  1064. static void ffmpeg_mpegts_data(void *data, struct encoder_packet *packet)
  1065. {
  1066. struct ffmpeg_output *stream = data;
  1067. struct ffmpeg_data *ff_data = &stream->ff_data;
  1068. int code;
  1069. if (!stream->got_headers) {
  1070. if (get_extradata(stream)) {
  1071. stream->got_headers = true;
  1072. } else {
  1073. warn("Failed to retrieve headers");
  1074. code = OBS_OUTPUT_INVALID_STREAM;
  1075. goto fail;
  1076. }
  1077. if (!write_header(stream, ff_data)) {
  1078. error("Failed to write headers");
  1079. code = OBS_OUTPUT_INVALID_STREAM;
  1080. goto fail;
  1081. }
  1082. av_dump_format(ff_data->output, 0, NULL, 1);
  1083. ff_data->initialized = true;
  1084. }
  1085. if (!stream->active)
  1086. return;
  1087. /* encoder failure */
  1088. if (!packet) {
  1089. obs_output_signal_stop(stream->output, OBS_OUTPUT_ENCODE_ERROR);
  1090. ffmpeg_mpegts_deactivate(stream);
  1091. return;
  1092. }
  1093. if (stopping(stream)) {
  1094. if (packet->sys_dts_usec >= (int64_t)stream->stop_ts) {
  1095. ffmpeg_mpegts_deactivate(stream);
  1096. return;
  1097. }
  1098. }
  1099. mpegts_write_packet(stream, packet);
  1100. return;
  1101. fail:
  1102. obs_output_signal_stop(stream->output, code);
  1103. ffmpeg_mpegts_full_stop(stream);
  1104. }
  1105. static obs_properties_t *ffmpeg_mpegts_properties(void *unused)
  1106. {
  1107. UNUSED_PARAMETER(unused);
  1108. obs_properties_t *props = obs_properties_create();
  1109. obs_properties_add_text(props, "path", obs_module_text("FilePath"),
  1110. OBS_TEXT_DEFAULT);
  1111. return props;
  1112. }
  1113. struct obs_output_info ffmpeg_mpegts_muxer = {
  1114. .id = "ffmpeg_mpegts_muxer",
  1115. .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK |
  1116. OBS_OUTPUT_SERVICE,
  1117. .protocols = "SRT;RIST",
  1118. #ifdef ENABLE_HEVC
  1119. .encoded_video_codecs = "h264;hevc",
  1120. #else
  1121. .encoded_video_codecs = "h264",
  1122. #endif
  1123. .encoded_audio_codecs = "aac;opus",
  1124. .get_name = ffmpeg_mpegts_getname,
  1125. .create = ffmpeg_mpegts_create,
  1126. .destroy = ffmpeg_mpegts_destroy,
  1127. .start = ffmpeg_mpegts_start,
  1128. .stop = ffmpeg_mpegts_stop,
  1129. .encoded_packet = ffmpeg_mpegts_data,
  1130. .get_total_bytes = ffmpeg_mpegts_total_bytes,
  1131. .get_properties = ffmpeg_mpegts_properties,
  1132. };