ftl-stream.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. /******************************************************************************
  2. Copyright (C) 2017 by Quinn Damerell <[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 <obs-avc.h>
  16. #include <util/platform.h>
  17. #include <util/circlebuf.h>
  18. #include <util/dstr.h>
  19. #include <util/threading.h>
  20. #include <inttypes.h>
  21. #include "ftl.h"
  22. #include "flv-mux.h"
  23. #include "net-if.h"
  24. #ifdef _WIN32
  25. #include <Iphlpapi.h>
  26. #else
  27. #include <sys/ioctl.h>
  28. #define INFINITE 0xFFFFFFFF
  29. #endif
  30. #define do_log(level, format, ...) \
  31. blog(level, "[ftl stream: '%s'] " format, \
  32. obs_output_get_name(stream->output), ##__VA_ARGS__)
  33. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  34. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  35. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  36. #define OPT_DROP_THRESHOLD "drop_threshold_ms"
  37. #define OPT_MAX_SHUTDOWN_TIME_SEC "max_shutdown_time_sec"
  38. #define OPT_BIND_IP "bind_ip"
  39. typedef struct _nalu_t {
  40. int len;
  41. int dts_usec;
  42. int send_marker_bit;
  43. uint8_t *data;
  44. } nalu_t;
  45. typedef struct _frame_of_nalus_t {
  46. nalu_t nalus[100];
  47. int total;
  48. int complete_frame;
  49. } frame_of_nalus_t;
  50. struct ftl_stream {
  51. obs_output_t *output;
  52. pthread_mutex_t packets_mutex;
  53. struct circlebuf packets;
  54. bool sent_headers;
  55. int64_t frames_sent;
  56. volatile bool connecting;
  57. pthread_t connect_thread;
  58. pthread_t status_thread;
  59. volatile bool active;
  60. volatile bool disconnected;
  61. pthread_t send_thread;
  62. int max_shutdown_time_sec;
  63. os_sem_t *send_sem;
  64. os_event_t *stop_event;
  65. uint64_t stop_ts;
  66. uint64_t shutdown_timeout_ts;
  67. struct dstr path;
  68. uint32_t channel_id;
  69. struct dstr username, password;
  70. struct dstr encoder_name;
  71. struct dstr bind_ip;
  72. /* frame drop variables */
  73. int64_t drop_threshold_usec;
  74. int64_t pframe_drop_threshold_usec;
  75. int min_priority;
  76. float congestion;
  77. int64_t last_dts_usec;
  78. uint64_t total_bytes_sent;
  79. uint64_t dropped_frames;
  80. uint64_t last_nack_count;
  81. ftl_handle_t ftl_handle;
  82. ftl_ingest_params_t params;
  83. int peak_kbps;
  84. uint32_t scale_width, scale_height, width, height;
  85. frame_of_nalus_t coded_pic_buffer;
  86. };
  87. static void log_libftl_messages(ftl_log_severity_t log_level,
  88. const char *message);
  89. static int init_connect(struct ftl_stream *stream);
  90. static void *connect_thread(void *data);
  91. static void *status_thread(void *data);
  92. static int _ftl_error_to_obs_error(int status);
  93. static const char *ftl_stream_getname(void *unused)
  94. {
  95. UNUSED_PARAMETER(unused);
  96. return obs_module_text("FTLStream");
  97. }
  98. static void log_ftl(int level, const char *format, va_list args)
  99. {
  100. blogva(LOG_INFO, format, args);
  101. UNUSED_PARAMETER(level);
  102. }
  103. static inline size_t num_buffered_packets(struct ftl_stream *stream);
  104. static inline void free_packets(struct ftl_stream *stream)
  105. {
  106. size_t num_packets;
  107. pthread_mutex_lock(&stream->packets_mutex);
  108. num_packets = num_buffered_packets(stream);
  109. if (num_packets)
  110. info("Freeing %d remaining packets", (int)num_packets);
  111. while (stream->packets.size) {
  112. struct encoder_packet packet;
  113. circlebuf_pop_front(&stream->packets, &packet, sizeof(packet));
  114. obs_encoder_packet_release(&packet);
  115. }
  116. pthread_mutex_unlock(&stream->packets_mutex);
  117. }
  118. static inline bool stopping(struct ftl_stream *stream)
  119. {
  120. return os_event_try(stream->stop_event) != EAGAIN;
  121. }
  122. static inline bool connecting(struct ftl_stream *stream)
  123. {
  124. return os_atomic_load_bool(&stream->connecting);
  125. }
  126. static inline bool active(struct ftl_stream *stream)
  127. {
  128. return os_atomic_load_bool(&stream->active);
  129. }
  130. static inline bool disconnected(struct ftl_stream *stream)
  131. {
  132. return os_atomic_load_bool(&stream->disconnected);
  133. }
  134. static void ftl_stream_destroy(void *data)
  135. {
  136. struct ftl_stream *stream = data;
  137. ftl_status_t status_code;
  138. info("ftl_stream_destroy");
  139. if (stopping(stream) && !connecting(stream)) {
  140. pthread_join(stream->send_thread, NULL);
  141. } else if (connecting(stream) || active(stream)) {
  142. if (stream->connecting) {
  143. info("wait for connect_thread to terminate");
  144. pthread_join(stream->status_thread, NULL);
  145. pthread_join(stream->connect_thread, NULL);
  146. info("wait for connect_thread to terminate: done");
  147. }
  148. stream->stop_ts = 0;
  149. os_event_signal(stream->stop_event);
  150. if (active(stream)) {
  151. os_sem_post(stream->send_sem);
  152. obs_output_end_data_capture(stream->output);
  153. pthread_join(stream->send_thread, NULL);
  154. }
  155. }
  156. info("ingest destroy");
  157. status_code = ftl_ingest_destroy(&stream->ftl_handle);
  158. if (status_code != FTL_SUCCESS) {
  159. info("Failed to destroy from ingest %d", status_code);
  160. }
  161. if (stream) {
  162. free_packets(stream);
  163. dstr_free(&stream->path);
  164. dstr_free(&stream->username);
  165. dstr_free(&stream->password);
  166. dstr_free(&stream->encoder_name);
  167. dstr_free(&stream->bind_ip);
  168. os_event_destroy(stream->stop_event);
  169. os_sem_destroy(stream->send_sem);
  170. pthread_mutex_destroy(&stream->packets_mutex);
  171. circlebuf_free(&stream->packets);
  172. bfree(stream);
  173. }
  174. }
  175. static void *ftl_stream_create(obs_data_t *settings, obs_output_t *output)
  176. {
  177. struct ftl_stream *stream = bzalloc(sizeof(struct ftl_stream));
  178. info("ftl_stream_create");
  179. stream->output = output;
  180. pthread_mutex_init_value(&stream->packets_mutex);
  181. stream->peak_kbps = -1;
  182. ftl_init();
  183. if (pthread_mutex_init(&stream->packets_mutex, NULL) != 0) {
  184. goto fail;
  185. }
  186. if (os_event_init(&stream->stop_event, OS_EVENT_TYPE_MANUAL) != 0) {
  187. goto fail;
  188. }
  189. stream->coded_pic_buffer.total = 0;
  190. stream->coded_pic_buffer.complete_frame = 0;
  191. UNUSED_PARAMETER(settings);
  192. return stream;
  193. fail:
  194. return NULL;
  195. }
  196. static void ftl_stream_stop(void *data, uint64_t ts)
  197. {
  198. struct ftl_stream *stream = data;
  199. info("ftl_stream_stop");
  200. if (stopping(stream) && ts != 0) {
  201. return;
  202. }
  203. if (connecting(stream)) {
  204. pthread_join(stream->status_thread, NULL);
  205. pthread_join(stream->connect_thread, NULL);
  206. }
  207. stream->stop_ts = ts / 1000ULL;
  208. if (ts) {
  209. stream->shutdown_timeout_ts = ts +
  210. (uint64_t)stream->max_shutdown_time_sec * 1000000000ULL;
  211. }
  212. if (active(stream)) {
  213. os_event_signal(stream->stop_event);
  214. if (stream->stop_ts == 0)
  215. os_sem_post(stream->send_sem);
  216. } else {
  217. obs_output_signal_stop(stream->output, OBS_OUTPUT_SUCCESS);
  218. }
  219. }
  220. static inline bool get_next_packet(struct ftl_stream *stream,
  221. struct encoder_packet *packet)
  222. {
  223. bool new_packet = false;
  224. pthread_mutex_lock(&stream->packets_mutex);
  225. if (stream->packets.size) {
  226. circlebuf_pop_front(&stream->packets, packet,
  227. sizeof(struct encoder_packet));
  228. new_packet = true;
  229. }
  230. pthread_mutex_unlock(&stream->packets_mutex);
  231. return new_packet;
  232. }
  233. static int avc_get_video_frame(struct ftl_stream *stream,
  234. struct encoder_packet *packet, bool is_header)
  235. {
  236. int consumed = 0;
  237. int len = (int)packet->size;
  238. nalu_t *nalu;
  239. unsigned char *video_stream = packet->data;
  240. while ((size_t)consumed < packet->size) {
  241. size_t total_max = sizeof(stream->coded_pic_buffer.nalus) /
  242. sizeof(stream->coded_pic_buffer.nalus[0]);
  243. if ((size_t)stream->coded_pic_buffer.total >= total_max) {
  244. warn("ERROR: cannot continue, nalu buffers are full");
  245. return -1;
  246. }
  247. nalu = &stream->coded_pic_buffer.nalus
  248. [stream->coded_pic_buffer.total];
  249. if (is_header) {
  250. if (consumed == 0) {
  251. //first 6 bytes are some obs header with part
  252. //of the sps
  253. video_stream += 6;
  254. consumed += 6;
  255. } else {
  256. //another spacer byte of 0x1
  257. video_stream += 1;
  258. consumed += 1;
  259. }
  260. len = video_stream[0] << 8 | video_stream[1];
  261. video_stream += 2;
  262. consumed += 2;
  263. } else {
  264. len = video_stream[0] << 24 |
  265. video_stream[1] << 16 |
  266. video_stream[2] << 8 |
  267. video_stream[3];
  268. if ((size_t)len > (packet->size - (size_t)consumed)) {
  269. warn("ERROR: got len of %d but packet only "
  270. "has %d left",
  271. len,
  272. (int)(packet->size - consumed));
  273. }
  274. consumed += 4;
  275. video_stream += 4;
  276. }
  277. consumed += len;
  278. uint8_t nalu_type = video_stream[0] & 0x1F;
  279. uint8_t nri = (video_stream[0] >> 5) & 0x3;
  280. if ((nalu_type != 12 && nalu_type != 6 && nalu_type != 9) ||
  281. nri) {
  282. nalu->data = video_stream;
  283. nalu->len = len;
  284. nalu->send_marker_bit = 0;
  285. stream->coded_pic_buffer.total++;
  286. }
  287. video_stream += len;
  288. }
  289. if (!is_header) {
  290. size_t idx = stream->coded_pic_buffer.total - 1;
  291. stream->coded_pic_buffer.nalus[idx].send_marker_bit = 1;
  292. }
  293. return 0;
  294. }
  295. static int send_packet(struct ftl_stream *stream,
  296. struct encoder_packet *packet, bool is_header)
  297. {
  298. int bytes_sent = 0;
  299. int ret = 0;
  300. if (packet->type == OBS_ENCODER_VIDEO) {
  301. stream->coded_pic_buffer.total = 0;
  302. avc_get_video_frame(stream, packet, is_header);
  303. int i;
  304. for (i = 0; i < stream->coded_pic_buffer.total; i++) {
  305. nalu_t *nalu = &stream->coded_pic_buffer.nalus[i];
  306. bytes_sent += ftl_ingest_send_media_dts(
  307. &stream->ftl_handle,
  308. FTL_VIDEO_DATA,
  309. packet->dts_usec,
  310. nalu->data,
  311. nalu->len,
  312. nalu->send_marker_bit);
  313. if (nalu->send_marker_bit) {
  314. stream->frames_sent++;
  315. }
  316. }
  317. } else if (packet->type == OBS_ENCODER_AUDIO) {
  318. bytes_sent += ftl_ingest_send_media_dts(
  319. &stream->ftl_handle,
  320. FTL_AUDIO_DATA,
  321. packet->dts_usec,
  322. packet->data,
  323. (int)packet->size, 0);
  324. } else {
  325. warn("Got packet type %d", packet->type);
  326. }
  327. if (is_header) {
  328. bfree(packet->data);
  329. }
  330. else {
  331. obs_encoder_packet_release(packet);
  332. }
  333. stream->total_bytes_sent += bytes_sent;
  334. return ret;
  335. }
  336. static void set_peak_bitrate(struct ftl_stream *stream)
  337. {
  338. int speedtest_kbps = 15000;
  339. int speedtest_duration = 1000;
  340. speed_test_t results;
  341. ftl_status_t status_code;
  342. status_code = ftl_ingest_speed_test_ex(
  343. &stream->ftl_handle,
  344. speedtest_kbps,
  345. speedtest_duration,
  346. &results);
  347. float percent_lost = 0;
  348. if (status_code == FTL_SUCCESS) {
  349. percent_lost = (float)results.lost_pkts * 100.f /
  350. (float)results.pkts_sent;
  351. } else {
  352. warn("Speed test failed with: %s",
  353. ftl_status_code_to_string(status_code));
  354. }
  355. // Get what the user set the encoding bitrate to.
  356. obs_encoder_t *video_encoder = obs_output_get_video_encoder(stream->output);
  357. obs_data_t *video_settings = obs_encoder_get_settings(video_encoder);
  358. int user_desired_bitrate = (int)obs_data_get_int(video_settings, "bitrate");
  359. obs_data_release(video_settings);
  360. // Report the results.
  361. info("Speed test completed: User desired bitrate %d, Peak kbps %d, "
  362. "initial rtt %d, "
  363. "final rtt %d, %3.2f lost packets",
  364. user_desired_bitrate,
  365. results.peak_kbps,
  366. results.starting_rtt,
  367. results.ending_rtt,
  368. percent_lost);
  369. // We still want to set the peak to about 1.2x what the target bitrate is,
  370. // even if the speed test reported it should be lower. If we don't, FTL
  371. // will queue data on the client and start adding latency. If the internet
  372. // connection really can't handle the bitrate the user will see either lost frame
  373. // and recovered frame counts go up, which is reflect in the dropped_frames count.
  374. stream->peak_kbps = stream->params.peak_kbps = user_desired_bitrate * 12 / 10;
  375. ftl_ingest_update_params(&stream->ftl_handle, &stream->params);
  376. }
  377. static inline bool send_headers(struct ftl_stream *stream, int64_t dts_usec);
  378. static inline bool can_shutdown_stream(struct ftl_stream *stream,
  379. struct encoder_packet *packet)
  380. {
  381. uint64_t cur_time = os_gettime_ns();
  382. bool timeout = cur_time >= stream->shutdown_timeout_ts;
  383. if (timeout)
  384. info("Stream shutdown timeout reached (%d second(s))",
  385. stream->max_shutdown_time_sec);
  386. return timeout || packet->sys_dts_usec >= (int64_t)stream->stop_ts;
  387. }
  388. static void *send_thread(void *data)
  389. {
  390. struct ftl_stream *stream = data;
  391. ftl_status_t status_code;
  392. os_set_thread_name("ftl-stream: send_thread");
  393. while (os_sem_wait(stream->send_sem) == 0) {
  394. struct encoder_packet packet;
  395. if (stopping(stream) && stream->stop_ts == 0) {
  396. break;
  397. }
  398. if (!get_next_packet(stream, &packet))
  399. continue;
  400. if (stopping(stream)) {
  401. if (can_shutdown_stream(stream, &packet)) {
  402. obs_encoder_packet_release(&packet);
  403. break;
  404. }
  405. }
  406. /* sends sps/pps on every key frame as this is typically
  407. * required for webrtc */
  408. if (packet.keyframe) {
  409. if (!send_headers(stream, packet.dts_usec)) {
  410. os_atomic_set_bool(&stream->disconnected, true);
  411. break;
  412. }
  413. }
  414. if (send_packet(stream, &packet, false) < 0) {
  415. os_atomic_set_bool(&stream->disconnected, true);
  416. break;
  417. }
  418. }
  419. if (disconnected(stream)) {
  420. info("Disconnected from %s", stream->path.array);
  421. } else {
  422. info("User stopped the stream");
  423. }
  424. if (!stopping(stream)) {
  425. pthread_detach(stream->send_thread);
  426. obs_output_signal_stop(stream->output, OBS_OUTPUT_DISCONNECTED);
  427. } else {
  428. obs_output_end_data_capture(stream->output);
  429. }
  430. info("ingest disconnect");
  431. status_code = ftl_ingest_disconnect(&stream->ftl_handle);
  432. if (status_code != FTL_SUCCESS) {
  433. printf("Failed to disconnect from ingest %d", status_code);
  434. }
  435. free_packets(stream);
  436. os_event_reset(stream->stop_event);
  437. os_atomic_set_bool(&stream->active, false);
  438. stream->sent_headers = false;
  439. return NULL;
  440. }
  441. static bool send_video_header(struct ftl_stream *stream, int64_t dts_usec)
  442. {
  443. obs_output_t *context = stream->output;
  444. obs_encoder_t *vencoder = obs_output_get_video_encoder(context);
  445. uint8_t *header;
  446. size_t size;
  447. struct encoder_packet packet = {
  448. .type = OBS_ENCODER_VIDEO,
  449. .timebase_den = 1,
  450. .keyframe = true,
  451. .dts_usec = dts_usec
  452. };
  453. obs_encoder_get_extra_data(vencoder, &header, &size);
  454. packet.size = obs_parse_avc_header(&packet.data, header, size);
  455. return send_packet(stream, &packet, true) >= 0;
  456. }
  457. static inline bool send_headers(struct ftl_stream *stream, int64_t dts_usec)
  458. {
  459. stream->sent_headers = true;
  460. if (!send_video_header(stream, dts_usec))
  461. return false;
  462. return true;
  463. }
  464. static inline bool reset_semaphore(struct ftl_stream *stream)
  465. {
  466. os_sem_destroy(stream->send_sem);
  467. return os_sem_init(&stream->send_sem, 0) == 0;
  468. }
  469. #ifdef _WIN32
  470. #define socklen_t int
  471. #endif
  472. static int init_send(struct ftl_stream *stream)
  473. {
  474. int ret;
  475. reset_semaphore(stream);
  476. ret = pthread_create(&stream->send_thread, NULL, send_thread, stream);
  477. if (ret != 0) {
  478. warn("Failed to create send thread");
  479. return OBS_OUTPUT_ERROR;
  480. }
  481. os_atomic_set_bool(&stream->active, true);
  482. obs_output_begin_data_capture(stream->output, 0);
  483. return OBS_OUTPUT_SUCCESS;
  484. }
  485. static int try_connect(struct ftl_stream *stream)
  486. {
  487. ftl_status_t status_code;
  488. if (dstr_is_empty(&stream->path)) {
  489. warn("URL is empty");
  490. return OBS_OUTPUT_BAD_PATH;
  491. }
  492. info("Connecting to FTL Ingest URL %s...", stream->path.array);
  493. stream->width = (int)obs_output_get_width(stream->output);
  494. stream->height = (int)obs_output_get_height(stream->output);
  495. status_code = ftl_ingest_connect(&stream->ftl_handle);
  496. if (status_code != FTL_SUCCESS) {
  497. if (status_code == FTL_BAD_OR_INVALID_STREAM_KEY) {
  498. blog(LOG_ERROR, "Invalid Key (%s)",
  499. ftl_status_code_to_string(status_code));
  500. return OBS_OUTPUT_INVALID_STREAM;
  501. } else {
  502. warn("Ingest connect failed with: %s (%d)",
  503. ftl_status_code_to_string(status_code),
  504. status_code);
  505. return _ftl_error_to_obs_error(status_code);
  506. }
  507. }
  508. info("Connection to %s successful", stream->path.array);
  509. // Always get the peak bitrate when we are starting.
  510. set_peak_bitrate(stream);
  511. pthread_create(&stream->status_thread, NULL, status_thread, stream);
  512. return init_send(stream);
  513. }
  514. static bool ftl_stream_start(void *data)
  515. {
  516. struct ftl_stream *stream = data;
  517. info("ftl_stream_start");
  518. // Mixer doesn't support bframes. So force them off.
  519. obs_encoder_t *video_encoder = obs_output_get_video_encoder(stream->output);
  520. obs_data_t *video_settings = obs_encoder_get_settings(video_encoder);
  521. obs_data_set_int(video_settings, "bf", 0);
  522. obs_data_release(video_settings);
  523. if (!obs_output_can_begin_data_capture(stream->output, 0)) {
  524. return false;
  525. }
  526. if (!obs_output_initialize_encoders(stream->output, 0)) {
  527. return false;
  528. }
  529. stream->frames_sent = 0;
  530. os_atomic_set_bool(&stream->connecting, true);
  531. return pthread_create(&stream->connect_thread, NULL, connect_thread,
  532. stream) == 0;
  533. }
  534. static inline bool add_packet(struct ftl_stream *stream,
  535. struct encoder_packet *packet)
  536. {
  537. circlebuf_push_back(&stream->packets, packet,
  538. sizeof(struct encoder_packet));
  539. return true;
  540. }
  541. static inline size_t num_buffered_packets(struct ftl_stream *stream)
  542. {
  543. return stream->packets.size / sizeof(struct encoder_packet);
  544. }
  545. static void drop_frames(struct ftl_stream *stream, const char *name,
  546. int highest_priority, bool pframes)
  547. {
  548. UNUSED_PARAMETER(pframes);
  549. struct circlebuf new_buf = {0};
  550. int num_frames_dropped = 0;
  551. #ifdef _DEBUG
  552. int start_packets = (int)num_buffered_packets(stream);
  553. #else
  554. UNUSED_PARAMETER(name);
  555. #endif
  556. circlebuf_reserve(&new_buf, sizeof(struct encoder_packet) * 8);
  557. while (stream->packets.size) {
  558. struct encoder_packet packet;
  559. circlebuf_pop_front(&stream->packets, &packet, sizeof(packet));
  560. /* do not drop audio data or video keyframes */
  561. if (packet.type == OBS_ENCODER_AUDIO ||
  562. packet.drop_priority >= highest_priority) {
  563. circlebuf_push_back(&new_buf, &packet, sizeof(packet));
  564. } else {
  565. num_frames_dropped++;
  566. obs_encoder_packet_release(&packet);
  567. }
  568. }
  569. circlebuf_free(&stream->packets);
  570. stream->packets = new_buf;
  571. if (stream->min_priority < highest_priority)
  572. stream->min_priority = highest_priority;
  573. if (!num_frames_dropped)
  574. return;
  575. stream->dropped_frames += num_frames_dropped;
  576. #ifdef _DEBUG
  577. debug("Dropped %s, prev packet count: %d, new packet count: %d",
  578. name,
  579. start_packets,
  580. (int)num_buffered_packets(stream));
  581. #endif
  582. }
  583. static bool find_first_video_packet(struct ftl_stream *stream,
  584. struct encoder_packet *first)
  585. {
  586. size_t count = stream->packets.size / sizeof(*first);
  587. for (size_t i = 0; i < count; i++) {
  588. struct encoder_packet *cur = circlebuf_data(&stream->packets,
  589. i * sizeof(*first));
  590. if (cur->type == OBS_ENCODER_VIDEO && !cur->keyframe) {
  591. *first = *cur;
  592. return true;
  593. }
  594. }
  595. return false;
  596. }
  597. static void check_to_drop_frames(struct ftl_stream *stream, bool pframes)
  598. {
  599. struct encoder_packet first;
  600. int64_t buffer_duration_usec;
  601. size_t num_packets = num_buffered_packets(stream);
  602. const char *name = pframes ? "p-frames" : "b-frames";
  603. int priority = pframes ?
  604. OBS_NAL_PRIORITY_HIGHEST : OBS_NAL_PRIORITY_HIGH;
  605. int64_t drop_threshold = pframes ?
  606. stream->pframe_drop_threshold_usec :
  607. stream->drop_threshold_usec;
  608. if (num_packets < 5) {
  609. if (!pframes)
  610. stream->congestion = 0.0f;
  611. return;
  612. }
  613. if (!find_first_video_packet(stream, &first))
  614. return;
  615. /* if the amount of time stored in the buffered packets waiting to be
  616. * sent is higher than threshold, drop frames */
  617. buffer_duration_usec = stream->last_dts_usec - first.dts_usec;
  618. if (!pframes) {
  619. stream->congestion = (float)buffer_duration_usec /
  620. (float)drop_threshold;
  621. }
  622. if (buffer_duration_usec > drop_threshold) {
  623. debug("buffer_duration_usec: %" PRId64, buffer_duration_usec);
  624. drop_frames(stream, name, priority, pframes);
  625. }
  626. }
  627. static bool add_video_packet(struct ftl_stream *stream,
  628. struct encoder_packet *packet)
  629. {
  630. check_to_drop_frames(stream, false);
  631. check_to_drop_frames(stream, true);
  632. /* if currently dropping frames, drop packets until it reaches the
  633. * desired priority */
  634. if (packet->priority < stream->min_priority) {
  635. stream->dropped_frames++;
  636. return false;
  637. } else {
  638. stream->min_priority = 0;
  639. }
  640. stream->last_dts_usec = packet->dts_usec;
  641. return add_packet(stream, packet);
  642. }
  643. static void ftl_stream_data(void *data, struct encoder_packet *packet)
  644. {
  645. struct ftl_stream *stream = data;
  646. struct encoder_packet new_packet;
  647. bool added_packet = false;
  648. if (disconnected(stream) || !active(stream))
  649. return;
  650. if (packet->type == OBS_ENCODER_VIDEO)
  651. obs_parse_avc_packet(&new_packet, packet);
  652. else
  653. obs_encoder_packet_ref(&new_packet, packet);
  654. pthread_mutex_lock(&stream->packets_mutex);
  655. if (!disconnected(stream)) {
  656. added_packet = (packet->type == OBS_ENCODER_VIDEO) ?
  657. add_video_packet(stream, &new_packet) :
  658. add_packet(stream, &new_packet);
  659. }
  660. pthread_mutex_unlock(&stream->packets_mutex);
  661. if (added_packet)
  662. os_sem_post(stream->send_sem);
  663. else
  664. obs_encoder_packet_release(&new_packet);
  665. }
  666. static void ftl_stream_defaults(obs_data_t *defaults)
  667. {
  668. UNUSED_PARAMETER(defaults);
  669. }
  670. static obs_properties_t *ftl_stream_properties(void *unused)
  671. {
  672. UNUSED_PARAMETER(unused);
  673. obs_properties_t *props = obs_properties_create();
  674. obs_properties_add_int(props, "peak_bitrate_kbps",
  675. obs_module_text("FTLStream.PeakBitrate"),
  676. 1000, 10000, 500);
  677. return props;
  678. }
  679. static uint64_t ftl_stream_total_bytes_sent(void *data)
  680. {
  681. struct ftl_stream *stream = data;
  682. return stream->total_bytes_sent;
  683. }
  684. static int ftl_stream_dropped_frames(void *data)
  685. {
  686. struct ftl_stream *stream = data;
  687. return (int)stream->dropped_frames;
  688. }
  689. static float ftl_stream_congestion(void *data)
  690. {
  691. struct ftl_stream *stream = data;
  692. return stream->min_priority > 0 ? 1.0f : stream->congestion;
  693. }
  694. enum ret_type {
  695. RET_CONTINUE,
  696. RET_BREAK,
  697. RET_EXIT,
  698. };
  699. static enum ret_type ftl_event(struct ftl_stream *stream,
  700. ftl_status_msg_t status)
  701. {
  702. if (status.msg.event.type != FTL_STATUS_EVENT_TYPE_DISCONNECTED)
  703. return RET_CONTINUE;
  704. info("Disconnected from ingest with reason: %s",
  705. ftl_status_code_to_string(status.msg.event.error_code));
  706. if (status.msg.event.reason == FTL_STATUS_EVENT_REASON_API_REQUEST) {
  707. return RET_BREAK;
  708. }
  709. //tell OBS and it will trigger a reconnection
  710. blog(LOG_WARNING, "Reconnecting to Ingest");
  711. obs_output_signal_stop(stream->output, OBS_OUTPUT_DISCONNECTED);
  712. return RET_EXIT;
  713. }
  714. static void *status_thread(void *data)
  715. {
  716. struct ftl_stream *stream = data;
  717. ftl_status_msg_t status;
  718. ftl_status_t status_code;
  719. while (!disconnected(stream)) {
  720. status_code = ftl_ingest_get_status(&stream->ftl_handle,
  721. &status, 1000);
  722. if (status_code == FTL_STATUS_TIMEOUT ||
  723. status_code == FTL_QUEUE_EMPTY) {
  724. continue;
  725. } else if (status_code == FTL_NOT_INITIALIZED) {
  726. break;
  727. }
  728. if (status.type == FTL_STATUS_EVENT) {
  729. enum ret_type ret_type = ftl_event(stream, status);
  730. if (ret_type == RET_EXIT)
  731. return NULL;
  732. else if (ret_type == RET_BREAK)
  733. break;
  734. } else if(status.type == FTL_STATUS_LOG) {
  735. blog(LOG_INFO, "[%d] %s", status.msg.log.log_level,
  736. status.msg.log.string);
  737. } else if (status.type == FTL_STATUS_VIDEO_PACKETS) {
  738. ftl_packet_stats_msg_t *p = &status.msg.pkt_stats;
  739. // Report nack requests as dropped frames
  740. stream->dropped_frames +=
  741. p->nack_reqs -stream->last_nack_count;
  742. stream->last_nack_count = p->nack_reqs;
  743. int log_level = p->nack_reqs > 0 ? LOG_INFO : LOG_DEBUG;
  744. blog(log_level, "Avg packet send per second %3.1f, "
  745. "total nack requests %d",
  746. (float)p->sent * 1000.f / p->period,
  747. (int)p->nack_reqs);
  748. } else if (status.type == FTL_STATUS_VIDEO_PACKETS_INSTANT) {
  749. ftl_packet_stats_instant_msg_t *p =
  750. &status.msg.ipkt_stats;
  751. int log_level = p->avg_rtt > 20 ? LOG_INFO : LOG_DEBUG;
  752. blog(log_level, "avg transmit delay %dms "
  753. "(min: %d, max: %d), "
  754. "avg rtt %dms (min: %d, max: %d)",
  755. p->avg_xmit_delay,
  756. p->min_xmit_delay, p->max_xmit_delay,
  757. p->avg_rtt, p->min_rtt, p->max_rtt);
  758. } else if (status.type == FTL_STATUS_VIDEO) {
  759. ftl_video_frame_stats_msg_t *v =
  760. &status.msg.video_stats;
  761. int log_level = v->queue_fullness > 0 ?
  762. LOG_INFO : LOG_DEBUG;
  763. blog(log_level, "Queue an average of %3.2f fps "
  764. "(%3.1f kbps), "
  765. "sent an average of %3.2f fps "
  766. "(%3.1f kbps), "
  767. "queue fullness %d, "
  768. "max frame size %d",
  769. (float)v->frames_queued * 1000.f / v->period,
  770. (float)v->bytes_queued / v->period * 8,
  771. (float)v->frames_sent * 1000.f / v->period,
  772. (float)v->bytes_sent / v->period * 8,
  773. v->queue_fullness, v->max_frame_size);
  774. } else {
  775. blog(LOG_DEBUG, "Status: Got Status message of type "
  776. "%d", status.type);
  777. }
  778. }
  779. blog(LOG_DEBUG, "status_thread: Exited");
  780. pthread_detach(stream->status_thread);
  781. return NULL;
  782. }
  783. static void *connect_thread(void *data)
  784. {
  785. struct ftl_stream *stream = data;
  786. int ret;
  787. os_set_thread_name("ftl-stream: connect_thread");
  788. blog(LOG_WARNING, "ftl-stream: connect thread");
  789. ret = init_connect(stream);
  790. if (ret != OBS_OUTPUT_SUCCESS) {
  791. obs_output_signal_stop(stream->output, ret);
  792. return NULL;
  793. }
  794. ret = try_connect(stream);
  795. if (ret != OBS_OUTPUT_SUCCESS) {
  796. obs_output_signal_stop(stream->output, ret);
  797. info("Connection to %s failed: %d", stream->path.array, ret);
  798. }
  799. if (!stopping(stream))
  800. pthread_detach(stream->connect_thread);
  801. os_atomic_set_bool(&stream->connecting, false);
  802. return NULL;
  803. }
  804. static void log_libftl_messages(ftl_log_severity_t log_level,
  805. const char * message)
  806. {
  807. UNUSED_PARAMETER(log_level);
  808. blog(LOG_WARNING, "[libftl] %s", message);
  809. }
  810. static int init_connect(struct ftl_stream *stream)
  811. {
  812. obs_service_t *service;
  813. obs_data_t *settings;
  814. const char *bind_ip, *key;
  815. ftl_status_t status_code;
  816. info("init_connect");
  817. if (stopping(stream))
  818. pthread_join(stream->send_thread, NULL);
  819. free_packets(stream);
  820. service = obs_output_get_service(stream->output);
  821. if (!service) {
  822. return OBS_OUTPUT_ERROR;
  823. }
  824. os_atomic_set_bool(&stream->disconnected, false);
  825. stream->total_bytes_sent = 0;
  826. stream->dropped_frames = 0;
  827. stream->min_priority = 0;
  828. settings = obs_output_get_settings(stream->output);
  829. obs_encoder_t *video_encoder =
  830. obs_output_get_video_encoder(stream->output);
  831. obs_data_t *video_settings =
  832. obs_encoder_get_settings(video_encoder);
  833. dstr_copy(&stream->path, obs_service_get_url(service));
  834. key = obs_service_get_key(service);
  835. int target_bitrate = (int)obs_data_get_int(video_settings, "bitrate");
  836. int peak_bitrate = (int)((float)target_bitrate * 1.1f);
  837. //minimum overshoot tolerance of 10%
  838. if (peak_bitrate < target_bitrate) {
  839. peak_bitrate = target_bitrate;
  840. }
  841. stream->params.stream_key = (char*)key;
  842. stream->params.video_codec = FTL_VIDEO_H264;
  843. stream->params.audio_codec = FTL_AUDIO_OPUS;
  844. stream->params.ingest_hostname = stream->path.array;
  845. stream->params.vendor_name = "OBS Studio";
  846. stream->params.vendor_version = OBS_VERSION;
  847. stream->params.peak_kbps =
  848. stream->peak_kbps < 0 ? 0 : stream->peak_kbps;
  849. //not required when using ftl_ingest_send_media_dts
  850. stream->params.fps_num = 0;
  851. stream->params.fps_den = 0;
  852. status_code = ftl_ingest_create(&stream->ftl_handle, &stream->params);
  853. if (status_code != FTL_SUCCESS) {
  854. if (status_code == FTL_BAD_OR_INVALID_STREAM_KEY) {
  855. blog(LOG_ERROR, "Invalid Key (%s)",
  856. ftl_status_code_to_string(status_code));
  857. return OBS_OUTPUT_INVALID_STREAM;
  858. }
  859. else {
  860. blog(LOG_ERROR, "Failed to create ingest handle (%s)",
  861. ftl_status_code_to_string(status_code));
  862. return OBS_OUTPUT_ERROR;
  863. }
  864. }
  865. dstr_copy(&stream->username, obs_service_get_username(service));
  866. dstr_copy(&stream->password, obs_service_get_password(service));
  867. dstr_depad(&stream->path);
  868. stream->drop_threshold_usec =
  869. (int64_t)obs_data_get_int(settings, OPT_DROP_THRESHOLD) * 1000;
  870. stream->max_shutdown_time_sec =
  871. (int)obs_data_get_int(settings, OPT_MAX_SHUTDOWN_TIME_SEC);
  872. bind_ip = obs_data_get_string(settings, OPT_BIND_IP);
  873. dstr_copy(&stream->bind_ip, bind_ip);
  874. obs_data_release(settings);
  875. obs_data_release(video_settings);
  876. return OBS_OUTPUT_SUCCESS;
  877. }
  878. // Returns 0 on success
  879. static int _ftl_error_to_obs_error(int status)
  880. {
  881. /* Map FTL errors to OBS errors */
  882. switch (status) {
  883. case FTL_SUCCESS:
  884. return OBS_OUTPUT_SUCCESS;
  885. case FTL_SOCKET_NOT_CONNECTED:
  886. case FTL_MALLOC_FAILURE:
  887. case FTL_INTERNAL_ERROR:
  888. case FTL_CONFIG_ERROR:
  889. case FTL_NOT_ACTIVE_STREAM:
  890. case FTL_NOT_CONNECTED:
  891. case FTL_ALREADY_CONNECTED:
  892. case FTL_STATUS_TIMEOUT:
  893. case FTL_QUEUE_FULL:
  894. case FTL_STATUS_WAITING_FOR_KEY_FRAME:
  895. case FTL_QUEUE_EMPTY:
  896. case FTL_NOT_INITIALIZED:
  897. return OBS_OUTPUT_ERROR;
  898. case FTL_BAD_REQUEST:
  899. case FTL_DNS_FAILURE:
  900. case FTL_CONNECT_ERROR:
  901. case FTL_UNSUPPORTED_MEDIA_TYPE:
  902. case FTL_OLD_VERSION:
  903. case FTL_UNAUTHORIZED:
  904. case FTL_AUDIO_SSRC_COLLISION:
  905. case FTL_VIDEO_SSRC_COLLISION:
  906. case FTL_STREAM_REJECTED:
  907. case FTL_BAD_OR_INVALID_STREAM_KEY:
  908. case FTL_CHANNEL_IN_USE:
  909. case FTL_REGION_UNSUPPORTED:
  910. case FTL_GAME_BLOCKED:
  911. return OBS_OUTPUT_CONNECT_FAILED;
  912. case FTL_NO_MEDIA_TIMEOUT:
  913. return OBS_OUTPUT_DISCONNECTED;
  914. case FTL_USER_DISCONNECT:
  915. return OBS_OUTPUT_SUCCESS;
  916. case FTL_UNKNOWN_ERROR_CODE:
  917. default:
  918. /* Unknown FTL error */
  919. return OBS_OUTPUT_ERROR;
  920. }
  921. }
  922. struct obs_output_info ftl_output_info = {
  923. .id = "ftl_output",
  924. .flags = OBS_OUTPUT_AV |
  925. OBS_OUTPUT_ENCODED |
  926. OBS_OUTPUT_SERVICE,
  927. .encoded_video_codecs = "h264",
  928. .encoded_audio_codecs = "opus",
  929. .get_name = ftl_stream_getname,
  930. .create = ftl_stream_create,
  931. .destroy = ftl_stream_destroy,
  932. .start = ftl_stream_start,
  933. .stop = ftl_stream_stop,
  934. .encoded_packet = ftl_stream_data,
  935. .get_defaults = ftl_stream_defaults,
  936. .get_properties = ftl_stream_properties,
  937. .get_total_bytes = ftl_stream_total_bytes_sent,
  938. .get_congestion = ftl_stream_congestion,
  939. .get_dropped_frames = ftl_stream_dropped_frames
  940. };