repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
agnusfeec/buildFV
descriptor.h
#ifndef DESCRIPTOR_H #define DESCRIPTOR_H class descriptor { public: descriptor(); }; #endif // DESCRIPTOR_H
ML-PA-Consulting-GmbH/NanoCBOR
tests/automated/test_decoder.c
/* * SPDX-License-Identifier: CC0-1.0 */ #include "test.h" #include "nanocbor/nanocbor.h" #include <CUnit/CUnit.h> static void test_decode_indefinite(void) { /* Test vector, 3 integers in an indefinite array */ static const uint8_t indefinite[] = { 0x9f, 0x01, 0x02, 0x03, 0xff }; nanocbor_value_t val; nanocbor_value_t cont; uint32_t tmp = 0; nanocbor_decoder_init(&val, indefinite, sizeof(indefinite)); CU_ASSERT_EQUAL(nanocbor_enter_array(&val, &cont), NANOCBOR_OK); CU_ASSERT_EQUAL(nanocbor_container_indefinite(&cont), true); /* Decode the three values */ CU_ASSERT(nanocbor_get_uint32(&cont, &tmp) > 0); CU_ASSERT(nanocbor_get_uint32(&cont, &tmp) > 0); CU_ASSERT(nanocbor_get_uint32(&cont, &tmp) > 0); CU_ASSERT_EQUAL(nanocbor_get_uint32(&cont, &tmp), NANOCBOR_ERR_END); CU_ASSERT_EQUAL(nanocbor_at_end(&cont), true); } static void test_decode_map(void) { static const uint8_t map_empty[] = { 0xa0 }; static const uint8_t map_one[] = { 0xa1, 0x01, 0x02 }; nanocbor_value_t val; nanocbor_value_t cont; uint32_t tmp = 0; /* Init the decoder and assert the properties of the empty map */ nanocbor_decoder_init(&val, map_empty, sizeof(map_empty)); CU_ASSERT_EQUAL(nanocbor_enter_map(&val, &cont), NANOCBOR_OK); CU_ASSERT_EQUAL(nanocbor_at_end(&cont), true); nanocbor_leave_container(&val, &cont); CU_ASSERT_EQUAL(nanocbor_at_end(&val), true); /* Init the decoder and verify the decoding of the map elements */ nanocbor_decoder_init(&val, map_one, sizeof(map_one)); CU_ASSERT_EQUAL(nanocbor_enter_map(&val, &cont), NANOCBOR_OK); CU_ASSERT(nanocbor_get_uint32(&cont, &tmp) > 0); CU_ASSERT_EQUAL(tmp, 1); CU_ASSERT(nanocbor_get_uint32(&cont, &tmp) > 0); CU_ASSERT_EQUAL(tmp, 2); CU_ASSERT_EQUAL(nanocbor_at_end(&cont), true); nanocbor_leave_container(&val, &cont); CU_ASSERT_EQUAL(nanocbor_at_end(&val), true); /* Init the decoder and skip over the empty map */ nanocbor_decoder_init(&val, map_empty, sizeof(map_empty)); CU_ASSERT_EQUAL(nanocbor_skip(&val), NANOCBOR_OK); CU_ASSERT_EQUAL(nanocbor_at_end(&val), true); /* Init the decoder and skip over the non-empty map */ nanocbor_decoder_init(&val, map_one, sizeof(map_one)); CU_ASSERT_EQUAL(nanocbor_skip(&val), NANOCBOR_OK); CU_ASSERT_EQUAL(nanocbor_at_end(&val), true); } static void test_tag(void) { static const uint8_t arraytag[] = { 0x82, 0xc1, 0x01, 0x02 }; nanocbor_value_t val; nanocbor_value_t cont; uint32_t tmp = 0; nanocbor_decoder_init(&val, arraytag, sizeof(arraytag)); CU_ASSERT_EQUAL(nanocbor_enter_array(&val, &cont), NANOCBOR_OK); CU_ASSERT_EQUAL(nanocbor_get_tag(&cont, &tmp), NANOCBOR_OK); CU_ASSERT_EQUAL(tmp, 1); CU_ASSERT(nanocbor_get_uint32(&cont, &tmp) > 0); CU_ASSERT_EQUAL(tmp, 1); CU_ASSERT(nanocbor_get_uint32(&cont, &tmp) > 0); CU_ASSERT_EQUAL(tmp, 2); CU_ASSERT_EQUAL(nanocbor_at_end(&cont), true); } static void test_decode_none(void) { nanocbor_value_t val; nanocbor_value_t cont; uint64_t tmp; nanocbor_decoder_init(&val, NULL, 0); CU_ASSERT_EQUAL(nanocbor_get_type(&val), NANOCBOR_ERR_END); CU_ASSERT_EQUAL(nanocbor_get_uint32(&val, (uint32_t*)&tmp), NANOCBOR_ERR_END); CU_ASSERT_EQUAL(nanocbor_get_int32(&val, (int32_t*)&tmp), NANOCBOR_ERR_END); CU_ASSERT_EQUAL(nanocbor_enter_array(&val, &cont), NANOCBOR_ERR_END); CU_ASSERT_EQUAL(nanocbor_enter_map(&val, &cont), NANOCBOR_ERR_END); CU_ASSERT_EQUAL(nanocbor_get_null(&val), NANOCBOR_ERR_END); CU_ASSERT_EQUAL(nanocbor_get_bool(&val, (bool*)&tmp), NANOCBOR_ERR_END); CU_ASSERT_EQUAL(nanocbor_skip(&val), NANOCBOR_ERR_END); CU_ASSERT_EQUAL(nanocbor_skip_simple(&val), NANOCBOR_ERR_END); } static void test_decode_basic(void) { nanocbor_value_t decoder; uint8_t byteval = 5; /* unsigned integer, value 5 */ uint32_t value = 0; nanocbor_decoder_init(&decoder, &byteval, sizeof(byteval)); CU_ASSERT_EQUAL(nanocbor_get_type(&decoder), NANOCBOR_TYPE_UINT); printf("\"val: %u\"\n", value); CU_ASSERT_EQUAL(nanocbor_get_uint32(&decoder, &value), 1); printf("\"val: %u\"\n", value); CU_ASSERT_EQUAL(5, value); int32_t intval = 0; nanocbor_decoder_init(&decoder, &byteval, sizeof(byteval)); CU_ASSERT_EQUAL(nanocbor_get_int32(&decoder, &intval), 1); CU_ASSERT_EQUAL(5, intval); const uint8_t decimal_frac[] = { 0xC4, 0x82, 0x21, 0x19, 0x6a, 0xb3 }; int32_t m; int32_t e; nanocbor_decoder_init(&decoder, decimal_frac, sizeof(decimal_frac)); CU_ASSERT_EQUAL(nanocbor_get_decimal_frac(&decoder, &e, &m), 0); CU_ASSERT_EQUAL(e, -2); CU_ASSERT_EQUAL(m, 27315); } const test_t tests_decoder[] = { { .f = test_decode_none, .n = "get type on empty buffer", }, { .f = test_decode_basic, .n = "Simple CBOR integer tests", }, { .f = test_decode_indefinite, .n = "CBOR indefinite array decode tests", }, { .f = test_decode_map, .n = "CBOR map decode tests", }, { .f = test_tag, .n = "CBOR tag decode test", }, { .f = NULL, .n = NULL, } };
y-sira/overlayweaver
native/ipmulticast/common.h
<reponame>y-sira/overlayweaver<filename>native/ipmulticast/common.h /* * Copyright 2006 National Institute of Advanced Industrial Science * and Technology (AIST), and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef IGMPCOMMON_H_ #define IGMPCOMMON_H_ #include <stdio.h> // for printf(3), stdout and ... #include <stdlib.h> // for malloc(3) #include <stdint.h> // for uint32_t and uint8_t #include <stdarg.h> // va_start(3) and others #include <string.h> // for memset(3) #include <netinet/ip.h> // for struct ip #include <netinet/igmp.h> // for struct igmp #include <netinet/in.h> // for htonl(3) and IPPROTO_IN #include <netinet/udp.h> // for struct udphdr #include <unistd.h> // for close(2) #include <errno.h> // for perror(3) and errno #include <sys/types.h> // for setsockopt(2) and recv(2) #include <sys/socket.h> // for PF_PACKET, setsockopt(2), recv(2) and SIOC[GS]IFFLAG #include <netpacket/packet.h> // for PF_PACKET #include <net/ethernet.h> // for PF_PACKET #include <sys/ioctl.h> // for ioctl(2) #include <sys/syslog.h> // for LOG_* #include <linux/if.h> // for IFF_ALLMULTI #ifdef linux # define _LINUX_IN_H # include <linux/mroute.h> // for vifi_t, MAXVIFS #else # include <netinet/ip_mroute.h> #endif #include "vif.h" #ifndef IGMP_V2_MEMBERSHIP_REPORT # define IGMP_V2_MEMBERSHIP_REPORT 0x22 // Ver. 3 membership report #endif #ifndef INADDR_ALLRPTS_GROUP # define INADDR_ALLRPTS_GROUP 0xe0000016U // 192.168.127.12 for IGMPv3 #endif #define TRUE 1 #define FALSE 0 #ifdef linux # define RAW_INPUT_IS_RAW # define RAW_OUTPUT_IS_RAW # undef HAVE_SA_LEN #else # undef RAW_INPUT_IS_RAW # undef RAW_INPUT_IS_RAW # undef HAVE_SA_LEN #endif #ifndef MAXHOSTNAMELEN # define MAXHOSTNAMELEN 64 #endif // used by DVMRP in pimd #define DEFAULT_METRIC 1 #define DEFAULT_THRESHOLD 1 // used if no reliable unicast routing information available #define UCAST_DEFAULT_SOURCE_METRIC 1024 #define UCAST_DEFAULT_SOURCE_PREFERENCE 1024 // used by PIM in pimd #define DEFAULT_PHY_RATE_LIMIT 0 #define DEFAULT_REG_RATE_LIMIT 0 #define INADDR_ANY_N (uint32_t)0x00000000 /* INADDR_ANY in network byteorder */ // parameters #define RECV_BUF_MAX_SIZE (256 * 1024) #define RECV_BUF_MIN_SIZE (48 * 1024) #define SEND_BUF_MAX_SIZE (256 * 1024) #define SEND_BUF_MIN_SIZE (48 * 1024) #define MINTTL 1 #define DEFAULT_DGRAM_TTL 128 #define CALCULATE_UDP_CHECKSUM #define MULTICAST_LOOP TRUE // in igmp.c #define MIN(a, b) ((a) > (b) ? (b) : (a)) #define BUF_SIZE 8192 extern int igmp_socket; extern uint32_t selfaddr; extern uint32_t allhostsgroup; extern uint32_t allroutersgroup; extern uint32_t allv3routersgroup; int init_igmp(char *ifName); void stop_igmp(); int send_igmp(uint32_t src, uint32_t dest, int type, int code, int32_t group, char *data, int datalen); int recv_igmp(struct ip **ipp, struct igmp **igmpp, char *data, int *datalenp, int maxdatasize); // in dgram.c extern int sock_dgram_send, sock_dgram_recv; int init_dgram(); void stop_dgram(); int send_dgram(uint32_t srcaddr, uint16_t srcport, uint32_t destaddr, uint16_t destport, uint16_t id, uint8_t ttl, char *data, uint16_t datalen); int recv_dgram(struct ip **ipp, struct udphdr **udpp, char *data, int *datalenp, int maxdatasize, int only_mcast); // in util.c #define LOG_BUF_SIZE 512 void log(int severity, int syserr, char *format, ...); // vif.c extern struct uvif uvifs[MAXVIFS]; extern vifi_t numvifs; extern int vifs_down; extern int phys_vif; extern vifi_t reg_vif_num; extern int udp_socket; extern int total_interfaces; void init_vifs(); void zero_vif(struct uvif *v, int t); void stop_all_vifs(); // config.c void config_vifs_from_kernel(); // in kern.c #ifdef RAW_OUTPUT_IS_RAW extern int curttl; #endif void k_init_pim(int socket); void k_stop_pim(int socket); void k_set_sndbuf(int sock, int bufSize, int minSize); void k_set_rcvbuf(int sock, int bufSize, int minSize); void k_hdr_include(int socket, int bool); void k_set_ttl(int socket, int t); void k_set_loop(int socket, int flag); void k_set_if(int socket, uint32_t ifa); void k_join(int socket, uint32_t grp, struct uvif *v); void k_leave(int socket, uint32_t grp, struct uvif *v); void k_add_vif(int socket, vifi_t vifi, struct uvif *v); void k_del_vif(int socket, vifi_t vifi); #if 0 int k_del_mfc(int socket, uint32_t source, uint32_t group); int k_chg_mfc(int socket, uint32_t source, uint32_t group, vifi_t iif, vifbitmap_t oifs, uint32_t rp_addr); int k_get_vif_count(vifi_t vifi, struct vif_count *retval); int k_get_sg_cnt(int socket, uint32_t source, uint32_t group, struct sg_count *retval); #endif // inet.c extern char s1[19]; extern char s2[19]; extern char s3[19]; extern char s4[19]; int inet_valid_host(uint32_t naddr); int inet_valid_subnet(uint32_t nsubnet, uint32_t nmask); char *inet_fmt(uint32_t addr, char *s); int inet_cksum(uint16_t *addr, unsigned int len, int add); char *netname(uint32_t addr, uint32_t mask); #endif /*IGMPCOMMON_H_*/
y-sira/overlayweaver
native/ipmulticast/test.c
/* * Copyright 2006 National Institute of Advanced Industrial Science * and Technology (AIST), and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <stdlib.h> // for exit(3) #include "common.h" #undef TEST_IGMP static void start(); int main(int argc, char **argv) { #ifdef TEST_IGMP if (init_igmp("eth0") < 0) { exit(1); } #else init_dgram(); #endif init_vifs(); start(); return 0; } static void start() { #ifdef TEST_IGMP send_igmp(selfaddr, allhostsgroup, IGMP_MEMBERSHIP_QUERY, 0, 0, NULL, 0); #endif while (TRUE) { int recvLen; socklen_t fromLen; #ifdef TEST_IGMP if (recv_igmp(NULL, NULL, NULL, NULL, 0) < 0) break; #else if (recv_dgram(NULL, NULL, NULL, NULL, 0, TRUE) < 0) break; #endif } }
y-sira/overlayweaver
native/ipmulticast/inet.c
/* * The mrouted program is covered by the license in the accompanying file * named "LICENSE.mrouted". Use of the mrouted program represents acceptance of * the terms and conditions listed in that file. * * The mrouted program is COPYRIGHT 1989 by The Board of Trustees of * Leland Stanford Junior University. * * * inet.c,v 3.8.4.1 1997/01/29 19:49:33 fenner Exp */ #define C(x) ((x) & 0xff) #include "common.h" /* * Exported variables. */ char s1[19]; /* buffers to hold the string representations */ char s2[19]; /* of IP addresses, to be passed to inet_fmt() */ char s3[19]; char s4[19]; /* * Verify that a given IP address is credible as a host address. * (Without a mask, cannot detect addresses of the form {subnet,0} or * {subnet,-1}.) */ int inet_valid_host(uint32_t naddr) { register uint32_t addr; addr = ntohl(naddr); return (!(IN_MULTICAST(addr) || IN_BADCLASS (addr) || (addr & 0xff000000) == 0)); } /* * Verify that a given netmask is plausible; * make sure that it is a series of 1's followed by * a series of 0's with no discontiguous 1's. */ int inet_valid_mask(mask) uint32_t mask; { if (~(((mask & -mask) - 1) | mask) != 0) { /* Mask is not contiguous */ return (FALSE); } return (TRUE); } /* * Verify that a given subnet number and mask pair are credible. * * With CIDR, almost any subnet and mask are credible. mrouted still * can't handle aggregated class A's, so we still check that, but * otherwise the only requirements are that the subnet address is * within the [ABC] range and that the host bits of the subnet * are all 0. */ int inet_valid_subnet(uint32_t nsubnet, uint32_t nmask) { register uint32_t subnet, mask; subnet = ntohl(nsubnet); mask = ntohl(nmask); if ((subnet & mask) != subnet) return (FALSE); if (subnet == 0) return (mask == 0); if (IN_CLASSA(subnet)) { if (mask < 0xff000000 || (subnet & 0xff000000) == 0x7f000000 || (subnet & 0xff000000) == 0x00000000) return (FALSE); } else if (IN_CLASSD(subnet) || IN_BADCLASS(subnet)) { /* Above Class C address space */ return (FALSE); } if (subnet & ~mask) { /* Host bits are set in the subnet */ return (FALSE); } if (!inet_valid_mask(mask)) { /* Netmask is not contiguous */ return (FALSE); } return (TRUE); } /* * Convert an IP address in uint32_t (network) format into a printable string. */ char *inet_fmt(uint32_t addr, char *s) { register uint8_t *a; a = (uint8_t *)&addr; sprintf(s, "%u.%u.%u.%u", a[0], a[1], a[2], a[3]); return (s); } /* * Convert the printable string representation of an IP address into the * uint32_t (network) format. Return 0xffffffff on error. (To detect the * legal address with that value, you must explicitly compare the string * with "255.255.255.255".) * The return value is in network order. */ uint32_t inet_parse(char *s, int n) { uint32_t a = 0; unsigned int a0 = 0, a1 = 0, a2 = 0, a3 = 0; int i; char c; i = sscanf(s, "%u.%u.%u.%u%c", &a0, &a1, &a2, &a3, &c); if (i < n || i > 4 || a0 > 255 || a1 > 255 || a2 > 255 || a3 > 255) return (0xffffffff); ((uint8_t *)&a)[0] = a0; ((uint8_t *)&a)[1] = a1; ((uint8_t *)&a)[2] = a2; ((uint8_t *)&a)[3] = a3; return (a); } /* * inet_cksum extracted from: * P I N G . C * * Author - * <NAME> * <NAME> Ballistic Research Laboratory * December, 1983 * Modified at Uc Berkeley * * (ping.c) Status - * Public Domain. Distribution Unlimited. * * I N _ C K S U M * * Checksum routine for Internet Protocol family headers (C Version) * */ int inet_cksum(uint16_t *addr, unsigned int len, int add) { register int nleft = (int)len; register uint16_t *w = addr; uint16_t answer = 0; register int sum = 0; /* * Our algorithm is simple, using a 32 bit accumulator (sum), * we add sequential 16 bit words to it, and at the end, fold * back all the carry bits from the top 16 bits into the lower * 16 bits. */ while (nleft > 1) { sum += *w++; nleft -= 2; } /* mop up an odd byte, if necessary */ if (nleft == 1) { *(uint8_t *) (&answer) = *(uint8_t *)w ; sum += answer; } sum += add; // for UDP /* * add back carry outs from top 16 bits to low 16 bits */ sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ sum += (sum >> 16); /* add carry */ answer = ~sum; /* truncate to 16 bits */ return (answer); } /* * Called by following netname() to create a mask specified network address. */ void trimdomain(char *cp) { static char domain[MAXHOSTNAMELEN + 1]; static int first = 1; char *s; if (first) { first = 0; if (gethostname(domain, MAXHOSTNAMELEN) == 0 && (s = strchr(domain, '.'))) (void) strcpy(domain, s + 1); else domain[0] = 0; } if (domain[0]) { while ((cp = strchr(cp, '.'))) { if (!strcasecmp(cp + 1, domain)) { *cp = 0; /* hit it */ break; } else { cp++; } } } } static unsigned long forgemask(unsigned long a) { unsigned long m; if (IN_CLASSA(a)) m = IN_CLASSA_NET; else if (IN_CLASSB(a)) m = IN_CLASSB_NET; else m = IN_CLASSC_NET; return (m); } static void domask(char *dst, unsigned long addr, unsigned long mask) { int b, i; if (!mask || (forgemask(addr) == mask)) { *dst = '\0'; return; } i = 0; for (b = 0; b < 32; b++) if (mask & (1 << b)) { int bb; i = b; for (bb = b+1; bb < 32; bb++) if (!(mask & (1 << bb))) { i = -1; /* noncontig */ break; } break; } if (i == -1) sprintf(dst, "&0x%lx", mask); else sprintf(dst, "/%d", 32 - i); } /* * Return the name of the network whose address is given. * The address is assumed to be that of a net or subnet, not a host. */ char *netname(uint32_t addr, uint32_t mask) { static char line[MAXHOSTNAMELEN + 4]; uint32_t omask; uint32_t i; i = ntohl(addr); omask = mask = ntohl(mask); if ((i & 0xffffff) == 0) sprintf(line, "%u", C(i >> 24)); else if ((i & 0xffff) == 0) sprintf(line, "%u.%u", C(i >> 24) , C(i >> 16)); else if ((i & 0xff) == 0) sprintf(line, "%u.%u.%u", C(i >> 24), C(i >> 16), C(i >> 8)); else sprintf(line, "%u.%u.%u.%u", C(i >> 24), C(i >> 16), C(i >> 8), C(i)); domask(line+strlen(line), i, omask); return (line); }
y-sira/overlayweaver
native/ipmulticast/igmp.c
<filename>native/ipmulticast/igmp.c /* * Copyright 2006 National Institute of Advanced Industrial Science * and Technology (AIST), and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" int igmp_socket; uint32_t selfaddr; uint32_t allhostsgroup; uint32_t allroutersgroup; uint32_t allv3routersgroup; static char *recvbuf = NULL; static char *sendbuf = NULL; static char igmp_kind_string[21]; static int loop = MULTICAST_LOOP; static char *igmp_packet_kind(char *buf, size_t bufLen, uint8_t type, uint8_t code); /* * Open and initialize an IGMP socket. */ int init_igmp(char *ifName) { struct ip *ip; if (recvbuf != NULL) free(recvbuf); if (sendbuf != NULL) free(sendbuf); recvbuf = malloc(BUF_SIZE); sendbuf = malloc(BUF_SIZE); // create a raw socket if ((igmp_socket = socket(PF_INET, SOCK_RAW, IPPROTO_IGMP)) < 0) { log(LOG_ERR, errno, "Failed to create a raw socket. You may have to be the \"root\" user to have priviledge."); return -1; } #if 0 // examine self IP addresses { struct ifconf ifc; int numIfreq = 32; struct ifreq *ifrp; struct ifreq *ifrEnd; int n; uint32_t addr; ifc.ifc_len = numIfreq * sizeof(struct ifreq); ifc.ifc_buf = calloc(ifc.ifc_len, sizeof(uint8_t)); while (ifc.ifc_buf) { char * newBuf; ioctl(igmp_socket, SIOCGIFCONF, (char *)&ifc); if ((ifc.ifc_len + sizeof(struct ifreq)) <= (numIfreq * sizeof(struct ifreq))) { break; } numIfreq *= 2; ifc.ifc_len = numIfreq * sizeof(struct ifreq); newBuf = realloc(ifc.ifc_buf, ifc.ifc_len); if (newBuf == NULL) { free(ifc.ifc_buf); } ifc.ifc_buf = newBuf; } if (ifc.ifc_buf == NULL) { log(LOG_ERR, 0, "Failed in malloc()."); return -1; } ifrp = (struct ifreq *)ifc.ifc_buf; ifrEnd = (struct ifreq *)(ifc.ifc_buf + ifc.ifc_len); for ( ; ifrp < ifrEnd; ifrp = (struct ifreq *)((char *)ifrp + n)) { #ifdef HAVE_SA_LEN n = ifrp->ifr_addr.sa_len + sizeof(ifrp->ifr_name); if (n < sizeof(*ifrp)) { n = sizeof(*ifrp); } #else n = sizeof(*ifrp); #endif if (ifrp->ifr_addr.sa_family != AF_INET) { // ignore continue; } memcpy(ifr.ifr_name, ifrp->ifr_name, sizeof(ifr.ifr_name)); if (ioctl(igmp_socket, SIOCGIFFLAGS, (char *)&ifr) < 0) { log(LOG_ERR, errno, "Failed in ioctl(2) SIOCGIFFLAGS for %s.\n", ifrp->ifr_name); continue; } if ((ifr.ifr_flags & (IFF_LOOPBACK | IFF_MULTICAST)) != IFF_MULTICAST) { // ignore loopback interface continue; } if (ifName != NULL) { if (strncmp(ifName, ifrp->ifr_name, sizeof(ifrp->ifr_name))) { // found interface has a different name from the specified one continue; } } // use an interface found first ifName = ifrp->ifr_name; selfaddr = ((struct sockaddr_in *)&ifrp->ifr_addr)->sin_addr.s_addr; printf("name: %s\n", ifName); printf("addr: %s\n", inet_fmt(selfaddr, s1)); } free(ifc.ifc_buf); } #endif k_hdr_include(igmp_socket, TRUE); k_set_sndbuf(igmp_socket, SEND_BUF_MAX_SIZE, SEND_BUF_MIN_SIZE); k_set_rcvbuf(igmp_socket, RECV_BUF_MAX_SIZE, RECV_BUF_MIN_SIZE); k_set_ttl(igmp_socket, 1); k_set_loop(igmp_socket, loop); k_hdr_include(igmp_socket, TRUE); k_set_sndbuf(igmp_socket, SEND_BUF_MAX_SIZE, SEND_BUF_MIN_SIZE); k_set_rcvbuf(igmp_socket, RECV_BUF_MAX_SIZE, RECV_BUF_MIN_SIZE); k_set_ttl(igmp_socket, 1); k_set_loop(igmp_socket, loop); // initialize IP header ip = (struct ip *)sendbuf; memset((void *)ip, 0, sizeof(struct ip)); ip->ip_v = IPVERSION; ip->ip_hl = sizeof(struct ip) >> 2; ip->ip_tos = IPTOS_PREC_INTERNETCONTROL; // 0xc0 ip->ip_ttl = MAXTTL; ip->ip_p = IPPROTO_IGMP; ip->ip_sum = 0; // kernel fills in // initialize addresses allhostsgroup = htonl(INADDR_ALLHOSTS_GROUP); allroutersgroup = htonl(INADDR_ALLRTRS_GROUP); allv3routersgroup = htonl(INADDR_ALLRPTS_GROUP); return 0; } void stop_igmp() { if (igmp_socket > 0) { close(igmp_socket); igmp_socket = -1; } if (igmp_socket > 0) { close(igmp_socket); igmp_socket = -1; } if (recvbuf != NULL) { free(recvbuf); recvbuf = NULL; } if (sendbuf != NULL) { free(sendbuf); sendbuf = NULL; } } int send_igmp(uint32_t src, uint32_t dest, int type, int code, int32_t group, char *data, int datalen) { struct ip *ip; struct igmp *igmp; int sendlen; int setloop = FALSE; struct sockaddr_in destsock; char *buf = sendbuf; // prepare IP header ip = (struct ip *)buf; ip->ip_len = sizeof(struct ip) + IGMP_MINLEN + datalen; ip->ip_src.s_addr = src; ip->ip_dst.s_addr = dest; sendlen = ip->ip_len; #if defined(RAW_OUTPUT_IS_RAW) || defined(OpenBSD) ip->ip_len = htons(ip->ip_len); #endif igmp = (struct igmp *)(buf + sizeof(struct ip)); igmp->igmp_type = (uint8_t)type; igmp->igmp_code = (uint8_t)code; igmp->igmp_group.s_addr = group; if (data != NULL) { if (sizeof(struct ip) + IGMP_MINLEN + datalen > BUF_SIZE) { datalen = BUF_SIZE - (sizeof(struct ip) + IGMP_MINLEN); log(LOG_WARNING, 0, "Given data is too large: %d\n", datalen); } memcpy((char *)(buf + sizeof(struct ip) + IGMP_MINLEN), data, datalen); } igmp->igmp_cksum = 0; igmp->igmp_cksum = inet_cksum((uint16_t *)igmp, IGMP_MINLEN + datalen, 0); if (IN_MULTICAST(ntohl(dest))) { k_set_if(igmp_socket, src); if (type != IGMP_DVMRP || dest == allhostsgroup) { setloop = TRUE; k_set_loop(igmp_socket, TRUE); } #ifdef RAW_OUTPUT_IS_RAW ip->ip_ttl = curttl; } else { ip->ip_ttl = MAXTTL; #endif } memset((void *)&destsock, 0, sizeof(destsock)); destsock.sin_family = PF_INET; #ifdef HAVE_SA_LEN destsock.sin_len = sizeof(destsock); #endif destsock.sin_addr.s_addr = dest; if (sendto(igmp_socket, sendbuf, sendlen, 0, (struct sockaddr *)&destsock, sizeof(destsock)) < 0) { log(LOG_ERR, errno, "Failed in sendto(2) to %s on %s.", inet_fmt(dest, s1), inet_fmt(src, s2)); if (setloop) { k_set_loop(igmp_socket, loop); } return -1; } if (setloop) { k_set_loop(igmp_socket, loop); } return 0; } int recv_igmp(struct ip **ipp, struct igmp **igmpp, char *data, int *datalenp, int maxdatasize) { uint32_t src, dest, group; struct ip *ip; struct igmp *igmp; int ipheaderlen, ipdatalen, igmpdatalen; int recvlen; // receive while (TRUE) { socklen_t fromlen; recvlen = recvfrom(igmp_socket, recvbuf, BUF_SIZE, 0, NULL, &fromlen); if (recvlen < 0) { if (errno != EINTR) { log(LOG_ERR, errno, "recv(2) returned -1."); } return -1; } if (recvbuf == NULL) { // IGMP subsystem has been stopped // Note that recvfrom(2) returns a non-negative number even though interrupted. return -1; } if (recvlen < sizeof (struct ip)) { log(LOG_WARNING, 0, "Received packet is too short: %d", recvlen); continue; } ip = (struct ip *)recvbuf; src = ip->ip_src.s_addr; dest = ip->ip_dst.s_addr; if (ip->ip_p == 0) { // message from kernel if (src == 0 || dest == 0) { log(LOG_WARNING, 0, "Message from kernel is not accurate."); } else { // do nothing } continue; } ipheaderlen = ip->ip_hl << 2; #ifdef RAW_INPUT_IS_RAW ipdatalen = ntohs(ip->ip_len) - ipheaderlen; #else ipdatalen = ip->ip_len; #endif if (ipheaderlen + ipdatalen != recvlen) { log(LOG_WARNING, 0, "Received packet from %s is shorter (%u bytes) than header+data length (%u+%u).", inet_fmt(src, s1), recvlen, ipheaderlen, ipdatalen); continue; } igmp = (struct igmp *)(recvbuf + ipheaderlen); group = igmp->igmp_group.s_addr; igmpdatalen = ipdatalen - IGMP_MINLEN; if (igmpdatalen < 0) { log(LOG_WARNING, 0, "Received IP data field is too short (%u bytes) for IGMP, from %s", ipdatalen, inet_fmt(src, s1)); continue; } if (ipp != NULL) *ipp = ip; if (igmpp != NULL) *igmpp = igmp; if (datalenp != NULL) { *datalenp = ipdatalen; } if ((ipdatalen > 0) && (data != NULL)) { int len = MIN(ipdatalen, maxdatasize); memcpy(data, recvbuf + ipheaderlen, len); // including entire IGMP packet } #if 0 printf("received packet: %s\n", igmp_packet_kind(igmp_kind_string, sizeof(igmp_kind_string), igmp->igmp_type, igmp->igmp_code)); printf(" src: %s\n", inet_fmt(src, s1)); printf(" dest: %s\n", inet_fmt(dest, s1)); fflush(stdout); #endif return 0; } } static char *igmp_packet_kind(char *buf, size_t bufLen, uint8_t type, uint8_t code) { switch (type) { case IGMP_MEMBERSHIP_QUERY: return "membership query"; case IGMP_V1_MEMBERSHIP_REPORT: return "V1 membership report"; case IGMP_V2_MEMBERSHIP_REPORT: return "V2 membership report"; case IGMP_V2_LEAVE_GROUP: return "V2 leave group"; case IGMP_DVMRP: return "DVMRP related"; case IGMP_PIM: return "PIM related"; case IGMP_MTRACE: return "trace query"; case IGMP_MTRACE_RESP: return "trace reply"; default: snprintf(buf, bufLen, "unknown: 0x%02x/0x%02x", type, code); return buf; } }
y-sira/overlayweaver
native/ipmulticast/kern.c
/* * Copyright (c) 1998-2001 * University of Southern California/Information Sciences Institute. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Id: kern.c,v 1.24 2003/02/12 21:56:55 pavlin Exp */ /* * Part of this program has been derived from mrouted. * The mrouted program is covered by the license in the accompanying file * named "LICENSE.mrouted". * * The mrouted program is COPYRIGHT 1989 by The Board of Trustees of * Leland Stanford Junior University. * */ #include "common.h" #ifdef RAW_OUTPUT_IS_RAW int curttl = 0; #endif /* * XXX: in *BSD there is only MRT_ASSERT, but in Linux there are * both MRT_ASSERT and MRT_PIM */ #ifndef MRT_PIM #define MRT_PIM MRT_ASSERT #endif /* MRT_PIM */ /* * Open/init the multicast routing in the kernel and sets the * MRT_PIM (aka MRT_ASSERT) flag in the kernel. */ void k_init_pim(int socket) { int v = 1; if (setsockopt(socket, IPPROTO_IP, MRT_INIT, (char *)&v, sizeof(int)) < 0) log(LOG_ERR, errno, "cannot enable multicast routing in kernel"); #if 0 // by Shudo if (setsockopt(socket, IPPROTO_IP, MRT_PIM, (char *)&v, sizeof(int)) < 0) log(LOG_ERR, errno, "cannot set PIM flag in kernel"); #endif } /* * Stops the multicast routing in the kernel and resets the * MRT_PIM (aka MRT_ASSERT) flag in the kernel. */ void k_stop_pim(int socket) { #if 0 // by Shudo int v = 0; if (setsockopt(socket, IPPROTO_IP, MRT_PIM, (char *)&v, sizeof(int)) < 0) log(LOG_ERR, errno, "cannot reset PIM flag in kernel"); #endif if (setsockopt(socket, IPPROTO_IP, MRT_DONE, (char *)NULL, 0) < 0) log(LOG_ERR, errno, "cannot disable multicast routing in kernel"); } /* * Set the socket sending buffer. `bufsize` is the preferred size, * `minsize` is the smallest acceptable size. */ void k_set_sndbuf(int socket, int bufsize, int minsize) { int delta = bufsize / 2; int iter = 0; /* * Set the socket buffer. If we can't set it as large as we * want, search around to try to find the highest acceptable * value. The highest acceptable value being smaller than * minsize is a fatal error. */ if (setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char *)&bufsize, sizeof(bufsize)) < 0) { bufsize -= delta; while (1) { iter++; if (delta > 1) delta /= 2; if (setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char *)&bufsize, sizeof(bufsize)) < 0) { bufsize -= delta; } else { if (delta < 1024) break; bufsize += delta; } } if (bufsize < minsize) { log(LOG_ERR, 0, "OS-allowed send buffer size %u < app min %u", bufsize, minsize); /*NOTREACHED*/ } } #if 0 // by Shudo IF_DEBUG(DEBUG_KERN) log(LOG_DEBUG, 0, "Got %d byte send buffer size in %d iterations", bufsize, iter); #endif } /* * Set the socket receiving buffer. `bufsize` is the preferred size, * `minsize` is the smallest acceptable size. */ void k_set_rcvbuf(int socket, int bufsize, int minsize) { int delta = bufsize / 2; int iter = 0; /* * Set the socket buffer. If we can't set it as large as we * want, search around to try to find the highest acceptable * value. The highest acceptable value being smaller than * minsize is a fatal error. */ if (setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char *)&bufsize, sizeof(bufsize)) < 0) { bufsize -= delta; while (1) { iter++; if (delta > 1) delta /= 2; if (setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char *)&bufsize, sizeof(bufsize)) < 0) { bufsize -= delta; } else { if (delta < 1024) break; bufsize += delta; } } if (bufsize < minsize) { log(LOG_ERR, 0, "OS-allowed recv buffer size %u < app min %u", bufsize, minsize); /*NOTREACHED*/ } } #if 0 // by Shudo IF_DEBUG(DEBUG_KERN) log(LOG_DEBUG, 0, "Got %d byte recv buffer size in %d iterations", bufsize, iter); #endif } /* * Set/reset the IP_HDRINCL option. My guess is we don't need it for raw * sockets, but having it here won't hurt. Well, unless you are running * an older version of FreeBSD (older than 2.2.2). If the multicast * raw packet is bigger than 208 bytes, then IP_HDRINCL triggers a bug * in the kernel and "panic". The kernel patch for netinet/ip_raw.c * coming with this distribution fixes it. */ void k_hdr_include(int socket, int bool) { #ifdef IP_HDRINCL if (setsockopt(socket, IPPROTO_IP, IP_HDRINCL, (char *)&bool, sizeof(bool)) < 0) log(LOG_ERR, errno, "setsockopt IP_HDRINCL %u", bool); #endif } /* * Set the default TTL for the multicast packets outgoing from this * socket. * TODO: Does it affect the unicast packets? */ void k_set_ttl(int socket, int t) { #ifdef RAW_OUTPUT_IS_RAW curttl = t; #else u_char ttl; ttl = t; if (setsockopt(socket, IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(ttl)) < 0) log(LOG_ERR, errno, "setsockopt IP_MULTICAST_TTL %u", ttl); #endif } /* * Set/reset the IP_MULTICAST_LOOP. Set/reset is specified by "flag". */ void k_set_loop(int socket, int flag) { u_char loop; loop = flag; if (setsockopt(socket, IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&loop, sizeof(loop)) < 0) log(LOG_ERR, errno, "setsockopt IP_MULTICAST_LOOP %u", loop); } /* * Set the IP_MULTICAST_IF option on local interface ifa. */ void k_set_if(int socket, uint32_t ifa) { struct in_addr adr; adr.s_addr = ifa; if (setsockopt(socket, IPPROTO_IP, IP_MULTICAST_IF, (char *)&adr, sizeof(adr)) < 0) log(LOG_ERR, errno, "setsockopt IP_MULTICAST_IF %s", inet_fmt(ifa, s1)); } /* * Join a multicast group on virtual interface 'v'. */ void k_join(int socket, uint32_t grp, struct uvif *v) { #ifdef linux struct ip_mreqn mreq; #else struct ip_mreq mreq; #endif /* linux */ #ifdef linux mreq.imr_ifindex = v->uv_ifindex; mreq.imr_address.s_addr = v->uv_lcl_addr; #else mreq.imr_interface.s_addr = v->uv_lcl_addr; #endif /* linux */ mreq.imr_multiaddr.s_addr = grp; if (setsockopt(socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mreq, sizeof(mreq)) < 0) { #ifdef linux log(LOG_WARNING, errno, "cannot join group %s on interface %s (ifindex %d)", inet_fmt(grp, s1), inet_fmt(v->uv_lcl_addr, s2), v->uv_ifindex); #else log(LOG_WARNING, errno, "cannot join group %s on interface %s", inet_fmt(grp, s1), inet_fmt(v->uv_lcl_addr, s2)); #endif /* linux */ } } /* * Leave a multicast group on virtual interface 'v'. */ void k_leave(int socket, uint32_t grp, struct uvif *v) { #ifdef linux struct ip_mreqn mreq; #else struct ip_mreq mreq; #endif /* linux */ #ifdef linux mreq.imr_ifindex = v->uv_ifindex; mreq.imr_address.s_addr = v->uv_lcl_addr; #else mreq.imr_interface.s_addr = v->uv_lcl_addr; #endif /* linux */ mreq.imr_multiaddr.s_addr = grp; if (setsockopt(socket, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&mreq, sizeof(mreq)) < 0) { #ifdef linux log(LOG_WARNING, errno, "cannot leave group %s on interface %s (ifindex %d)", inet_fmt(grp, s1), inet_fmt(v->uv_lcl_addr, s2), v->uv_ifindex); #else log(LOG_WARNING, errno, "cannot leave group %s on interface %s", inet_fmt(grp, s1), inet_fmt(v->uv_lcl_addr, s2)); #endif /* linux */ } } /* * Add a virtual interface in the kernel. */ void k_add_vif(int socket, vifi_t vifi, struct uvif *v) { struct vifctl vc; vc.vifc_vifi = vifi; /* XXX: we don't support VIFF_TUNNEL; VIFF_SRCRT is obsolete */ vc.vifc_flags = 0; if (v->uv_flags & VIFF_REGISTER) vc.vifc_flags |= VIFF_REGISTER; vc.vifc_threshold = v->uv_threshold; vc.vifc_rate_limit = v->uv_rate_limit; vc.vifc_lcl_addr.s_addr = v->uv_lcl_addr; vc.vifc_rmt_addr.s_addr = v->uv_rmt_addr; if (setsockopt(socket, IPPROTO_IP, MRT_ADD_VIF, (char *)&vc, sizeof(vc)) < 0) log(LOG_ERR, errno, "setsockopt MRT_ADD_VIF on vif %d", vifi); } /* * Delete a virtual interface in the kernel. */ void k_del_vif(int socket, vifi_t vifi) { if (setsockopt(socket, IPPROTO_IP, MRT_DEL_VIF, (char *)&vifi, sizeof(vifi)) < 0) log(LOG_ERR, errno, "setsockopt MRT_DEL_VIF on vif %d", vifi); } #if 0 // by Shudo /* * Delete all MFC entries for particular routing entry from the kernel. */ int k_del_mfc(int socket, uint32_t source, uint32_t group) { struct mfcctl mc; mc.mfcc_origin.s_addr = source; mc.mfcc_mcastgrp.s_addr = group; if (setsockopt(socket, IPPROTO_IP, MRT_DEL_MFC, (char *)&mc, sizeof(mc)) < 0) { log(LOG_WARNING, errno, "setsockopt k_del_mfc"); return FALSE; } IF_DEBUG(DEBUG_MFC) log(LOG_DEBUG, 0, "Deleted MFC entry: src %s, grp %s", inet_fmt(mc.mfcc_origin.s_addr, s1), inet_fmt(mc.mfcc_mcastgrp.s_addr, s2)); return(TRUE); } /* * Install/modify a MFC entry in the kernel */ int k_chg_mfc(int socket, uint32_t source, uint32_t group, vifi_t iif, vifbitmap_t oifs, uint32_t rp_addr) { struct mfcctl mc; vifi_t vifi; struct uvif *v; mc.mfcc_origin.s_addr = source; #ifdef OLD_KERNEL mc.mfcc_originmas.s_addr = 0xffffffff; /* Got it from mrouted-3.9 */ #endif /* OLD_KERNEL */ mc.mfcc_mcastgrp.s_addr = group; mc.mfcc_parent = iif; /* * draft-ietf-pim-sm-v2-new-05.txt section 4.2 mentions iif is removed * at the packet forwarding phase */ VIFM_CLR(mc.mfcc_parent, oifs); for (vifi = 0, v = uvifs; vifi < numvifs; vifi++, v++) { if (VIFM_ISSET(vifi, oifs)) mc.mfcc_ttls[vifi] = v->uv_threshold; else mc.mfcc_ttls[vifi] = 0; } #ifdef PIM_REG_KERNEL_ENCAP mc.mfcc_rp_addr.s_addr = rp_addr; #endif if (setsockopt(socket, IPPROTO_IP, MRT_ADD_MFC, (char *)&mc, sizeof(mc)) < 0) { log(LOG_WARNING, errno, "setsockopt MRT_ADD_MFC for source %s and group %s", inet_fmt(source, s1), inet_fmt(group, s2)); return(FALSE); } return(TRUE); } /* * Get packet counters for particular interface */ /* * XXX: TODO: currently not used, but keep just in case we need it later. */ int k_get_vif_count(vifi_t vifi, struct vif_count *retval) { struct sioc_vif_req vreq; vreq.vifi = vifi; if (ioctl(udp_socket, SIOCGETVIFCNT, (char *)&vreq) < 0) { log(LOG_WARNING, errno, "SIOCGETVIFCNT on vif %d", vifi); retval->icount = retval->ocount = retval->ibytes = retval->obytes = 0xffffffff; return (1); } retval->icount = vreq.icount; retval->ocount = vreq.ocount; retval->ibytes = vreq.ibytes; retval->obytes = vreq.obytes; return (0); } /* * Gets the number of packets, bytes, and number op packets arrived * on wrong if in the kernel for particular (S,G) entry. */ int k_get_sg_cnt(int socket, uint32_t source, uint32_t group, struct sg_count *retval) { struct sioc_sg_req sgreq; sgreq.src.s_addr = source; sgreq.grp.s_addr = group; if ((ioctl(socket, SIOCGETSGCNT, (char *)&sgreq) < 0) || (sgreq.wrong_if == 0xffffffff)) { /* XXX: ipmulti-3.5 has bug in ip_mroute.c, get_sg_cnt(): * the return code is always 0, so this is why we need to check * the wrong_if value. */ log(LOG_WARNING, errno, "SIOCGETSGCNT on (%s %s)", inet_fmt(source, s1), inet_fmt(group, s2)); retval->pktcnt = retval->bytecnt = retval->wrong_if = ~0; return(1); } retval->pktcnt = sgreq.pktcnt; retval->bytecnt = sgreq.bytecnt; retval->wrong_if = sgreq.wrong_if; return(0); } #endif // if 0
y-sira/overlayweaver
native/ipmulticast/vif.c
<gh_stars>10-100 /* * This file has been derived from pimd-2.1.0-alpha29.17. * The pimd program is covered by the license in the accompanying file * named "LICENSE.pimd-2.1.0-alpha29.17". * * Part of the pimd program has been derived from mrouted. * The mrouted program is covered by the license in the accompanying file * named "LICENSE.mtouted". */ #include "common.h" /* * Exported variables. */ struct uvif uvifs[MAXVIFS]; /* array of all virtual interfaces */ vifi_t numvifs; /* Number of vifs in use */ int vifs_down; /* 1=>some interfaces are down */ int phys_vif; /* An enabled vif */ vifi_t reg_vif_num; /* really virtual interface for registers */ int udp_socket; /* Since the honkin' kernel doesn't support */ /* ioctls on raw IP sockets, we need a UDP */ /* socket as well as our IGMP (raw) socket. */ /* How dumb. */ int total_interfaces; /* Number of all interfaces: including the * non-configured, but excluding the * loopback interface and the non-multicast * capable interfaces. */ static int init_reg_vif(); static void start_all_vifs(); static void start_vif(vifi_t vifi); static void stop_vif(vifi_t vifi); void init_vifs() { vifi_t vifi; struct uvif *v; int enabled_vifs; numvifs = 0; reg_vif_num = NO_VIF; vifs_down = FALSE; /* * Configure the vifs based on the interface configuration of the * the kernel and the contents of the configuration file. * (Open a UDP socket for ioctl use in the config procedures if * the kernel can't handle IOCTL's on the IGMP socket.) */ #ifdef IOCTL_OK_ON_RAW_SOCKET udp_socket = igmp_socket; #else if ((udp_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) log(LOG_ERR, errno, "UDP socket"); #endif /* * Clean up all vifs */ for (vifi = 0, v = uvifs; vifi < MAXVIFS; ++vifi, ++v) { zero_vif(v, FALSE); } log(LOG_INFO, 0, "Getting vifs from kernel"); config_vifs_from_kernel(); #if 0 // by Shudo log(LOG_INFO, 0, "Getting vifs from %s", configfilename); config_vifs_from_file(); #endif /* * Quit if there are fewer than two enabled vifs. */ enabled_vifs = 0; phys_vif = -1; for (vifi = 0, v = uvifs; vifi < numvifs; ++vifi, ++v) { /* Initialize the outgoing timeout for each vif. * Currently use a fixed time 'PIM_JOIN_PRUNE_HOLDTIME'. * Later, may add a configurable array to feed these * parameters, or compute them as function of the i/f * bandwidth and the overall connectivity...etc. */ #if 0 // by Shudo SET_TIMER(v->uv_jp_timer, PIM_JOIN_PRUNE_HOLDTIME); #endif if (v->uv_flags & (VIFF_DISABLED | VIFF_DOWN | VIFF_REGISTER | VIFF_TUNNEL)) continue; if (phys_vif == -1) phys_vif = vifi; enabled_vifs++; } if (enabled_vifs < 1) /* XXX: TODO: */ log(LOG_ERR, 0, "can't forward: %s", enabled_vifs == 0 ? "no enabled vifs" : "only one enabled vif"); k_init_pim(igmp_socket); /* Call to kernel to initialize structures */ /* Add a dummy virtual interface to support Registers in the kernel. * In order for this to work, the kernel has to have been modified * with the PIM patches to ip_mroute.{c,h} and ip.c */ init_reg_vif(); start_all_vifs(); } /* * Initialize the passed vif with all appropriate default values. * "t" is true if a tunnel or register_vif, or false if a phyint. */ void zero_vif(struct uvif *v, int t) { v->uv_flags = 0; v->uv_metric = DEFAULT_METRIC; v->uv_admetric = 0; v->uv_threshold = DEFAULT_THRESHOLD; v->uv_rate_limit = t ? DEFAULT_REG_RATE_LIMIT : DEFAULT_PHY_RATE_LIMIT; v->uv_lcl_addr = INADDR_ANY_N; v->uv_rmt_addr = INADDR_ANY_N; #if 0 // by Shudo v->uv_dst_addr = t ? INADDR_ANY_N : allpimrouters_group; #else v->uv_dst_addr = INADDR_ANY_N; #endif v->uv_subnet = INADDR_ANY_N; v->uv_subnetmask = INADDR_ANY_N; v->uv_subnetbcast = INADDR_ANY_N; strncpy(v->uv_name, "", IFNAMSIZ); v->uv_groups = (struct listaddr *)NULL; v->uv_dvmrp_neighbors = (struct listaddr *)NULL; NBRM_CLRALL(v->uv_nbrmap); v->uv_querier = (struct listaddr *)NULL; v->uv_igmpv1_warn = 0; v->uv_prune_lifetime = 0; v->uv_acl = (struct vif_acl *)NULL; #if 0 // by Shudo RESET_TIMER(v->uv_leaf_timer); #endif v->uv_addrs = (struct phaddr *)NULL; v->uv_filter = (struct vif_filter *)NULL; #if 0 // by Shudo RESET_TIMER(v->uv_pim_hello_timer); RESET_TIMER(v->uv_gq_timer); RESET_TIMER(v->uv_jp_timer); #endif #if 0 // by Shudo v->uv_pim_neighbors = (struct pim_nbr_entry *)NULL; #endif #if 0 // by Shudo v->uv_local_pref = default_source_preference; v->uv_local_metric = default_source_metric; #else v->uv_local_pref = UCAST_DEFAULT_SOURCE_PREFERENCE; v->uv_local_metric = UCAST_DEFAULT_SOURCE_METRIC; #endif #ifdef linux v->uv_ifindex = -1; #endif /* linux */ } /* * Add a (the) register vif to the vif table. */ static int init_reg_vif() { struct uvif *v; vifi_t i; v = &uvifs[numvifs]; v->uv_flags = 0; /* initialization */ if ((numvifs + 1) == MAXVIFS) { /* Exit the program! The PIM router must have a Register vif */ log(LOG_ERR, 0, "cannot install the Register vif: too many interfaces"); /* To make lint happy */ return (FALSE); } /* * So far in PIM we need only one register vif and we save its number in * the global reg_vif_num. */ reg_vif_num = numvifs; /* set the REGISTER flag */ v->uv_flags = VIFF_REGISTER; #ifdef PIM_EXPERIMENTAL v->uv_flags |= VIFF_REGISTER_KERNEL_ENCAP; #endif strncpy(v->uv_name,"register_vif0", IFNAMSIZ); /* Use the address of the first available physical interface to * create the register vif. */ for (i = 0; i < numvifs; i++) if (uvifs[i].uv_flags & (VIFF_DOWN | VIFF_DISABLED | VIFF_REGISTER | VIFF_TUNNEL)) continue; else break; if (i >= numvifs) { log(LOG_ERR, 0, "No physical interface enabled"); return -1; } v->uv_lcl_addr = uvifs[i].uv_lcl_addr; v->uv_threshold = MINTTL; numvifs++; total_interfaces++; return 0; } static void start_all_vifs() { vifi_t vifi; struct uvif *v; unsigned int action; /* Start first the NON-REGISTER vifs */ for(action = 0; ; action = VIFF_REGISTER) { for (vifi = 0, v = uvifs; vifi < numvifs; ++vifi, ++v) { if ((v->uv_flags & VIFF_REGISTER) ^ action) /* If starting non-registers but the vif is a register * or if starting registers, but the interface is not * a register, then just continue. */ continue; /* Start vif if not DISABLED or DOWN */ if (v->uv_flags & (VIFF_DISABLED | VIFF_DOWN)) { if (v->uv_flags & VIFF_DISABLED) log(LOG_INFO, 0, "%s is DISABLED; vif #%u out of service", v->uv_name, vifi); else log(LOG_INFO, 0, "%s is DOWN; vif #%u out of service", v->uv_name, vifi); } else start_vif(vifi); } if (action == VIFF_REGISTER) break; /* We are done */ } } /* * stop all vifs */ void stop_all_vifs() { vifi_t vifi; for (vifi = 0; vifi < numvifs; vifi++) { stop_vif(vifi); } } /* * Initialize the vif and add to the kernel. The vif can be either * physical, register or tunnel (tunnels will be used in the future * when this code becomes PIM multicast boarder router. */ static void start_vif(vifi_t vifi) { struct uvif *v; uint32_t src; v = &uvifs[vifi]; src = v->uv_lcl_addr; /* Initialy no router on any vif */ if (v->uv_flags & VIFF_REGISTER) v->uv_flags = v->uv_flags & ~VIFF_DOWN; else { v->uv_flags = (v->uv_flags | VIFF_DR | VIFF_NONBRS) & ~VIFF_DOWN; #if 0 // by Shudo SET_TIMER(v->uv_pim_hello_timer, 1 + RANDOM() % PIM_TIMER_HELLO_PERIOD); SET_TIMER(v->uv_jp_timer, 1 + RANDOM() % PIM_JOIN_PRUNE_PERIOD); /* TODO: CHECK THE TIMERS!!!!! Set or reset? */ RESET_TIMER(v->uv_gq_timer); v->uv_pim_neighbors = (pim_nbr_entry_t *)NULL; #endif } /* Tell kernel to add, i.e. start this vif */ k_add_vif(igmp_socket, vifi, &uvifs[vifi]); log(LOG_INFO, 0, "%s comes up; vif #%u now in service", v->uv_name, vifi); if (!(v->uv_flags & VIFF_REGISTER)) { #if 0 // by Shudo /* * Join the PIM multicast group on the interface. */ k_join(igmp_socket, allpimrouters_group, v); #endif /* * Join the ALL-ROUTERS multicast group on the interface. * This allows mtrace requests to loop back if they are run * on the multicast router. */ k_join(igmp_socket, allroutersgroup, v); k_join(igmp_socket, allv3routersgroup, v); // for IGMPv3 /* * Until neighbors are discovered, assume responsibility for sending * periodic group membership queries to the subnet. Send the first * query. */ v->uv_flags |= VIFF_QUERIER; #if 0 // by Shudo, this process is to be implemented in an upper layer query_groups(v); #endif #if 0 // by Shudo /* * Send a probe via the new vif to look for neighbors. */ send_pim_hello(v, PIM_TIMER_HELLO_HOLDTIME); #endif } #ifdef linux else { struct ifreq ifr; memset(&ifr, 0, sizeof(struct ifreq)); /* strncpy(ifr.ifr_name,v->uv_name, IFNAMSIZ); */ strncpy(ifr.ifr_name, "pimreg", IFNAMSIZ); if (ioctl(udp_socket, SIOGIFINDEX, (char *) &ifr) < 0) { log(LOG_ERR, errno, "ioctl SIOGIFINDEX for %s", ifr.ifr_name); /* Not reached */ return; } v->uv_ifindex = ifr.ifr_ifindex; } #endif /* linux */ } /* * Stop a vif (either physical interface, tunnel or * register.) If we are running only PIM we don't have tunnels. */ static void stop_vif(vifi_t vifi) { struct uvif *v; struct listaddr *a; #if 0 // by Shudo register pim_nbr_entry_t *n, *next; #endif struct vif_acl *acl; /* * TODO: make sure that the kernel viftable is * consistent with the daemon table */ v = &uvifs[vifi]; if (!(v->uv_flags & VIFF_REGISTER)) { #if 0 // by Shudo k_leave(igmp_socket, allpimrouters_group, v); #endif k_leave(igmp_socket, allroutersgroup, v); /* * Discard all group addresses. (No need to tell kernel; * the k_del_vif() call will clean up kernel state.) */ while (v->uv_groups != NULL) { a = v->uv_groups; v->uv_groups = a->al_next; free((char *)a); } } /* * TODO: inform (eventually) the neighbors I am going down by sending * PIM_HELLO with holdtime=0 so someone else should become a DR. */ /* TODO: dummy! Implement it!! Any problems if don't use it? */ #if 0 // by Shudo delete_vif_from_mrt(vifi); #endif /* * Delete the interface from the kernel's vif structure. */ k_del_vif(igmp_socket, vifi); v->uv_flags = (v->uv_flags & ~VIFF_DR & ~VIFF_QUERIER & ~VIFF_NONBRS ) | VIFF_DOWN; if (!(v->uv_flags & VIFF_REGISTER)) { #if 0 // by Shudo RESET_TIMER(v->uv_pim_hello_timer); RESET_TIMER(v->uv_jp_timer); RESET_TIMER(v->uv_gq_timer); #endif #if 0 // by Shudo for (n = v->uv_pim_neighbors; n != NULL; n = next) { next = n->next; /* Free the space for each neighbour */ free((char *)n); } v->uv_pim_neighbors = NULL; #endif } /* TODO: currently not used */ /* The Access Control List (list with the scoped addresses) */ while (v->uv_acl != NULL) { acl = v->uv_acl; v->uv_acl = acl->acl_next; free((char *)acl); } vifs_down = TRUE; log(LOG_INFO, 0, "%s goes down; vif #%u out of service", v->uv_name, vifi); }
y-sira/overlayweaver
native/ipmulticast/glue.c
<filename>native/ipmulticast/glue.c /* * Copyright 2006,2008 National Institute of Advanced Industrial Science * and Technology (AIST), and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <jni.h> #include "ow_ipmulticast_Native.h" #include "common.h" #define IOEXCEPTION_CLASS_NAME "java/io/IOException" #define NATIVEVIF_CLASS_NAME "ow/ipmulticast/VirtualInterface$NativeVIF" #define IGMPMessage_CLASS_NAME "ow/ipmulticast/IGMP$IGMPMessage" #define MulticastMessage_CLASS_NAME "ow/ipmulticast/IPMulticast$MulticastMessage" static jclass clazz_IOException = NULL; static jfieldID field_NativeVIF_isRegisterVIF = NULL; static jfieldID field_NativeVIF_localAddress = NULL; static jfieldID field_NativeVIF_netmask = NULL; static jfieldID field_NativeVIF_name = NULL; static jfieldID field_NativeVIF_ifIndex = NULL; static jfieldID field_IGMPMessage_src = NULL; static jfieldID field_IGMPMessage_dest = NULL; static jfieldID field_IGMPMessage_type = NULL; static jfieldID field_IGMPMessage_code = NULL; static jfieldID field_IGMPMessage_group = NULL; static jfieldID field_IGMPMessage_data = NULL; static jfieldID field_MulticastMessage_srcaddr = NULL; static jfieldID field_MulticastMessage_srcport = NULL; static jfieldID field_MulticastMessage_destaddr = NULL; static jfieldID field_MulticastMessage_destport = NULL; static jfieldID field_MulticastMessage_id = NULL; static jfieldID field_MulticastMessage_ttl = NULL; static jfieldID field_MulticastMessage_data = NULL; static int initialized = FALSE; JNIEXPORT void JNICALL Java_ow_ipmulticast_Native_initNative(JNIEnv *env, jclass clazz) { if (initialized) return; if (field_IGMPMessage_src == NULL) { jclass class_NativeVIF, class_IGMPMessage, class_MulticastMessage; clazz_IOException = (*env)->FindClass(env, IOEXCEPTION_CLASS_NAME); class_NativeVIF = (*env)->FindClass(env, NATIVEVIF_CLASS_NAME); field_NativeVIF_isRegisterVIF = (*env)->GetFieldID(env, class_NativeVIF, "isRegisterVIF", "Z"); field_NativeVIF_localAddress = (*env)->GetFieldID(env, class_NativeVIF, "localAddress", "I"); field_NativeVIF_netmask = (*env)->GetFieldID(env, class_NativeVIF, "netmask", "I"); field_NativeVIF_name = (*env)->GetFieldID(env, class_NativeVIF, "name", "Ljava/lang/String;"); field_NativeVIF_ifIndex = (*env)->GetFieldID(env, class_NativeVIF, "ifIndex", "I"); class_IGMPMessage = (*env)->FindClass(env, IGMPMessage_CLASS_NAME); field_IGMPMessage_src = (*env)->GetFieldID(env, class_IGMPMessage, "src", "I"); field_IGMPMessage_dest = (*env)->GetFieldID(env, class_IGMPMessage, "dest", "I"); field_IGMPMessage_type = (*env)->GetFieldID(env, class_IGMPMessage, "type", "I"); field_IGMPMessage_code = (*env)->GetFieldID(env, class_IGMPMessage, "code", "I"); field_IGMPMessage_group = (*env)->GetFieldID(env, class_IGMPMessage, "group", "I"); field_IGMPMessage_data = (*env)->GetFieldID(env, class_IGMPMessage, "data", "[B"); class_MulticastMessage = (*env)->FindClass(env, MulticastMessage_CLASS_NAME); field_MulticastMessage_srcaddr = (*env)->GetFieldID(env, class_MulticastMessage, "srcaddr", "I"); field_MulticastMessage_srcport = (*env)->GetFieldID(env, class_MulticastMessage, "srcport", "I"); field_MulticastMessage_destaddr = (*env)->GetFieldID(env, class_MulticastMessage, "destaddr", "I"); field_MulticastMessage_destport = (*env)->GetFieldID(env, class_MulticastMessage, "destport", "I"); field_MulticastMessage_id = (*env)->GetFieldID(env, class_MulticastMessage, "id", "I"); field_MulticastMessage_ttl = (*env)->GetFieldID(env, class_MulticastMessage, "ttl", "I"); field_MulticastMessage_data = (*env)->GetFieldID(env, class_MulticastMessage, "data", "[B"); } // initialize IGMP-related stuff if (init_igmp(NULL) < 0) { (*env)->ThrowNew(env, clazz_IOException, "Failed to create a raw socket for IGMP. It needs \"root\" proviledge."); } // initialize multicast-related stuff if (init_dgram() < 0) { (*env)->ThrowNew(env, clazz_IOException, "Failed to create a raw socket for multicast. It needs \"root\" priviledge."); } // initialize virtual interfaces init_vifs(); initialized = TRUE; } JNIEXPORT void JNICALL Java_ow_ipmulticast_Native_stopNative(JNIEnv *env, jclass clazz) { stop_all_vifs(); stop_igmp(); initialized = FALSE; } JNIEXPORT jint JNICALL Java_ow_ipmulticast_Native_numberOfVIFs(JNIEnv *env, jclass clazz) { return (jint) /* vifi_t is unsigned short */ numvifs; } JNIEXPORT void JNICALL Java_ow_ipmulticast_Native_fillVIFs(JNIEnv *env, jclass clazz, jobjectArray nativeVIFArray) { jsize arraylen = (*env)->GetArrayLength(env, nativeVIFArray); jsize i; for (i = 0; i < arraylen; i++) { struct uvif *v = &uvifs[i]; jobject nativeVIF, nameString; nameString = (*env)->NewStringUTF(env, v->uv_name); nativeVIF = (*env)->GetObjectArrayElement(env, nativeVIFArray, i); (*env)->SetBooleanField(env, nativeVIF, field_NativeVIF_isRegisterVIF, (jboolean) (v->uv_flags & VIFF_REGISTER)); (*env)->SetIntField(env, nativeVIF, field_NativeVIF_localAddress, (jint) /*uint32_t*/ htonl(v->uv_lcl_addr)); (*env)->SetIntField(env, nativeVIF, field_NativeVIF_netmask, (jint) /*uint32_t*/ htonl(v->uv_subnetmask)); (*env)->SetObjectField(env, nativeVIF, field_NativeVIF_name, nameString); (*env)->SetIntField(env, nativeVIF, field_NativeVIF_ifIndex, (jint) /*int*/ v->uv_ifindex); } } JNIEXPORT void JNICALL Java_ow_ipmulticast_Native_receiveIGMP(JNIEnv *env, jclass clazz, jobject container) { struct ip *ip; struct igmp *igmp; char data[BUF_SIZE]; int datalen = 0; jbyteArray jdata; if (recv_igmp(&ip, &igmp, data, &datalen, BUF_SIZE) < 0) { (*env)->ThrowNew(env, clazz_IOException, "recvfrom(2) returned -1."); } if (datalen >= BUF_SIZE) { log(LOG_WARNING, 0, "Buffer is possiblly too short."); datalen = BUF_SIZE; } (*env)->SetIntField(env, container, field_IGMPMessage_src, (jint)(ntohl(ip->ip_src.s_addr))); (*env)->SetIntField(env, container, field_IGMPMessage_dest, (jint)(ntohl(ip->ip_dst.s_addr))); (*env)->SetIntField(env, container, field_IGMPMessage_type, (jint)(igmp->igmp_type)); (*env)->SetIntField(env, container, field_IGMPMessage_code, (jint)(igmp->igmp_code)); (*env)->SetIntField(env, container, field_IGMPMessage_group, (jint)(ntohl(igmp->igmp_group.s_addr))); if (datalen > 0) { // jdata = new byte[datalen]; jdata[0..datale-1] = ... jdata = (*env)->NewByteArray(env, (jsize)datalen); (*env)->SetByteArrayRegion(env, jdata, (jsize)0, (jsize)datalen, (jbyte *)data); // container.data = jdata (*env)->SetObjectField(env, container, field_IGMPMessage_data, (jobject)jdata); } } JNIEXPORT void JNICALL Java_ow_ipmulticast_Native_sendIGMP(JNIEnv *env, jclass clazz, jint src, jint dest, jint type, jint code, jint group, jbyteArray jdata) { jsize datalen; jbyte *data; src = htonl(src); dest = htonl(dest); group = htonl(group); if (jdata != NULL) { datalen = (*env)->GetArrayLength(env, jdata); data = (*env)->GetByteArrayElements(env, jdata, NULL); } else { datalen = 0; data = NULL; } #if 0 printf("send\n"); printf(" src: %s\n", inet_fmt(src, s1)); printf(" dest: %s\n", inet_fmt(dest, s1)); printf(" group: %s\n", inet_fmt(group, s1)); printf(" datalen: %d\n", datalen); fflush(stdout); #endif send_igmp((uint32_t)src, (uint32_t)dest, (int)type, (int)code, (uint32_t)group, (char *)data, (int)datalen); if (jdata != NULL) { (*env)->ReleaseByteArrayElements(env, jdata, data, JNI_ABORT); } } JNIEXPORT void JNICALL Java_ow_ipmulticast_Native_receiveMulticast(JNIEnv *env, jclass clazz, jobject container) { struct ip *ip; struct udphdr *udp; char data[BUF_SIZE]; int datalen = 0; jbyteArray jdata; if (recv_dgram(&ip, &udp, data, &datalen, BUF_SIZE, TRUE) < 0) { (*env)->ThrowNew(env, clazz_IOException, "recvfrom(2) returned -1."); } if (datalen >= BUF_SIZE) { log(LOG_WARNING, 0, "Buffer is possiblly too short."); datalen = BUF_SIZE; } #ifdef RAW_OUTPUT_IS_RAW ip->ip_src.s_addr = ntohl(ip->ip_src.s_addr); ip->ip_dst.s_addr = ntohl(ip->ip_dst.s_addr); udp->source = ntohs(udp->source); udp->dest = ntohs(udp->dest); #endif (*env)->SetIntField(env, container, field_MulticastMessage_srcaddr, (jint)(ip->ip_src.s_addr)); (*env)->SetIntField(env, container, field_MulticastMessage_srcport, (jint)(udp->source)); (*env)->SetIntField(env, container, field_MulticastMessage_destaddr, (jint)(ip->ip_dst.s_addr)); (*env)->SetIntField(env, container, field_MulticastMessage_destport, (jint)(udp->dest)); (*env)->SetIntField(env, container, field_MulticastMessage_id, (jint)(ip->ip_id)); (*env)->SetIntField(env, container, field_MulticastMessage_ttl, (jint)(ip->ip_ttl)); if (datalen > 0) { // jdata = new byte[datalen]; jdata[0..datale-1] = ... jdata = (*env)->NewByteArray(env, (jsize)datalen); (*env)->SetByteArrayRegion(env, jdata, (jsize)0, (jsize)datalen, (jbyte *)data); // container.data = jdata (*env)->SetObjectField(env, container, field_MulticastMessage_data, (jobject)jdata); } } JNIEXPORT void JNICALL Java_ow_ipmulticast_Native_sendMulticast(JNIEnv *env, jclass clazz, jint srcaddr, jint srcport, jint destaddr, jint destport, jint id, jint ttl, jint datalen, jbyteArray jdata) { jsize datasize; jbyte *data; srcaddr = htonl(srcaddr); destaddr = htonl(destaddr); if (jdata != NULL) { datasize = (*env)->GetArrayLength(env, jdata); data = (*env)->GetByteArrayElements(env, jdata, NULL); } else { datasize = 0; data = NULL; } if (datalen > datasize) { datalen = datasize; } #if 0 printf("send\n"); printf(" src: %s\n", inet_fmt(srcaddr, s1)); printf(" dest: %s:%d\n", inet_fmt(destaddr, s1), destport); printf(" datasize: %d\n", datasize); printf(" datalen: %d\n", datalen); fflush(stdout); #endif send_dgram((uint32_t)srcaddr, (uint16_t)srcport, (uint32_t)destaddr, (uint16_t)destport, (uint16_t)id, (uint8_t)ttl, (char *)data, (int)datalen); if (jdata != NULL) { (*env)->ReleaseByteArrayElements(env, jdata, data, JNI_ABORT); } } JNIEXPORT void JNICALL Java_ow_ipmulticast_Native_joinGroup(JNIEnv *env, jclass clazz, jint group, jint ifLocalAddr, jint ifIndex) { struct uvif u; u.uv_ifindex = (int)ifIndex; u.uv_lcl_addr = (uint32_t)htonl(ifLocalAddr); k_join(sock_dgram_send, (uint32_t)htonl(group), &u); } JNIEXPORT void JNICALL Java_ow_ipmulticast_Native_leaveGroup(JNIEnv *env, jclass clazz, jint group, jint ifLocalAddr, jint ifIndex) { struct uvif u; u.uv_ifindex = (int)ifIndex; u.uv_lcl_addr = (uint32_t)htonl(ifLocalAddr); k_leave(sock_dgram_send, (uint32_t)htonl(group), &u); }
y-sira/overlayweaver
native/ipmulticast/config.c
<reponame>y-sira/overlayweaver /* * This file has been derived from pimd-2.1.0-alpha29.17. * The pimd program is covered by the license in the accompanying file * named "LICENSE.pimd-2.1.0-alpha29.17". * * Part of the pimd program has been derived from mrouted. * The mrouted program is covered by the license in the accompanying file * named "LICENSE.mtouted". */ #include "common.h" /* * Query the kernel to find network interfaces that are multicast-capable * and install them in the uvifs array. */ void config_vifs_from_kernel() { struct ifreq *ifrp, *ifend; register struct uvif *v; register vifi_t vifi; int n; uint32_t addr, mask, subnet; short flags; int num_ifreq = 32; struct ifconf ifc; char *newbuf; total_interfaces = 0; /* The total number of physical interfaces */ ifc.ifc_len = num_ifreq * sizeof(struct ifreq); ifc.ifc_buf = calloc(ifc.ifc_len, sizeof(char)); while (ifc.ifc_buf) { if (ioctl(udp_socket, SIOCGIFCONF, (char *)&ifc) < 0) log(LOG_ERR, errno, "ioctl SIOCGIFCONF"); /* * If the buffer was large enough to hold all the addresses * then break out, otherwise increase the buffer size and * try again. * * The only way to know that we definitely had enough space * is to know that there was enough space for at least one * more struct ifreq. ??? */ if ((num_ifreq * sizeof(struct ifreq)) >= ifc.ifc_len + sizeof(struct ifreq)) break; num_ifreq *= 2; ifc.ifc_len = num_ifreq * sizeof(struct ifreq); newbuf = realloc(ifc.ifc_buf, ifc.ifc_len); if (newbuf == NULL) free(ifc.ifc_buf); ifc.ifc_buf = newbuf; } if (ifc.ifc_buf == NULL) log(LOG_ERR, 0, "config_vifs_from_kernel: ran out of memory"); ifrp = (struct ifreq *)ifc.ifc_buf; ifend = (struct ifreq *)(ifc.ifc_buf + ifc.ifc_len); /* * Loop through all of the interfaces. */ for (; ifrp < ifend; ifrp = (struct ifreq *)((char *)ifrp + n)) { struct ifreq ifr; #ifdef HAVE_SA_LEN n = ifrp->ifr_addr.sa_len + sizeof(ifrp->ifr_name); if (n < sizeof(*ifrp)) n = sizeof(*ifrp); #else n = sizeof(*ifrp); #endif /* HAVE_SA_LEN */ /* * Ignore any interface for an address family other than IP. */ if (ifrp->ifr_addr.sa_family != AF_INET) { total_interfaces++; /* Eventually may have IP address later */ continue; } addr = ((struct sockaddr_in *)&ifrp->ifr_addr)->sin_addr.s_addr; /* * Need a template to preserve address info that is * used below to locate the next entry. (Otherwise, * SIOCGIFFLAGS stomps over it because the requests * are returned in a union.) */ bcopy(ifrp->ifr_name, ifr.ifr_name, sizeof(ifr.ifr_name)); /* * Ignore loopback interfaces and interfaces that do not * support multicast. */ if (ioctl(udp_socket, SIOCGIFFLAGS, (char *)&ifr) < 0) log(LOG_ERR, errno, "ioctl SIOCGIFFLAGS for %s", ifr.ifr_name); flags = ifr.ifr_flags; if ((flags & (IFF_LOOPBACK | IFF_MULTICAST)) != IFF_MULTICAST) continue; /* * Everyone below is a potential vif interface. * We don't care if it has wrong configuration or not configured * at all. */ total_interfaces++; /* * Ignore any interface whose address and mask do not define a * valid subnet number, or whose address is of the form * {subnet,0} or {subnet,-1}. */ if (ioctl(udp_socket, SIOCGIFNETMASK, (char *)&ifr) < 0) { if (!(flags & IFF_POINTOPOINT)) { log(LOG_ERR, errno, "ioctl SIOCGIFNETMASK for %s", ifr.ifr_name); } else { mask = 0xffffffff; } } else { mask = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr; } subnet = addr & mask; if ((!inet_valid_subnet(subnet, mask)) || (addr == subnet) || addr == (subnet | ~mask)) { if (!(inet_valid_host(addr) && (flags & IFF_POINTOPOINT))) { log(LOG_WARNING, 0, "ignoring %s, has invalid address (%s) and/or mask (%s)", ifr.ifr_name, inet_fmt(addr, s1), inet_fmt(mask, s2)); continue; } } /* * Ignore any interface that is connected to the same subnet as * one already installed in the uvifs array. */ /* * TODO: XXX: bug or "feature" is to allow only one interface per * subnet? */ for (vifi = 0, v = uvifs; vifi < numvifs; ++vifi, ++v) { if (strcmp(v->uv_name, ifr.ifr_name) == 0) { log(LOG_DEBUG, 0, "skipping %s (%s on subnet %s) (alias for vif#%u?)", v->uv_name, inet_fmt(addr, s1), netname(subnet, mask), vifi); break; } /* we don't care about point-to-point links in same subnet */ if (flags & IFF_POINTOPOINT) continue; if (v->uv_flags & VIFF_POINT_TO_POINT) continue; #if 0 /* * TODO: to allow different interfaces belong to * overlapping subnet addresses, use this version instead */ if (((addr & mask ) == v->uv_subnet) && (v->uv_subnetmask == mask)) { log(LOG_WARNING, 0, "ignoring %s, same subnet as %s", ifr.ifr_name, v->uv_name); break; } #else if ((addr & v->uv_subnetmask) == v->uv_subnet || (v->uv_subnet & mask) == subnet) { log(LOG_WARNING, 0, "ignoring %s, same subnet as %s", ifr.ifr_name, v->uv_name); break; } #endif /* 0 */ } if (vifi != numvifs) continue; /* * If there is room in the uvifs array, install this interface. */ if (numvifs == MAXVIFS) { log(LOG_WARNING, 0, "too many vifs, ignoring %s", ifr.ifr_name); continue; } v = &uvifs[numvifs]; zero_vif(v, FALSE); v->uv_lcl_addr = addr; v->uv_subnet = subnet; v->uv_subnetmask = mask; v->uv_subnetbcast = subnet | ~mask; strncpy(v->uv_name, ifr.ifr_name, IFNAMSIZ); if (flags & IFF_POINTOPOINT) { v->uv_flags |= (VIFF_REXMIT_PRUNES | VIFF_POINT_TO_POINT); if (ioctl(udp_socket, SIOCGIFDSTADDR, (char *)&ifr) < 0) { log(LOG_ERR, errno, "ioctl SIOCGIFDSTADDR for %s", v->uv_name); } else { v->uv_rmt_addr = ((struct sockaddr_in *)(&ifr.ifr_dstaddr))->sin_addr.s_addr; } } #ifdef linux { struct ifreq ifridx; memset(&ifridx, 0, sizeof(ifridx)); strncpy(ifridx.ifr_name,v->uv_name, IFNAMSIZ); if (ioctl(udp_socket, SIOGIFINDEX, (char *) &ifridx) < 0) { log(LOG_ERR, errno, "ioctl SIOGIFINDEX for %s", ifridx.ifr_name); /* Not reached */ return; } v->uv_ifindex = ifridx.ifr_ifindex; } if (flags & IFF_POINTOPOINT) { log(LOG_INFO, 0, "installing %s (%s -> %s) as vif #%u-%d - rate=%d", v->uv_name, inet_fmt(addr, s1), inet_fmt(v->uv_rmt_addr, s2), numvifs, v->uv_ifindex, v->uv_rate_limit); } else { log(LOG_INFO, 0, "installing %s (%s on subnet %s) as vif #%u-%d - rate=%d", v->uv_name, inet_fmt(addr, s1), netname(subnet, mask), numvifs, v->uv_ifindex, v->uv_rate_limit); } #else /* !linux */ if (flags & IFF_POINTOPOINT) { log(LOG_INFO, 0, "installing %s (%s -> %s) as vif #%u - rate=%d", v->uv_name, inet_fmt(addr, s1), inet_fmt(v->uv_rmt_addr, s2), numvifs, v->uv_rate_limit); } else { log(LOG_INFO, 0, "installing %s (%s on subnet %s) as vif #%u - rate=%d", v->uv_name, inet_fmt(addr, s1), netname(subnet, mask), numvifs, v->uv_rate_limit); } #endif /* linux */ ++numvifs; /* * If the interface is not yet up, set the vifs_down flag to * remind us to check again later. */ if (!(flags & IFF_UP)) { v->uv_flags |= VIFF_DOWN; vifs_down = TRUE; } } }
y-sira/overlayweaver
native/ipmulticast/dgram.c
/* * Copyright 2006 National Institute of Advanced Industrial Science * and Technology (AIST), and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" int sock_dgram_send, sock_dgram_recv; static char *recvbuf = NULL; static char *sendbuf = NULL; static int loop = MULTICAST_LOOP; int init_dgram() { struct ip *ip; if (recvbuf != NULL) free(recvbuf); if (sendbuf != NULL) free(sendbuf); recvbuf = malloc(BUF_SIZE); sendbuf = malloc(BUF_SIZE); // create a raw socket if (((sock_dgram_send = socket(PF_INET, SOCK_RAW, IPPROTO_UDP)) < 0) || ((sock_dgram_recv = socket(PF_INET, SOCK_RAW, IPPROTO_UDP)) < 0)) { log(LOG_ERR, errno, "Failed to create a raw socket. You may have to be the \"root\" user to have priviledge."); return -1; } k_hdr_include(sock_dgram_send, TRUE); k_set_sndbuf(sock_dgram_send, SEND_BUF_MAX_SIZE, SEND_BUF_MIN_SIZE); k_set_rcvbuf(sock_dgram_send, RECV_BUF_MAX_SIZE, RECV_BUF_MIN_SIZE); k_set_loop(sock_dgram_send, loop); k_hdr_include(sock_dgram_recv, TRUE); k_set_sndbuf(sock_dgram_recv, SEND_BUF_MAX_SIZE, SEND_BUF_MIN_SIZE); k_set_rcvbuf(sock_dgram_recv, RECV_BUF_MAX_SIZE, RECV_BUF_MIN_SIZE); k_set_loop(sock_dgram_recv, loop); // initialize IP header ip = (struct ip *)sendbuf; memset((void *)ip, 0, sizeof(struct ip)); ip->ip_v = IPVERSION; ip->ip_hl = sizeof(struct ip) >> 2; //ip->ip_tos = IPTOS_MINCOST; ip->ip_off = htons(IP_DF); // don't fragment ip->ip_ttl = DEFAULT_DGRAM_TTL; ip->ip_p = IPPROTO_UDP; ip->ip_sum = 0; // kernel fills in return 0; } void stop_dgram() { if (sock_dgram_send > 0) { close(sock_dgram_send); sock_dgram_send = -1; } if (sock_dgram_recv > 0) { close(sock_dgram_recv); sock_dgram_recv = -1; } if (recvbuf != NULL) free(recvbuf); if (sendbuf != NULL) free(sendbuf); } int send_dgram(uint32_t srcaddr, uint16_t srcport, uint32_t destaddr, uint16_t destport, uint16_t id, uint8_t ttl, char *data, uint16_t datalen) { struct ip *ip; struct udphdr *udp; int ipheaderlen; int sendlen; int setloop = FALSE; struct sockaddr_in destsock; char *buf = sendbuf; ip = (struct ip *)buf; ipheaderlen = (ip->ip_hl << 2); if (ipheaderlen + sizeof(struct udphdr) + datalen > BUF_SIZE) { datalen = BUF_SIZE - (ipheaderlen + sizeof(struct udphdr)); log(LOG_WARNING, 0, "Given data is too large: %d\n", datalen); } // prepare IP header ip->ip_len = ipheaderlen + sizeof(struct udphdr) + datalen; ip->ip_src.s_addr = srcaddr; ip->ip_dst.s_addr = destaddr; sendlen = ip->ip_len; #if defined(RAW_OUTPUT_IS_RAW) || defined(OpenBSD) ip->ip_len = htons(ip->ip_len); #endif ip->ip_id = id; ip->ip_ttl = ttl; // prepare UDP header udp = (struct udphdr *)(buf + ipheaderlen); udp->source = htons(srcport); udp->dest = htons(destport); udp->len = sizeof(struct udphdr) + datalen; #if defined(RAW_OUTPUT_IS_RAW) || defined(OpenBSD) udp->len = htons(udp->len); #endif // copy data if (data != NULL) { memcpy(((char *)udp) + sizeof(struct udphdr), data, datalen); } // calculate checksum #ifdef CALCULATE_UDP_CHECKSUM { int add = 0; uint16_t i = 0; add += srcaddr >> 16; add += srcaddr & 0xffff; add += destaddr >> 16; add += destaddr & 0xffff; *(((uint8_t *)&i) + 1) = ip->ip_p; add += i; add += udp->len; udp->check = 0; udp->check = inet_cksum((uint16_t *)udp, sizeof(struct udphdr) + datalen, add); } #else udp->check = 0; #endif if (IN_MULTICAST(ntohl(destaddr))) { k_set_if(sock_dgram_send, srcaddr); if (destaddr == allhostsgroup) { setloop = TRUE; k_set_loop(sock_dgram_send, TRUE); } } memset((void *)&destsock, 0, sizeof(destsock)); destsock.sin_family = PF_INET; #ifdef HAVE_SA_LEN destsock.sin_len = sizeof(destsock); #endif destsock.sin_addr.s_addr = destaddr; destsock.sin_port = destport; if (sendto(sock_dgram_send, sendbuf, sendlen, 0, (struct sockaddr *)&destsock, sizeof(destsock)) < 0) { log(LOG_ERR, errno, "Failed in sendto(2) to %s on %s.", inet_fmt(destaddr, s1), inet_fmt(srcaddr, s2)); if (setloop) { k_set_loop(sock_dgram_send, loop); } return -1; } if (setloop) { k_set_loop(sock_dgram_send, loop); } return 0; } int recv_dgram(struct ip **ipp, struct udphdr **udpp, char *data, int *datalenp, int maxdatasize, int only_mcast) { uint32_t src, dest; struct ip *ip; struct udphdr *udp; int ipheaderlen, ipdatalen, udpdatalen; int recvlen; // receive while (TRUE) { socklen_t fromlen; recvlen = recvfrom(sock_dgram_recv, recvbuf, BUF_SIZE, 0, NULL, &fromlen); if (recvlen < 0) { if (errno != EINTR) { log(LOG_ERR, errno, "recv(2) returned -1."); } return -1; } if (recvlen < sizeof (struct ip)) { log(LOG_WARNING, 0, "Received packet is too short: %d", recvlen); continue; } ip = (struct ip *)recvbuf; src = ip->ip_src.s_addr; dest = ip->ip_dst.s_addr; if (only_mcast && !IN_MULTICAST(ntohl(dest))) { // ignore unicast message continue; } if (ip->ip_p == 0) { // message from kernel if (src == 0 || dest == 0) { log(LOG_WARNING, 0, "Message from kernel is not accurate."); } else { // do nothing } continue; } ipheaderlen = ip->ip_hl << 2; #ifdef RAW_INPUT_IS_RAW ipdatalen = ntohs(ip->ip_len) - ipheaderlen; #else ipdatalen = ip->ip_len; #endif if (ipheaderlen + ipdatalen != recvlen) { log(LOG_WARNING, 0, "Received packet from %s is shorter (%u bytes) than header+data length (%u+%u).", inet_fmt(src, s1), recvlen, ipheaderlen, ipdatalen); continue; } udp = (struct udphdr *)(recvbuf + ipheaderlen); udpdatalen = ipdatalen - sizeof(struct udphdr); if (ipp != NULL) *ipp = ip; if (udpp != NULL) *udpp = udp; if (datalenp != NULL) { *datalenp = udpdatalen; } if ((ipdatalen > 0) && (data != NULL)) { int len = MIN(udpdatalen, maxdatasize); memcpy(data, ((char *)udp) + sizeof(struct udphdr), len); } return 0; } }
FelixLinBH/IUpgrade
IUpgrade/Classes/UIResponder+IUpgrade.h
// // UIResponder+IUpgrade.h // Pods // // Created by LBH on 2016/8/8. // // #import <UIKit/UIKit.h> @interface UIResponder (IUpgrade) @end
FelixLinBH/IUpgrade
Example/IUpgrade/IUpgradeViewController.h
// // IUpgradeViewController.h // IUpgrade // // Created by felix.lin on 07/31/2016. // Copyright (c) 2016 felix.lin. All rights reserved. // @import UIKit; @interface IUpgradeViewController : UIViewController @end
FelixLinBH/IUpgrade
IUpgrade/Classes/IUpgrade.h
<reponame>FelixLinBH/IUpgrade // // IUpgrade.h // Pods // // Created by LBH on 2016/8/1. // // #import <Foundation/Foundation.h> typedef NS_ENUM(NSUInteger, IUpgradeAlertType) { IUpgradeDefault, IUpgradeForec, IUpgradeSkip }; @interface IUpgrade : NSObject @property (nonatomic) NSString *plistUrlString; @property (nonatomic) NSString *alertTitle; @property (nonatomic) NSString *prefixMessage; @property (nonatomic) NSString *suffixMessage; @property (nonatomic, assign) IUpgradeAlertType type; + (IUpgrade *)sharedInstance; - (void)checkVersion; - (void)CheckVersionForced; - (void)setAlertTitle:(NSString *)alertTitle prefixMessage:(NSString *)prefixMessage suffixMessage:(NSString *)suffixMessage; @end
FelixLinBH/IUpgrade
Example/IUpgrade/IUpgradeAppDelegate.h
// // IUpgradeAppDelegate.h // IUpgrade // // Created by felix.lin on 07/31/2016. // Copyright (c) 2016 felix.lin. All rights reserved. // @import UIKit; @interface IUpgradeAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
danieljfarrell/EFLaceView
EFLaceView.h
// // EFLaceView.h // EFLaceView // // Created by MacBook Pro ef on 01/08/06. // Copyright 2006 <NAME>. All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // - Neither the name of Edouard FISCHER nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import <Cocoa/Cocoa.h> #import "EFView.h" @interface EFLaceView : NSView { NSObject* _dataObjectsContainer; NSString* _dataObjectsKeyPath; NSObject* _selectionIndexesContainer; NSString* _selectionIndexesKeyPath; NSArray* _oldDataObjects; BOOL _isMaking; NSPoint _startPoint; NSPoint _endPoint; NSPoint _rubberStart; NSPoint _rubberEnd; BOOL _isRubbing; id _startHole; id _endHole; EFView* _startSubView; EFView* _endSubView; id _delegate; } #pragma mark - #pragma mark *** bindings *** - (void)startObservingDataObjects:(NSArray *)dataObjects; - (void)stopObservingDataObjects:(NSArray *)dataObjects; #pragma mark - #pragma mark *** setters and accessors - (id)delegate; - (void)setDelegate:(id)newDelegate; - (NSMutableArray *)laces; - (NSArray *)dataObjects; - (NSIndexSet *)selectionIndexes; - (NSArray *)oldDataObjects; - (void)setOldDataObjects:(NSArray *)anOldDataObjects; #pragma mark - #pragma mark *** geometry *** - (BOOL)isStartHole:(NSPoint)aPoint; - (BOOL)isEndHole:(NSPoint)aPoint; - (void)drawLinkFrom:(NSPoint)startPoint to:(NSPoint)endPoint color:(NSColor *)insideColor; - (void)deselectViews; - (void)selectView:(EFView *)aView; - (void)selectView:(EFView *)aView state:(BOOL)aBool; - (NSArray*)selectedSubViews; - (void) connectHole:(id)startHole toHole:(id)endHole; @end @interface NSObject (EFLaceViewDataObject) + (NSArray *)keysForNonBoundsProperties; @end @interface NSObject (EFLaceViewDelegateMethod) - (BOOL)EFLaceView:(EFLaceView*)aView shouldSelectView:(EFView *)aView state:(BOOL)aBool; - (BOOL)EFLaceView:(EFLaceView*)aView shouldSelectLace:(NSDictionary*)aLace; - (BOOL)EFLaceView:(EFLaceView*)aView shouldConnectHole:(id)startHole toHole:(id)endHole; - (BOOL)EFLaceView:(EFLaceView*)aView shouldDrawView:(EFView *)aView; @end
danieljfarrell/EFLaceView
EFView.h
// // EFView.h // EFLaceView // // Created by MacBook Pro ef on 25/07/06. // Copyright 2006 <NAME>. All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // - Neither the name of Edouard FISCHER nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import <Cocoa/Cocoa.h> @interface EFView : NSView { int _tag; NSString* _title; NSColor* _titleColor; NSMutableSet* _inputs; NSMutableSet* _outputs; float _verticalOffset; NSMutableDictionary* _stringAttributes; id _data; } #pragma mark - #pragma mark *** class *** #pragma mark - #pragma mark *** holes *** - (NSArray *)orderedHoles:(NSSet *)aSet; - (NSPoint)startHolePoint:(id) aStartHole; - (NSPoint)endHolePoint:(id) aEndHole; - (id)startHole:(NSPoint)aPoint; - (id)endHole:(NSPoint)aPoint; #pragma mark - #pragma mark *** setters and accessors *** // vertical offset - (float)verticalOffset; - (void)setVerticalOffset:(float)aValue; // selected - (BOOL)isSelected; // title - (NSString *)title; - (void)setTitle:(NSString *)aTitle; // title color - (NSColor *)titleColor; - (void)setTitleColor:(NSColor *)aColor; #pragma mark drawingbounds - (float) originX; - (float) originY; - (float) width; - (float) height; - (void) setOriginX:(float)aFloat; - (void) setOriginY:(float)aFloat; - (void) setWidth:(float)aFloat; - (void) setHeight:(float)aFloat; #pragma mark inputs and outputs - (NSMutableSet*)inputs; - (NSArray *)orderedInputs; - (NSMutableSet *)outputs; - (NSArray*)orderedOutputs; #pragma mark - #pragma mark *** geometry *** - (NSSize) minimalSize; @end
coral-labs/plugins
packages/camera/camera/ios/Classes/FLTSavePhotoDelegate.h
<filename>packages/camera/camera/ios/Classes/FLTSavePhotoDelegate.h // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import AVFoundation; @import Foundation; @import Flutter; #import "FLTThreadSafeFlutterResult.h" NS_ASSUME_NONNULL_BEGIN /** Delegate object that handles photo capture results. */ @interface FLTSavePhotoDelegate : NSObject <AVCapturePhotoCaptureDelegate> /// The file path for the captured photo. @property(readonly, nonatomic) NSString *path; /// The thread safe flutter result wrapper to report the result. @property(readonly, nonatomic) FLTThreadSafeFlutterResult *result; /// The queue on which captured photos are wrote to disk. @property(strong, nonatomic) dispatch_queue_t ioQueue; /// Used to keep the delegate alive until didFinishProcessingPhotoSampleBuffer. @property(strong, nonatomic, nullable) FLTSavePhotoDelegate *selfReference; /** * Initialize a photo capture delegate. * @param path the path for captured photo file. * @param result the thread safe flutter result wrapper to report the result. * @param ioQueue the queue on which captured photos are wrote to disk. */ - (instancetype)initWithPath:(NSString *)path result:(FLTThreadSafeFlutterResult *)result ioQueue:(dispatch_queue_t)ioQueue; @end NS_ASSUME_NONNULL_END
coral-labs/plugins
packages/camera/camera_windows/windows/capture_device_info.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_DEVICE_INFO_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_DEVICE_INFO_H_ #include <string> namespace camera_windows { // Name and device ID information for a capture device. class CaptureDeviceInfo { public: CaptureDeviceInfo() {} virtual ~CaptureDeviceInfo() = default; // Disallow copy and move. CaptureDeviceInfo(const CaptureDeviceInfo&) = delete; CaptureDeviceInfo& operator=(const CaptureDeviceInfo&) = delete; // Build unique device name from display name and device id. // Format: "display_name <device_id>". std::string GetUniqueDeviceName() const; // Parses display name and device id from unique device name format. // Format: "display_name <device_id>". bool CaptureDeviceInfo::ParseDeviceInfoFromCameraName( const std::string& camera_name); // Updates display name. void SetDisplayName(const std::string& display_name) { display_name_ = display_name; } // Updates device id. void SetDeviceID(const std::string& device_id) { device_id_ = device_id; } // Returns device id. std::string GetDeviceId() const { return device_id_; } private: std::string display_name_; std::string device_id_; }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_DEVICE_INFO_H_
coral-labs/plugins
packages/camera/camera/ios/Classes/QueueHelper.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface QueueHelper : NSObject + (void)ensureToRunOnMainQueue:(void (^)(void))block; @end NS_ASSUME_NONNULL_END
coral-labs/plugins
packages/file_selector/file_selector_windows/windows/file_dialog_controller.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_FILE_DIALOG_CONTROLLER_H_ #define PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_FILE_DIALOG_CONTROLLER_H_ #include <comdef.h> #include <comip.h> #include <shobjidl.h> #include <windows.h> #include <memory> _COM_SMARTPTR_TYPEDEF(IFileDialog, IID_IFileDialog); namespace file_selector_windows { // A thin wrapper for IFileDialog to allow for faking and inspection in tests. // // Since this class defines the end of what can be unit tested, it should // contain as little logic as possible. class FileDialogController { public: // Creates a controller managing |dialog|. FileDialogController(IFileDialog* dialog); virtual ~FileDialogController(); // Disallow copy and assign. FileDialogController(const FileDialogController&) = delete; FileDialogController& operator=(const FileDialogController&) = delete; // IFileDialog wrappers: virtual HRESULT SetDefaultFolder(IShellItem* folder); virtual HRESULT SetFileName(const wchar_t* name); virtual HRESULT SetFileTypes(UINT count, COMDLG_FILTERSPEC* filters); virtual HRESULT SetOkButtonLabel(const wchar_t* text); virtual HRESULT GetOptions(FILEOPENDIALOGOPTIONS* out_options) const; virtual HRESULT SetOptions(FILEOPENDIALOGOPTIONS options); virtual HRESULT Show(HWND parent); virtual HRESULT GetResult(IShellItem** out_item) const; // IFileOpenDialog wrapper. This will fail if the IFileDialog* provided to the // constructor was not an IFileOpenDialog instance. virtual HRESULT GetResults(IShellItemArray** out_items) const; private: IFileDialogPtr dialog_ = nullptr; }; // Interface for creating FileDialogControllers, to allow for dependency // injection. class FileDialogControllerFactory { public: virtual ~FileDialogControllerFactory(); virtual std::unique_ptr<FileDialogController> CreateController( IFileDialog* dialog) const = 0; }; } // namespace file_selector_windows #endif // PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_FILE_DIALOG_CONTROLLER_H_
coral-labs/plugins
packages/camera/camera/ios/Classes/FLTThreadSafeEventChannel.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Flutter/Flutter.h> NS_ASSUME_NONNULL_BEGIN /** * A thread safe wrapper for FlutterEventChannel that can be called from any thread, by dispatching * its underlying engine calls to the main thread. */ @interface FLTThreadSafeEventChannel : NSObject /** * Creates a FLTThreadSafeEventChannel by wrapping a FlutterEventChannel object. * @param channel The FlutterEventChannel object to be wrapped. */ - (instancetype)initWithEventChannel:(FlutterEventChannel *)channel; /* * Registers a handler on the main thread for stream setup requests from the Flutter side. # The completion block runs on the main thread. */ - (void)setStreamHandler:(nullable NSObject<FlutterStreamHandler> *)handler completion:(void (^)(void))completion; @end NS_ASSUME_NONNULL_END
coral-labs/plugins
packages/camera/camera/ios/Classes/FLTThreadSafeFlutterResult.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Flutter/Flutter.h> /** * A thread safe wrapper for FlutterResult that can be called from any thread, by dispatching its * underlying engine calls to the main thread. */ @interface FLTThreadSafeFlutterResult : NSObject /** * Gets the original FlutterResult object wrapped by this FLTThreadSafeFlutterResult instance. */ @property(readonly, nonatomic, nonnull) FlutterResult flutterResult; /** * Initializes with a FlutterResult object. * @param result The FlutterResult object that the result will be given to. */ - (nonnull instancetype)initWithResult:(nonnull FlutterResult)result; /** * Sends a successful result on the main thread without any data. */ - (void)sendSuccess; /** * Sends a successful result on the main thread with data. * @param data Result data that is send to the Flutter Dart side. */ - (void)sendSuccessWithData:(nonnull id)data; /** * Sends an NSError as result on the main thread. * @param error Error that will be send as FlutterError. */ - (void)sendError:(nonnull NSError *)error; /** * Sends a FlutterError as result on the main thread. */ - (void)sendErrorWithCode:(nonnull NSString *)code message:(nullable NSString *)message details:(nullable id)details; /** * Sends FlutterMethodNotImplemented as result on the main thread. */ - (void)sendNotImplemented; @end
coral-labs/plugins
packages/in_app_purchase/in_app_purchase_storekit/ios/Classes/FIAObjectTranslator.h
<gh_stars>1000+ // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Foundation/Foundation.h> #import <StoreKit/StoreKit.h> NS_ASSUME_NONNULL_BEGIN @interface FIAObjectTranslator : NSObject // Converts an instance of SKProduct into a dictionary. + (NSDictionary *)getMapFromSKProduct:(SKProduct *)product; // Converts an instance of SKProductSubscriptionPeriod into a dictionary. + (NSDictionary *)getMapFromSKProductSubscriptionPeriod:(SKProductSubscriptionPeriod *)period API_AVAILABLE(ios(11.2)); // Converts an instance of SKProductDiscount into a dictionary. + (NSDictionary *)getMapFromSKProductDiscount:(SKProductDiscount *)discount API_AVAILABLE(ios(11.2)); // Converts an array of SKProductDiscount instances into an array of dictionaries. + (nonnull NSArray *)getMapArrayFromSKProductDiscounts: (nonnull NSArray<SKProductDiscount *> *)productDiscounts API_AVAILABLE(ios(12.2)); // Converts an instance of SKProductsResponse into a dictionary. + (NSDictionary *)getMapFromSKProductsResponse:(SKProductsResponse *)productResponse; // Converts an instance of SKPayment into a dictionary. + (NSDictionary *)getMapFromSKPayment:(SKPayment *)payment; // Converts an instance of NSLocale into a dictionary. + (NSDictionary *)getMapFromNSLocale:(NSLocale *)locale; // Creates an instance of the SKMutablePayment class based on the supplied dictionary. + (SKMutablePayment *)getSKMutablePaymentFromMap:(NSDictionary *)map; // Converts an instance of SKPaymentTransaction into a dictionary. + (NSDictionary *)getMapFromSKPaymentTransaction:(SKPaymentTransaction *)transaction; // Converts an instance of NSError into a dictionary. + (NSDictionary *)getMapFromNSError:(NSError *)error; // Converts an instance of SKStorefront into a dictionary. + (NSDictionary *)getMapFromSKStorefront:(SKStorefront *)storefront API_AVAILABLE(ios(13), macos(10.15), watchos(6.2)); // Converts the supplied instances of SKStorefront and SKPaymentTransaction into a dictionary. + (NSDictionary *)getMapFromSKStorefront:(SKStorefront *)storefront andSKPaymentTransaction:(SKPaymentTransaction *)transaction API_AVAILABLE(ios(13), macos(10.15), watchos(6.2)); // Creates an instance of the SKPaymentDiscount class based on the supplied dictionary. + (nullable SKPaymentDiscount *)getSKPaymentDiscountFromMap:(NSDictionary *)map withError:(NSString *_Nullable *_Nullable)error API_AVAILABLE(ios(12.2)); @end ; NS_ASSUME_NONNULL_END
coral-labs/plugins
packages/camera/camera/example/ios/RunnerTests/MockFLTThreadSafeFlutterResult.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MockFLTThreadSafeFlutterResult_h #define MockFLTThreadSafeFlutterResult_h /** * Extends FLTThreadSafeFlutterResult to give tests the ability to wait on the result and * read the received result. */ @interface MockFLTThreadSafeFlutterResult : FLTThreadSafeFlutterResult @property(readonly, nonatomic, nonnull) XCTestExpectation *expectation; @property(nonatomic, nullable) id receivedResult; /** * Initializes the MockFLTThreadSafeFlutterResult with an expectation. * * The expectation is fullfilled when a result is called allowing tests to await the result in an * asynchronous manner. */ - (nonnull instancetype)initWithExpectation:(nonnull XCTestExpectation *)expectation; @end #endif /* MockFLTThreadSafeFlutterResult_h */
coral-labs/plugins
packages/camera/camera/ios/Classes/FLTThreadSafeMethodChannel.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Flutter/Flutter.h> NS_ASSUME_NONNULL_BEGIN /** * A thread safe wrapper for FlutterMethodChannel that can be called from any thread, by dispatching * its underlying engine calls to the main thread. */ @interface FLTThreadSafeMethodChannel : NSObject /** * Creates a FLTThreadSafeMethodChannel by wrapping a FlutterMethodChannel object. * @param channel The FlutterMethodChannel object to be wrapped. */ - (instancetype)initWithMethodChannel:(FlutterMethodChannel *)channel; /** * Invokes the specified flutter method on the main thread with the specified arguments. */ - (void)invokeMethod:(NSString *)method arguments:(nullable id)arguments; @end NS_ASSUME_NONNULL_END
coral-labs/plugins
packages/camera/camera_windows/windows/preview_handler.h
<gh_stars>1-10 // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_PREVIEW_HANDLER_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_PREVIEW_HANDLER_H_ #include <mfapi.h> #include <mfcaptureengine.h> #include <wrl/client.h> #include <memory> #include <string> #include "capture_engine_listener.h" namespace camera_windows { using Microsoft::WRL::ComPtr; // States the preview handler can be in. // // When created, the handler starts in |kNotStarted| state and mostly // transitions in sequential order of the states. When the preview is running, // it can be set to the |kPaused| state and later resumed to |kRunning| state. enum class PreviewState { kNotStarted, kStarting, kRunning, kPaused, kStopping }; // Handler for a camera's video preview. // // Handles preview sink initialization and manages the state of the video // preview. class PreviewHandler { public: PreviewHandler() {} virtual ~PreviewHandler() = default; // Prevent copying. PreviewHandler(PreviewHandler const&) = delete; PreviewHandler& operator=(PreviewHandler const&) = delete; // Initializes preview sink and requests capture engine to start previewing. // Sets preview state to: starting. // Returns false if recording cannot be started. // // capture_engine: A pointer to capture engine instance. Used to start // the actual recording. // base_media_type: A pointer to base media type used as a base // for the actual video capture media type. // sample_callback: A pointer to capture engine listener. // This is set as sample callback for preview sink. bool StartPreview(IMFCaptureEngine* capture_engine, IMFMediaType* base_media_type, CaptureEngineListener* sample_callback); // Stops existing recording. // Returns false if recording cannot be stopped. // // capture_engine: A pointer to capture engine instance. Used to stop // the ongoing recording. bool StopPreview(IMFCaptureEngine* capture_engine); // Set the preview handler recording state to: paused. bool PausePreview(); // Set the preview handler recording state to: running. bool ResumePreview(); // Set the preview handler recording state to: running. void OnPreviewStarted(); // Returns true if preview state is running or paused. bool IsInitialized() const { return preview_state_ == PreviewState::kRunning && preview_state_ == PreviewState::kPaused; } // Returns true if preview state is running. bool IsRunning() const { return preview_state_ == PreviewState::kRunning; } // Return true if preview state is paused. bool IsPaused() const { return preview_state_ == PreviewState::kPaused; } // Returns true if preview state is starting. bool IsStarting() const { return preview_state_ == PreviewState::kStarting; } private: // Initializes record sink for video file capture. HRESULT InitPreviewSink(IMFCaptureEngine* capture_engine, IMFMediaType* base_media_type, CaptureEngineListener* sample_callback); PreviewState preview_state_ = PreviewState::kNotStarted; ComPtr<IMFCapturePreviewSink> preview_sink_; }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_PREVIEW_HANDLER_H_
coral-labs/plugins
packages/camera/camera_windows/windows/capture_controller.h
<gh_stars>1-10 // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_CONTROLLER_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_CONTROLLER_H_ #include <d3d11.h> #include <flutter/texture_registrar.h> #include <mfapi.h> #include <mfcaptureengine.h> #include <mferror.h> #include <mfidl.h> #include <windows.h> #include <wrl/client.h> #include <memory> #include <string> #include "capture_controller_listener.h" #include "capture_engine_listener.h" #include "photo_handler.h" #include "preview_handler.h" #include "record_handler.h" #include "texture_handler.h" namespace camera_windows { using flutter::TextureRegistrar; using Microsoft::WRL::ComPtr; // Camera resolution presets. Used to request a capture resolution. enum class ResolutionPreset { // Automatic resolution, uses the highest resolution available. kAuto, // 240p (320x240) kLow, // 480p (720x480) kMedium, // 720p (1280x720) kHigh, // 1080p (1920x1080) kVeryHigh, // 2160p (4096x2160) kUltraHigh, // The highest resolution available. kMax, }; // Camera capture engine state. // // On creation, |CaptureControllers| start in state |kNotInitialized|. // On initialization, the capture controller transitions to the |kInitializing| // and then |kInitialized| state. enum class CaptureEngineState { kNotInitialized, kInitializing, kInitialized }; // Interface for a class that enumerates video capture device sources. class VideoCaptureDeviceEnumerator { private: virtual bool EnumerateVideoCaptureDeviceSources(IMFActivate*** devices, UINT32* count) = 0; }; // Interface implemented by capture controllers. // // Capture controllers are used to capture video streams or still photos from // their associated |Camera|. class CaptureController { public: CaptureController() {} virtual ~CaptureController() = default; // Disallow copy and move. CaptureController(const CaptureController&) = delete; CaptureController& operator=(const CaptureController&) = delete; // Initializes the capture controller with the specified device id. // // texture_registrar: Pointer to Flutter TextureRegistrar instance. Used to // register texture for capture preview. // device_id: A string that holds information of camera device id to // be captured. // record_audio: A boolean value telling if audio should be captured on // video recording. // resolution_preset: Maximum capture resolution height. virtual void InitCaptureDevice(TextureRegistrar* texture_registrar, const std::string& device_id, bool record_audio, ResolutionPreset resolution_preset) = 0; // Returns preview frame width virtual uint32_t GetPreviewWidth() const = 0; // Returns preview frame height virtual uint32_t GetPreviewHeight() const = 0; // Starts the preview. virtual void StartPreview() = 0; // Pauses the preview. virtual void PausePreview() = 0; // Resumes the preview. virtual void ResumePreview() = 0; // Starts recording video. virtual void StartRecord(const std::string& file_path, int64_t max_video_duration_ms) = 0; // Stops the current video recording. virtual void StopRecord() = 0; // Captures a still photo. virtual void TakePicture(const std::string& file_path) = 0; }; // Concrete implementation of the |CaptureController| interface. // // Handles the video preview stream via a |PreviewHandler| instance, video // capture via a |RecordHandler| instance, and still photo capture via a // |PhotoHandler| instance. class CaptureControllerImpl : public CaptureController, public CaptureEngineObserver { public: static bool EnumerateVideoCaptureDeviceSources(IMFActivate*** devices, UINT32* count); explicit CaptureControllerImpl(CaptureControllerListener* listener); virtual ~CaptureControllerImpl(); // Disallow copy and move. CaptureControllerImpl(const CaptureControllerImpl&) = delete; CaptureControllerImpl& operator=(const CaptureControllerImpl&) = delete; // CaptureController void InitCaptureDevice(TextureRegistrar* texture_registrar, const std::string& device_id, bool record_audio, ResolutionPreset resolution_preset) override; uint32_t GetPreviewWidth() const override { return preview_frame_width_; } uint32_t GetPreviewHeight() const override { return preview_frame_height_; } void StartPreview() override; void PausePreview() override; void ResumePreview() override; void StartRecord(const std::string& file_path, int64_t max_video_duration_ms) override; void StopRecord() override; void TakePicture(const std::string& file_path) override; // CaptureEngineObserver void OnEvent(IMFMediaEvent* event) override; bool IsReadyForSample() const override { return capture_engine_state_ == CaptureEngineState::kInitialized && preview_handler_ && preview_handler_->IsRunning(); } bool UpdateBuffer(uint8_t* data, uint32_t data_length) override; void UpdateCaptureTime(uint64_t capture_time) override; // Sets capture engine, for testing purposes. void SetCaptureEngine(IMFCaptureEngine* capture_engine) { capture_engine_ = capture_engine; } // Sets video source, for testing purposes. void SetVideoSource(IMFMediaSource* video_source) { video_source_ = video_source; } // Sets audio source, for testing purposes. void SetAudioSource(IMFMediaSource* audio_source) { audio_source_ = audio_source; } private: // Helper function to return initialized state as boolean; bool IsInitialized() const { return capture_engine_state_ == CaptureEngineState::kInitialized; } // Resets capture controller state. // This is called if capture engine creation fails or is disposed. void ResetCaptureController(); // Returns max preview height calculated from resolution present. uint32_t GetMaxPreviewHeight() const; // Uses first audio source to capture audio. // Note: Enumerating audio sources via platform interface is not supported. HRESULT CreateDefaultAudioCaptureSource(); // Initializes video capture source from camera device. HRESULT CreateVideoCaptureSourceForDevice(const std::string& video_device_id); // Creates DX11 Device and D3D Manager. HRESULT CreateD3DManagerWithDX11Device(); // Initializes capture engine object. HRESULT CreateCaptureEngine(); // Enumerates video_sources media types and finds out best resolution // for preview and video capture. HRESULT FindBaseMediaTypes(); // Stops timed video record. Called internally when record handler when max // recording time is exceeded. void StopTimedRecord(); // Stops preview. Called internally on camera reset and dispose. void StopPreview(); // Handles capture engine initalization event. void OnCaptureEngineInitialized(bool success, const std::string& error); // Handles capture engine errors. void OnCaptureEngineError(HRESULT hr, const std::string& error); // Handles picture events. void OnPicture(bool success, const std::string& error); // Handles preview started events. void OnPreviewStarted(bool success, const std::string& error); // Handles preview stopped events. void OnPreviewStopped(bool success, const std::string& error); // Handles record started events. void OnRecordStarted(bool success, const std::string& error); // Handles record stopped events. void OnRecordStopped(bool success, const std::string& error); bool media_foundation_started_ = false; bool record_audio_ = false; uint32_t preview_frame_width_ = 0; uint32_t preview_frame_height_ = 0; UINT dx_device_reset_token_ = 0; std::unique_ptr<RecordHandler> record_handler_; std::unique_ptr<PreviewHandler> preview_handler_; std::unique_ptr<PhotoHandler> photo_handler_; std::unique_ptr<TextureHandler> texture_handler_; CaptureControllerListener* capture_controller_listener_; std::string video_device_id_; CaptureEngineState capture_engine_state_ = CaptureEngineState::kNotInitialized; ResolutionPreset resolution_preset_ = ResolutionPreset::kMedium; ComPtr<IMFCaptureEngine> capture_engine_; ComPtr<CaptureEngineListener> capture_engine_callback_handler_; ComPtr<IMFDXGIDeviceManager> dxgi_device_manager_; ComPtr<ID3D11Device> dx11_device_; ComPtr<IMFMediaType> base_capture_media_type_; ComPtr<IMFMediaType> base_preview_media_type_; ComPtr<IMFMediaSource> video_source_; ComPtr<IMFMediaSource> audio_source_; TextureRegistrar* texture_registrar_ = nullptr; }; // Inferface for factory classes that create |CaptureController| instances. class CaptureControllerFactory { public: CaptureControllerFactory() {} virtual ~CaptureControllerFactory() = default; // Disallow copy and move. CaptureControllerFactory(const CaptureControllerFactory&) = delete; CaptureControllerFactory& operator=(const CaptureControllerFactory&) = delete; // Create and return a |CaptureController| that makes callbacks on the // specified |CaptureControllerListener|, which must not be null. virtual std::unique_ptr<CaptureController> CreateCaptureController( CaptureControllerListener* listener) = 0; }; // Concreate implementation of |CaptureControllerFactory|. class CaptureControllerFactoryImpl : public CaptureControllerFactory { public: CaptureControllerFactoryImpl() {} virtual ~CaptureControllerFactoryImpl() = default; // Disallow copy and move. CaptureControllerFactoryImpl(const CaptureControllerFactoryImpl&) = delete; CaptureControllerFactoryImpl& operator=(const CaptureControllerFactoryImpl&) = delete; std::unique_ptr<CaptureController> CreateCaptureController( CaptureControllerListener* listener) override { return std::make_unique<CaptureControllerImpl>(listener); } }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_CONTROLLER_H_
coral-labs/plugins
packages/camera/camera_windows/windows/string_utils.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_STRING_UTILS_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_STRING_UTILS_H_ #include <shobjidl.h> #include <string> namespace camera_windows { // Converts the given UTF-16 string to UTF-8. std::string Utf8FromUtf16(const std::wstring& utf16_string); // Converts the given UTF-8 string to UTF-16. std::wstring Utf16FromUtf8(const std::string& utf8_string); } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_STRING_UTILS_H_
coral-labs/plugins
packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FlutterWebView_Test.h
<gh_stars>1-10 // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This header is available in the Test module. Import via "@import webview_flutter_wkwebview.Test;" #import <webview_flutter_wkwebview/FlutterWebView.h> NS_ASSUME_NONNULL_BEGIN @interface FLTWebViewController () - (NSURLRequest *)buildNSURLRequest:(NSDictionary<NSString *, id> *)arguments; - (void)onLoadUrl:(FlutterMethodCall *)call result:(FlutterResult)result; - (void)onLoadRequest:(FlutterMethodCall *)call result:(FlutterResult)result; @end NS_ASSUME_NONNULL_END
coral-labs/plugins
packages/camera/camera_windows/windows/capture_controller_listener.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_CONTROLLER_LISTENER_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_CONTROLLER_LISTENER_H_ #include <functional> namespace camera_windows { // Interface for classes that receives callbacks on events from the associated // |CaptureController|. class CaptureControllerListener { public: virtual ~CaptureControllerListener() = default; // Called by CaptureController on successful capture engine initialization. // // texture_id: A 64bit integer id registered by TextureRegistrar virtual void OnCreateCaptureEngineSucceeded(int64_t texture_id) = 0; // Called by CaptureController if initializing the capture engine fails. // // error: A string describing the error. virtual void OnCreateCaptureEngineFailed(const std::string& error) = 0; // Called by CaptureController on successfully started preview. // // width: Preview frame width. // height: Preview frame height. virtual void OnStartPreviewSucceeded(int32_t width, int32_t height) = 0; // Called by CaptureController if starting the preview fails. // // error: A string describing the error. virtual void OnStartPreviewFailed(const std::string& error) = 0; // Called by CaptureController on successfully paused preview. virtual void OnPausePreviewSucceeded() = 0; // Called by CaptureController if pausing the preview fails. // // error: A string describing the error. virtual void OnPausePreviewFailed(const std::string& error) = 0; // Called by CaptureController on successfully resumed preview. virtual void OnResumePreviewSucceeded() = 0; // Called by CaptureController if resuming the preview fails. // // error: A string describing the error. virtual void OnResumePreviewFailed(const std::string& error) = 0; // Called by CaptureController on successfully started recording. virtual void OnStartRecordSucceeded() = 0; // Called by CaptureController if starting the recording fails. // // error: A string describing the error. virtual void OnStartRecordFailed(const std::string& error) = 0; // Called by CaptureController on successfully stopped recording. // // file_path: Filesystem path of the recorded video file. virtual void OnStopRecordSucceeded(const std::string& file_path) = 0; // Called by CaptureController if stopping the recording fails. // // error: A string describing the error. virtual void OnStopRecordFailed(const std::string& error) = 0; // Called by CaptureController on successfully captured picture. // // file_path: Filesystem path of the captured image. virtual void OnTakePictureSucceeded(const std::string& file_path) = 0; // Called by CaptureController if taking picture fails. // // error: A string describing the error. virtual void OnTakePictureFailed(const std::string& error) = 0; // Called by CaptureController when timed recording is successfully recorded. // // file_path: Filesystem path of the captured image. // video_duration: Duration of recorded video in milliseconds. virtual void OnVideoRecordSucceeded(const std::string& file_path, int64_t video_duration_ms) = 0; // Called by CaptureController if timed recording fails. // // error: A string describing the error. virtual void OnVideoRecordFailed(const std::string& error) = 0; // Called by CaptureController if capture engine returns error. // For example when camera is disconnected while on use. // // error: A string describing the error. virtual void OnCaptureError(const std::string& error) = 0; }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_CONTROLLER_LISTENER_H_
coral-labs/plugins
packages/camera/camera_windows/windows/test/mocks.h
<filename>packages/camera/camera_windows/windows/test/mocks.h // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_TEST_MOCKS_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_TEST_MOCKS_H_ #include <flutter/method_call.h> #include <flutter/method_result_functions.h> #include <flutter/standard_method_codec.h> #include <flutter/texture_registrar.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <mfcaptureengine.h> #include "camera.h" #include "camera_plugin.h" #include "capture_controller.h" #include "capture_controller_listener.h" #include "capture_engine_listener.h" namespace camera_windows { namespace test { namespace { using flutter::EncodableMap; using flutter::EncodableValue; using ::testing::_; class MockMethodResult : public flutter::MethodResult<> { public: ~MockMethodResult() = default; MOCK_METHOD(void, SuccessInternal, (const EncodableValue* result), (override)); MOCK_METHOD(void, ErrorInternal, (const std::string& error_code, const std::string& error_message, const EncodableValue* details), (override)); MOCK_METHOD(void, NotImplementedInternal, (), (override)); }; class MockBinaryMessenger : public flutter::BinaryMessenger { public: ~MockBinaryMessenger() = default; MOCK_METHOD(void, Send, (const std::string& channel, const uint8_t* message, size_t message_size, flutter::BinaryReply reply), (const)); MOCK_METHOD(void, SetMessageHandler, (const std::string& channel, flutter::BinaryMessageHandler handler), ()); }; class MockTextureRegistrar : public flutter::TextureRegistrar { public: MockTextureRegistrar() { ON_CALL(*this, RegisterTexture) .WillByDefault([this](flutter::TextureVariant* texture) -> int64_t { EXPECT_TRUE(texture); this->texture_ = texture; this->texture_id_ = 1000; return this->texture_id_; }); ON_CALL(*this, UnregisterTexture) .WillByDefault([this](int64_t tid) -> bool { if (tid == this->texture_id_) { texture_ = nullptr; this->texture_id_ = -1; return true; } return false; }); ON_CALL(*this, MarkTextureFrameAvailable) .WillByDefault([this](int64_t tid) -> bool { if (tid == this->texture_id_) { return true; } return false; }); } ~MockTextureRegistrar() { texture_ = nullptr; } MOCK_METHOD(int64_t, RegisterTexture, (flutter::TextureVariant * texture), (override)); MOCK_METHOD(bool, UnregisterTexture, (int64_t), (override)); MOCK_METHOD(bool, MarkTextureFrameAvailable, (int64_t), (override)); int64_t texture_id_ = -1; flutter::TextureVariant* texture_ = nullptr; }; class MockCameraFactory : public CameraFactory { public: MockCameraFactory() { ON_CALL(*this, CreateCamera).WillByDefault([this]() { assert(this->pending_camera_); return std::move(this->pending_camera_); }); } ~MockCameraFactory() = default; // Disallow copy and move. MockCameraFactory(const MockCameraFactory&) = delete; MockCameraFactory& operator=(const MockCameraFactory&) = delete; MOCK_METHOD(std::unique_ptr<Camera>, CreateCamera, (const std::string& device_id), (override)); std::unique_ptr<Camera> pending_camera_; }; class MockCamera : public Camera { public: MockCamera(const std::string& device_id) : device_id_(device_id), Camera(device_id){}; ~MockCamera() = default; // Disallow copy and move. MockCamera(const MockCamera&) = delete; MockCamera& operator=(const MockCamera&) = delete; MOCK_METHOD(void, OnCreateCaptureEngineSucceeded, (int64_t texture_id), (override)); MOCK_METHOD(std::unique_ptr<flutter::MethodResult<>>, GetPendingResultByType, (PendingResultType type)); MOCK_METHOD(void, OnCreateCaptureEngineFailed, (const std::string& error), (override)); MOCK_METHOD(void, OnStartPreviewSucceeded, (int32_t width, int32_t height), (override)); MOCK_METHOD(void, OnStartPreviewFailed, (const std::string& error), (override)); MOCK_METHOD(void, OnResumePreviewSucceeded, (), (override)); MOCK_METHOD(void, OnResumePreviewFailed, (const std::string& error), (override)); MOCK_METHOD(void, OnPausePreviewSucceeded, (), (override)); MOCK_METHOD(void, OnPausePreviewFailed, (const std::string& error), (override)); MOCK_METHOD(void, OnStartRecordSucceeded, (), (override)); MOCK_METHOD(void, OnStartRecordFailed, (const std::string& error), (override)); MOCK_METHOD(void, OnStopRecordSucceeded, (const std::string& file_path), (override)); MOCK_METHOD(void, OnStopRecordFailed, (const std::string& error), (override)); MOCK_METHOD(void, OnTakePictureSucceeded, (const std::string& file_path), (override)); MOCK_METHOD(void, OnTakePictureFailed, (const std::string& error), (override)); MOCK_METHOD(void, OnVideoRecordSucceeded, (const std::string& file_path, int64_t video_duration), (override)); MOCK_METHOD(void, OnVideoRecordFailed, (const std::string& error), (override)); MOCK_METHOD(void, OnCaptureError, (const std::string& error), (override)); MOCK_METHOD(bool, HasDeviceId, (std::string & device_id), (const override)); MOCK_METHOD(bool, HasCameraId, (int64_t camera_id), (const override)); MOCK_METHOD(bool, AddPendingResult, (PendingResultType type, std::unique_ptr<MethodResult<>> result), (override)); MOCK_METHOD(bool, HasPendingResultByType, (PendingResultType type), (const override)); MOCK_METHOD(camera_windows::CaptureController*, GetCaptureController, (), (override)); MOCK_METHOD(void, InitCamera, (flutter::TextureRegistrar * texture_registrar, flutter::BinaryMessenger* messenger, bool record_audio, ResolutionPreset resolution_preset), (override)); std::unique_ptr<CaptureController> capture_controller_; std::unique_ptr<MethodResult<>> pending_result_; std::string device_id_; int64_t camera_id_ = -1; }; class MockCaptureControllerFactory : public CaptureControllerFactory { public: MockCaptureControllerFactory(){}; virtual ~MockCaptureControllerFactory() = default; // Disallow copy and move. MockCaptureControllerFactory(const MockCaptureControllerFactory&) = delete; MockCaptureControllerFactory& operator=(const MockCaptureControllerFactory&) = delete; MOCK_METHOD(std::unique_ptr<CaptureController>, CreateCaptureController, (CaptureControllerListener * listener), (override)); }; class MockCaptureController : public CaptureController { public: ~MockCaptureController() = default; MOCK_METHOD(void, InitCaptureDevice, (flutter::TextureRegistrar * texture_registrar, const std::string& device_id, bool record_audio, ResolutionPreset resolution_preset), (override)); MOCK_METHOD(uint32_t, GetPreviewWidth, (), (const override)); MOCK_METHOD(uint32_t, GetPreviewHeight, (), (const override)); // Actions MOCK_METHOD(void, StartPreview, (), (override)); MOCK_METHOD(void, ResumePreview, (), (override)); MOCK_METHOD(void, PausePreview, (), (override)); MOCK_METHOD(void, StartRecord, (const std::string& file_path, int64_t max_video_duration_ms), (override)); MOCK_METHOD(void, StopRecord, (), (override)); MOCK_METHOD(void, TakePicture, (const std::string& file_path), (override)); }; // MockCameraPlugin extends CameraPlugin behaviour a bit to allow adding cameras // without creating them first with create message handler and mocking static // system calls class MockCameraPlugin : public CameraPlugin { public: MockCameraPlugin(flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger) : CameraPlugin(texture_registrar, messenger){}; // Creates a plugin instance with the given CameraFactory instance. // Exists for unit testing with mock implementations. MockCameraPlugin(flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger, std::unique_ptr<CameraFactory> camera_factory) : CameraPlugin(texture_registrar, messenger, std::move(camera_factory)){}; ~MockCameraPlugin() = default; // Disallow copy and move. MockCameraPlugin(const MockCameraPlugin&) = delete; MockCameraPlugin& operator=(const MockCameraPlugin&) = delete; MOCK_METHOD(bool, EnumerateVideoCaptureDeviceSources, (IMFActivate * **devices, UINT32* count), (override)); // Helper to add camera without creating it via CameraFactory for testing // purposes void AddCamera(std::unique_ptr<Camera> camera) { cameras_.push_back(std::move(camera)); } }; class MockCaptureSource : public IMFCaptureSource { public: MockCaptureSource(){}; ~MockCaptureSource() = default; // IUnknown STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFCaptureSource) { *ppv = static_cast<IMFCaptureSource*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } MOCK_METHOD(HRESULT, GetCaptureDeviceSource, (MF_CAPTURE_ENGINE_DEVICE_TYPE mfCaptureEngineDeviceType, IMFMediaSource** ppMediaSource)); MOCK_METHOD(HRESULT, GetCaptureDeviceActivate, (MF_CAPTURE_ENGINE_DEVICE_TYPE mfCaptureEngineDeviceType, IMFActivate** ppActivate)); MOCK_METHOD(HRESULT, GetService, (REFIID rguidService, REFIID riid, IUnknown** ppUnknown)); MOCK_METHOD(HRESULT, AddEffect, (DWORD dwSourceStreamIndex, IUnknown* pUnknown)); MOCK_METHOD(HRESULT, RemoveEffect, (DWORD dwSourceStreamIndex, IUnknown* pUnknown)); MOCK_METHOD(HRESULT, RemoveAllEffects, (DWORD dwSourceStreamIndex)); MOCK_METHOD(HRESULT, GetAvailableDeviceMediaType, (DWORD dwSourceStreamIndex, DWORD dwMediaTypeIndex, IMFMediaType** ppMediaType)); MOCK_METHOD(HRESULT, SetCurrentDeviceMediaType, (DWORD dwSourceStreamIndex, IMFMediaType* pMediaType)); MOCK_METHOD(HRESULT, GetCurrentDeviceMediaType, (DWORD dwSourceStreamIndex, IMFMediaType** ppMediaType)); MOCK_METHOD(HRESULT, GetDeviceStreamCount, (DWORD * pdwStreamCount)); MOCK_METHOD(HRESULT, GetDeviceStreamCategory, (DWORD dwSourceStreamIndex, MF_CAPTURE_ENGINE_STREAM_CATEGORY* pStreamCategory)); MOCK_METHOD(HRESULT, GetMirrorState, (DWORD dwStreamIndex, BOOL* pfMirrorState)); MOCK_METHOD(HRESULT, SetMirrorState, (DWORD dwStreamIndex, BOOL fMirrorState)); MOCK_METHOD(HRESULT, GetStreamIndexFromFriendlyName, (UINT32 uifriendlyName, DWORD* pdwActualStreamIndex)); private: volatile ULONG ref_ = 0; }; // Uses IMFMediaSourceEx which has SetD3DManager method. class MockMediaSource : public IMFMediaSourceEx { public: MockMediaSource(){}; ~MockMediaSource() = default; // IUnknown STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFMediaSource) { *ppv = static_cast<IMFMediaSource*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } // IMFMediaSource HRESULT GetCharacteristics(DWORD* dwCharacteristics) override { return E_NOTIMPL; } // IMFMediaSource HRESULT CreatePresentationDescriptor( IMFPresentationDescriptor** presentationDescriptor) override { return E_NOTIMPL; } // IMFMediaSource HRESULT Start(IMFPresentationDescriptor* presentationDescriptor, const GUID* guidTimeFormat, const PROPVARIANT* varStartPosition) override { return E_NOTIMPL; } // IMFMediaSource HRESULT Stop(void) override { return E_NOTIMPL; } // IMFMediaSource HRESULT Pause(void) override { return E_NOTIMPL; } // IMFMediaSource HRESULT Shutdown(void) override { return E_NOTIMPL; } // IMFMediaEventGenerator HRESULT GetEvent(DWORD dwFlags, IMFMediaEvent** event) override { return E_NOTIMPL; } // IMFMediaEventGenerator HRESULT BeginGetEvent(IMFAsyncCallback* callback, IUnknown* unkState) override { return E_NOTIMPL; } // IMFMediaEventGenerator HRESULT EndGetEvent(IMFAsyncResult* result, IMFMediaEvent** event) override { return E_NOTIMPL; } // IMFMediaEventGenerator HRESULT QueueEvent(MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, const PROPVARIANT* value) override { return E_NOTIMPL; } // IMFMediaSourceEx HRESULT GetSourceAttributes(IMFAttributes** attributes) { return E_NOTIMPL; } // IMFMediaSourceEx HRESULT GetStreamAttributes(DWORD stream_id, IMFAttributes** attributes) { return E_NOTIMPL; } // IMFMediaSourceEx HRESULT SetD3DManager(IUnknown* manager) { return S_OK; } private: volatile ULONG ref_ = 0; }; class MockCapturePreviewSink : public IMFCapturePreviewSink { public: // IMFCaptureSink MOCK_METHOD(HRESULT, GetOutputMediaType, (DWORD dwSinkStreamIndex, IMFMediaType** ppMediaType)); // IMFCaptureSink MOCK_METHOD(HRESULT, GetService, (DWORD dwSinkStreamIndex, REFGUID rguidService, REFIID riid, IUnknown** ppUnknown)); // IMFCaptureSink MOCK_METHOD(HRESULT, AddStream, (DWORD dwSourceStreamIndex, IMFMediaType* pMediaType, IMFAttributes* pAttributes, DWORD* pdwSinkStreamIndex)); // IMFCaptureSink MOCK_METHOD(HRESULT, Prepare, ()); // IMFCaptureSink MOCK_METHOD(HRESULT, RemoveAllStreams, ()); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, SetRenderHandle, (HANDLE handle)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, SetRenderSurface, (IUnknown * pSurface)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, UpdateVideo, (const MFVideoNormalizedRect* pSrc, const RECT* pDst, const COLORREF* pBorderClr)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, SetSampleCallback, (DWORD dwStreamSinkIndex, IMFCaptureEngineOnSampleCallback* pCallback)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, GetMirrorState, (BOOL * pfMirrorState)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, SetMirrorState, (BOOL fMirrorState)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, GetRotation, (DWORD dwStreamIndex, DWORD* pdwRotationValue)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, SetRotation, (DWORD dwStreamIndex, DWORD dwRotationValue)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, SetCustomSink, (IMFMediaSink * pMediaSink)); // IUnknown STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFCapturePreviewSink) { *ppv = static_cast<IMFCapturePreviewSink*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } void SendFakeSample(uint8_t* src_buffer, uint32_t size) { assert(sample_callback_); ComPtr<IMFSample> sample; ComPtr<IMFMediaBuffer> buffer; HRESULT hr = MFCreateSample(&sample); if (SUCCEEDED(hr)) { hr = MFCreateMemoryBuffer(size, &buffer); } if (SUCCEEDED(hr)) { uint8_t* target_data; if (SUCCEEDED(buffer->Lock(&target_data, nullptr, nullptr))) { std::copy(src_buffer, src_buffer + size, target_data); } hr = buffer->Unlock(); } if (SUCCEEDED(hr)) { hr = buffer->SetCurrentLength(size); } if (SUCCEEDED(hr)) { hr = sample->AddBuffer(buffer.Get()); } if (SUCCEEDED(hr)) { sample_callback_->OnSample(sample.Get()); } } ComPtr<IMFCaptureEngineOnSampleCallback> sample_callback_; private: ~MockCapturePreviewSink() = default; volatile ULONG ref_ = 0; }; class MockCaptureRecordSink : public IMFCaptureRecordSink { public: // IMFCaptureSink MOCK_METHOD(HRESULT, GetOutputMediaType, (DWORD dwSinkStreamIndex, IMFMediaType** ppMediaType)); // IMFCaptureSink MOCK_METHOD(HRESULT, GetService, (DWORD dwSinkStreamIndex, REFGUID rguidService, REFIID riid, IUnknown** ppUnknown)); // IMFCaptureSink MOCK_METHOD(HRESULT, AddStream, (DWORD dwSourceStreamIndex, IMFMediaType* pMediaType, IMFAttributes* pAttributes, DWORD* pdwSinkStreamIndex)); // IMFCaptureSink MOCK_METHOD(HRESULT, Prepare, ()); // IMFCaptureSink MOCK_METHOD(HRESULT, RemoveAllStreams, ()); // IMFCaptureRecordSink MOCK_METHOD(HRESULT, SetOutputByteStream, (IMFByteStream * pByteStream, REFGUID guidContainerType)); // IMFCaptureRecordSink MOCK_METHOD(HRESULT, SetOutputFileName, (LPCWSTR fileName)); // IMFCaptureRecordSink MOCK_METHOD(HRESULT, SetSampleCallback, (DWORD dwStreamSinkIndex, IMFCaptureEngineOnSampleCallback* pCallback)); // IMFCaptureRecordSink MOCK_METHOD(HRESULT, SetCustomSink, (IMFMediaSink * pMediaSink)); // IMFCaptureRecordSink MOCK_METHOD(HRESULT, GetRotation, (DWORD dwStreamIndex, DWORD* pdwRotationValue)); // IMFCaptureRecordSink MOCK_METHOD(HRESULT, SetRotation, (DWORD dwStreamIndex, DWORD dwRotationValue)); // IUnknown STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFCaptureRecordSink) { *ppv = static_cast<IMFCaptureRecordSink*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } private: ~MockCaptureRecordSink() = default; volatile ULONG ref_ = 0; }; class MockCapturePhotoSink : public IMFCapturePhotoSink { public: // IMFCaptureSink MOCK_METHOD(HRESULT, GetOutputMediaType, (DWORD dwSinkStreamIndex, IMFMediaType** ppMediaType)); // IMFCaptureSink MOCK_METHOD(HRESULT, GetService, (DWORD dwSinkStreamIndex, REFGUID rguidService, REFIID riid, IUnknown** ppUnknown)); // IMFCaptureSink MOCK_METHOD(HRESULT, AddStream, (DWORD dwSourceStreamIndex, IMFMediaType* pMediaType, IMFAttributes* pAttributes, DWORD* pdwSinkStreamIndex)); // IMFCaptureSink MOCK_METHOD(HRESULT, Prepare, ()); // IMFCaptureSink MOCK_METHOD(HRESULT, RemoveAllStreams, ()); // IMFCapturePhotoSink MOCK_METHOD(HRESULT, SetOutputFileName, (LPCWSTR fileName)); // IMFCapturePhotoSink MOCK_METHOD(HRESULT, SetSampleCallback, (IMFCaptureEngineOnSampleCallback * pCallback)); // IMFCapturePhotoSink MOCK_METHOD(HRESULT, SetOutputByteStream, (IMFByteStream * pByteStream)); // IUnknown STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFCapturePhotoSink) { *ppv = static_cast<IMFCapturePhotoSink*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } private: ~MockCapturePhotoSink() = default; volatile ULONG ref_ = 0; }; template <class T> class FakeIMFAttributesBase : public T { static_assert(std::is_base_of<IMFAttributes, T>::value, "I must inherit from IMFAttributes"); // IIMFAttributes HRESULT GetItem(REFGUID guidKey, PROPVARIANT* pValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetItemType(REFGUID guidKey, MF_ATTRIBUTE_TYPE* pType) override { return E_NOTIMPL; } // IIMFAttributes HRESULT CompareItem(REFGUID guidKey, REFPROPVARIANT Value, BOOL* pbResult) override { return E_NOTIMPL; } // IIMFAttributes HRESULT Compare(IMFAttributes* pTheirs, MF_ATTRIBUTES_MATCH_TYPE MatchType, BOOL* pbResult) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetUINT32(REFGUID guidKey, UINT32* punValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetUINT64(REFGUID guidKey, UINT64* punValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetDouble(REFGUID guidKey, double* pfValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetGUID(REFGUID guidKey, GUID* pguidValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetStringLength(REFGUID guidKey, UINT32* pcchLength) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetString(REFGUID guidKey, LPWSTR pwszValue, UINT32 cchBufSize, UINT32* pcchLength) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetAllocatedString(REFGUID guidKey, LPWSTR* ppwszValue, UINT32* pcchLength) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetBlobSize(REFGUID guidKey, UINT32* pcbBlobSize) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetBlob(REFGUID guidKey, UINT8* pBuf, UINT32 cbBufSize, UINT32* pcbBlobSize) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetAllocatedBlob(REFGUID guidKey, UINT8** ppBuf, UINT32* pcbSize) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetUnknown(REFGUID guidKey, REFIID riid, __RPC__deref_out_opt LPVOID* ppv) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetItem(REFGUID guidKey, REFPROPVARIANT Value) override { return E_NOTIMPL; } // IIMFAttributes HRESULT DeleteItem(REFGUID guidKey) override { return E_NOTIMPL; } // IIMFAttributes HRESULT DeleteAllItems(void) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetUINT32(REFGUID guidKey, UINT32 unValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetUINT64(REFGUID guidKey, UINT64 unValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetDouble(REFGUID guidKey, double fValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetGUID(REFGUID guidKey, REFGUID guidValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetString(REFGUID guidKey, LPCWSTR wszValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetBlob(REFGUID guidKey, const UINT8* pBuf, UINT32 cbBufSize) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetUnknown(REFGUID guidKey, IUnknown* pUnknown) override { return E_NOTIMPL; } // IIMFAttributes HRESULT LockStore(void) override { return E_NOTIMPL; } // IIMFAttributes HRESULT UnlockStore(void) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetCount(UINT32* pcItems) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetItemByIndex(UINT32 unIndex, GUID* pguidKey, PROPVARIANT* pValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT CopyAllItems(IMFAttributes* pDest) override { return E_NOTIMPL; } }; class FakeMediaType : public FakeIMFAttributesBase<IMFMediaType> { public: FakeMediaType(GUID major_type, GUID sub_type, int width, int height) : major_type_(major_type), sub_type_(sub_type), width_(width), height_(height){}; // IMFAttributes HRESULT GetUINT64(REFGUID key, UINT64* value) override { if (key == MF_MT_FRAME_SIZE) { *value = (int64_t)width_ << 32 | (int64_t)height_; return S_OK; } else if (key == MF_MT_FRAME_RATE) { *value = (int64_t)frame_rate_ << 32 | 1; return S_OK; } return E_FAIL; }; // IMFAttributes HRESULT GetGUID(REFGUID key, GUID* value) override { if (key == MF_MT_MAJOR_TYPE) { *value = major_type_; return S_OK; } else if (key == MF_MT_SUBTYPE) { *value = sub_type_; return S_OK; } return E_FAIL; } // IIMFAttributes HRESULT CopyAllItems(IMFAttributes* pDest) override { pDest->SetUINT64(MF_MT_FRAME_SIZE, (int64_t)width_ << 32 | (int64_t)height_); pDest->SetUINT64(MF_MT_FRAME_RATE, (int64_t)frame_rate_ << 32 | 1); pDest->SetGUID(MF_MT_MAJOR_TYPE, major_type_); pDest->SetGUID(MF_MT_SUBTYPE, sub_type_); return S_OK; } // IMFMediaType HRESULT STDMETHODCALLTYPE GetMajorType(GUID* pguidMajorType) override { return E_NOTIMPL; }; // IMFMediaType HRESULT STDMETHODCALLTYPE IsCompressedFormat(BOOL* pfCompressed) override { return E_NOTIMPL; } // IMFMediaType HRESULT STDMETHODCALLTYPE IsEqual(IMFMediaType* pIMediaType, DWORD* pdwFlags) override { return E_NOTIMPL; } // IMFMediaType HRESULT STDMETHODCALLTYPE GetRepresentation( GUID guidRepresentation, LPVOID* ppvRepresentation) override { return E_NOTIMPL; } // IMFMediaType HRESULT STDMETHODCALLTYPE FreeRepresentation( GUID guidRepresentation, LPVOID pvRepresentation) override { return E_NOTIMPL; } // IUnknown STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFMediaType) { *ppv = static_cast<IMFMediaType*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } private: ~FakeMediaType() = default; volatile ULONG ref_ = 0; const GUID major_type_; const GUID sub_type_; const int width_; const int height_; const int frame_rate_ = 30; }; class MockCaptureEngine : public IMFCaptureEngine { public: MockCaptureEngine() { ON_CALL(*this, Initialize) .WillByDefault([this](IMFCaptureEngineOnEventCallback* callback, IMFAttributes* attributes, IUnknown* audioSource, IUnknown* videoSource) -> HRESULT { EXPECT_TRUE(callback); EXPECT_TRUE(attributes); EXPECT_TRUE(videoSource); // audioSource is allowed to be nullptr; callback_ = callback; videoSource_ = reinterpret_cast<IMFMediaSource*>(videoSource); audioSource_ = reinterpret_cast<IMFMediaSource*>(audioSource); initialized_ = true; return S_OK; }); }; virtual ~MockCaptureEngine() = default; MOCK_METHOD(HRESULT, Initialize, (IMFCaptureEngineOnEventCallback * callback, IMFAttributes* attributes, IUnknown* audioSource, IUnknown* videoSource)); MOCK_METHOD(HRESULT, StartPreview, ()); MOCK_METHOD(HRESULT, StopPreview, ()); MOCK_METHOD(HRESULT, StartRecord, ()); MOCK_METHOD(HRESULT, StopRecord, (BOOL finalize, BOOL flushUnprocessedSamples)); MOCK_METHOD(HRESULT, TakePhoto, ()); MOCK_METHOD(HRESULT, GetSink, (MF_CAPTURE_ENGINE_SINK_TYPE type, IMFCaptureSink** sink)); MOCK_METHOD(HRESULT, GetSource, (IMFCaptureSource * *ppSource)); // IUnknown STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFCaptureEngine) { *ppv = static_cast<IMFCaptureEngine*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } void CreateFakeEvent(HRESULT hrStatus, GUID event_type) { EXPECT_TRUE(initialized_); ComPtr<IMFMediaEvent> event; MFCreateMediaEvent(MEExtendedType, event_type, hrStatus, nullptr, &event); if (callback_) { callback_->OnEvent(event.Get()); } } ComPtr<IMFCaptureEngineOnEventCallback> callback_; ComPtr<IMFMediaSource> videoSource_; ComPtr<IMFMediaSource> audioSource_; volatile ULONG ref_ = 0; bool initialized_ = false; }; #define MOCK_DEVICE_ID "mock_device_id" #define MOCK_CAMERA_NAME "mock_camera_name <" MOCK_DEVICE_ID ">" #define MOCK_INVALID_CAMERA_NAME "invalid_camera_name" } // namespace } // namespace test } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_TEST_MOCKS_H_
coral-labs/plugins
packages/camera/camera/ios/Classes/FLTSavePhotoDelegate_Test.h
<reponame>coral-labs/plugins // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FLTSavePhotoDelegate.h" /** API exposed for unit tests. */ @interface FLTSavePhotoDelegate () /// Handler to write captured photo data into a file. /// @param error the capture error. /// @param photoDataProvider a closure that provides photo data. - (void)handlePhotoCaptureResultWithError:(NSError *)error photoDataProvider:(NSData * (^)(void))photoDataProvider; @end
coral-labs/plugins
packages/camera/camera_windows/windows/capture_engine_listener.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_ENGINE_LISTENER_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_ENGINE_LISTENER_H_ #include <mfcaptureengine.h> #include <cassert> #include <functional> namespace camera_windows { // A class that implements callbacks for events from a |CaptureEngineListener|. class CaptureEngineObserver { public: virtual ~CaptureEngineObserver() = default; // Returns true if sample can be processed. virtual bool IsReadyForSample() const = 0; // Handles Capture Engine media events. virtual void OnEvent(IMFMediaEvent* event) = 0; // Updates texture buffer virtual bool UpdateBuffer(uint8_t* data, uint32_t new_length) = 0; // Handles capture timestamps updates. // Used to stop timed recordings when recorded time is exceeded. virtual void UpdateCaptureTime(uint64_t capture_time) = 0; }; // Listener for Windows Media Foundation capture engine events and samples. // // Events are redirected to observers for processing. Samples are preprosessed // and sent to the associated observer if it is ready to process samples. class CaptureEngineListener : public IMFCaptureEngineOnSampleCallback, public IMFCaptureEngineOnEventCallback { public: CaptureEngineListener(CaptureEngineObserver* observer) : observer_(observer) { assert(observer); } ~CaptureEngineListener() {} // Disallow copy and move. CaptureEngineListener(const CaptureEngineListener&) = delete; CaptureEngineListener& operator=(const CaptureEngineListener&) = delete; // IUnknown STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv); // IMFCaptureEngineOnEventCallback STDMETHODIMP OnEvent(IMFMediaEvent* pEvent); // IMFCaptureEngineOnSampleCallback STDMETHODIMP_(HRESULT) OnSample(IMFSample* pSample); private: CaptureEngineObserver* observer_; volatile ULONG ref_ = 0; }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_ENGINE_LISTENER_H_
coral-labs/plugins
packages/camera/camera_windows/windows/camera_plugin.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAMERA_PLUGIN_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAMERA_PLUGIN_H_ #include <flutter/flutter_view.h> #include <flutter/method_channel.h> #include <flutter/plugin_registrar_windows.h> #include <flutter/standard_method_codec.h> #include <functional> #include "camera.h" #include "capture_controller.h" #include "capture_controller_listener.h" namespace camera_windows { using flutter::MethodResult; namespace test { namespace { // Forward declaration of test class. class MockCameraPlugin; } // namespace } // namespace test class CameraPlugin : public flutter::Plugin, public VideoCaptureDeviceEnumerator { public: static void RegisterWithRegistrar(flutter::PluginRegistrarWindows* registrar); CameraPlugin(flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger); // Creates a plugin instance with the given CameraFactory instance. // Exists for unit testing with mock implementations. CameraPlugin(flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger, std::unique_ptr<CameraFactory> camera_factory); virtual ~CameraPlugin(); // Disallow copy and move. CameraPlugin(const CameraPlugin&) = delete; CameraPlugin& operator=(const CameraPlugin&) = delete; // Called when a method is called on plugin channel. void HandleMethodCall(const flutter::MethodCall<>& method_call, std::unique_ptr<MethodResult<>> result); private: // Loops through cameras and returns camera // with matching device_id or nullptr. Camera* GetCameraByDeviceId(std::string& device_id); // Loops through cameras and returns camera // with matching camera_id or nullptr. Camera* GetCameraByCameraId(int64_t camera_id); // Disposes camera by camera id. void DisposeCameraByCameraId(int64_t camera_id); // Enumerates video capture devices. bool EnumerateVideoCaptureDeviceSources(IMFActivate*** devices, UINT32* count) override; // Handles availableCameras method calls. // Enumerates video capture devices and // returns list of available camera devices. void AvailableCamerasMethodHandler( std::unique_ptr<flutter::MethodResult<>> result); // Handles create method calls. // Creates camera and initializes capture controller for requested device. // Stores result object to be handled after request is processed. void CreateMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); // Handles initialize method calls. // Requests existing camera controller to start preview. // Stores result object to be handled after request is processed. void InitializeMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); // Handles takePicture method calls. // Requests existing camera controller to take photo. // Stores result object to be handled after request is processed. void TakePictureMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); // Handles startVideoRecording method calls. // Requests existing camera controller to start recording. // Stores result object to be handled after request is processed. void StartVideoRecordingMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); // Handles stopVideoRecording method calls. // Requests existing camera controller to stop recording. // Stores result object to be handled after request is processed. void StopVideoRecordingMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); // Handles pausePreview method calls. // Requests existing camera controller to pause recording. // Stores result object to be handled after request is processed. void PausePreviewMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); // Handles resumePreview method calls. // Requests existing camera controller to resume preview. // Stores result object to be handled after request is processed. void ResumePreviewMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); // Handles dsipose method calls. // Disposes camera if exists. void DisposeMethodHandler(const EncodableMap& args, std::unique_ptr<MethodResult<>> result); std::unique_ptr<CameraFactory> camera_factory_; flutter::TextureRegistrar* texture_registrar_; flutter::BinaryMessenger* messenger_; std::vector<std::unique_ptr<Camera>> cameras_; friend class camera_windows::test::MockCameraPlugin; }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAMERA_PLUGIN_H_
coral-labs/plugins
packages/ios_platform_images/ios/Classes/UIImage+ios_platform_images.h
<reponame>coral-labs/plugins // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <UIKit/UIKit.h> @interface UIImage (ios_platform_images) /// Loads a UIImage from the embedded Flutter project's assets. /// /// This method loads the Flutter asset that is appropriate for the current /// screen. If you are on a 2x retina device where usually `UIImage` would be /// loading `@2x` assets, it will attempt to load the `2.0x` variant. It will /// load the standard image if it can't find the `2.0x` variant. /// /// For example, if your Flutter project's `pubspec.yaml` lists "assets/foo.png" /// and "assets/2.0x/foo.png", calling /// `[UIImage flutterImageWithName:@"assets/foo.png"]` will load /// "assets/2.0x/foo.png". /// /// See also https://flutter.dev/docs/development/ui/assets-and-images /// /// Note: We don't yet support images from package dependencies (ex. /// `AssetImage('icons/heart.png', package: 'my_icons')`). + (UIImage *)flutterImageWithName:(NSString *)name; @end
coral-labs/plugins
packages/file_selector/file_selector_windows/windows/file_selector_plugin.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_FILE_SELECTOR_PLUGIN_H_ #define PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_FILE_SELECTOR_PLUGIN_H_ #include <flutter/method_channel.h> #include <flutter/plugin_registrar_windows.h> #include <functional> #include "file_dialog_controller.h" namespace file_selector_windows { // Abstraction for accessing the Flutter view's root window, to allow for faking // in unit tests without creating fake window hierarchies, as well as to work // around https://github.com/flutter/flutter/issues/90694. using FlutterRootWindowProvider = std::function<HWND()>; class FileSelectorPlugin : public flutter::Plugin { public: static void RegisterWithRegistrar(flutter::PluginRegistrarWindows* registrar); // Creates a new plugin instance for the given registar, using the given // factory to create native dialog controllers. FileSelectorPlugin( FlutterRootWindowProvider window_provider, std::unique_ptr<FileDialogControllerFactory> dialog_controller_factory); virtual ~FileSelectorPlugin(); // Called when a method is called on plugin channel; void HandleMethodCall(const flutter::MethodCall<>& method_call, std::unique_ptr<flutter::MethodResult<>> result); private: // The provider for the root window to attach the dialog to. FlutterRootWindowProvider get_root_window_; // The factory for creating dialog controller instances. std::unique_ptr<FileDialogControllerFactory> controller_factory_; }; } // namespace file_selector_windows #endif // PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_FILE_SELECTOR_PLUGIN_H_
coral-labs/plugins
packages/camera/camera_windows/windows/texture_handler.h
<reponame>coral-labs/plugins // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_TEXTURE_HANDLER_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_TEXTURE_HANDLER_H_ #include <flutter/texture_registrar.h> #include <memory> #include <mutex> #include <string> namespace camera_windows { // Describes flutter desktop pixelbuffers pixel data order. struct FlutterDesktopPixel { uint8_t r = 0; uint8_t g = 0; uint8_t b = 0; uint8_t a = 0; }; // Describes MFVideoFormat_RGB32 data order. struct MFVideoFormatRGB32Pixel { uint8_t b = 0; uint8_t g = 0; uint8_t r = 0; uint8_t x = 0; }; // Handles the registration of Flutter textures, pixel buffers, and the // conversion of texture formats. class TextureHandler { public: TextureHandler(flutter::TextureRegistrar* texture_registrar) : texture_registrar_(texture_registrar) {} virtual ~TextureHandler(); // Prevent copying. TextureHandler(TextureHandler const&) = delete; TextureHandler& operator=(TextureHandler const&) = delete; // Updates source data buffer with given data. bool UpdateBuffer(uint8_t* data, uint32_t data_length); // Registers texture and updates given texture_id pointer value. int64_t RegisterTexture(); // Updates current preview texture size. void UpdateTextureSize(uint32_t width, uint32_t height) { preview_frame_width_ = width; preview_frame_height_ = height; } // Sets software mirror state. void SetMirrorPreviewState(bool mirror) { mirror_preview_ = mirror; } private: // Informs flutter texture registrar of updated texture. void OnBufferUpdated(); // Converts local pixel buffer to flutter pixel buffer. const FlutterDesktopPixelBuffer* ConvertPixelBufferForFlutter(size_t width, size_t height); // Checks if texture registrar, texture id and texture are available. bool TextureRegistered() { return texture_registrar_ && texture_ && texture_id_ > -1; } bool mirror_preview_ = true; int64_t texture_id_ = -1; uint32_t bytes_per_pixel_ = 4; uint32_t source_buffer_size_ = 0; uint32_t preview_frame_width_ = 0; uint32_t preview_frame_height_ = 0; std::vector<uint8_t> source_buffer_; std::vector<uint8_t> dest_buffer_; std::unique_ptr<flutter::TextureVariant> texture_; std::unique_ptr<FlutterDesktopPixelBuffer> flutter_desktop_pixel_buffer_ = nullptr; flutter::TextureRegistrar* texture_registrar_ = nullptr; std::mutex buffer_mutex_; }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_TEXTURE_HANDLER_H_
coral-labs/plugins
packages/file_selector/file_selector_windows/windows/test/test_utils.h
<gh_stars>1-10 // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_TEST_TEST_UTILS_H_ #define PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_TEST_TEST_UTILS_H_ #include <comdef.h> #include <comip.h> #include <shlobj.h> #include <shobjidl.h> #include <windows.h> #include <memory> #include <string> #include <type_traits> #include <variant> #include "file_dialog_controller.h" _COM_SMARTPTR_TYPEDEF(IShellItem, IID_IShellItem); _COM_SMARTPTR_TYPEDEF(IShellItemArray, IID_IShellItemArray); namespace file_selector_windows { namespace test { // Creates a temp file, managed as an IShellItem, which will be deleted when // the instance goes out of scope. // // This creates a file on the filesystem since creating IShellItem instances for // files that don't exist is non-trivial. class ScopedTestShellItem { public: ScopedTestShellItem(); ~ScopedTestShellItem(); // Disallow copy and assign. ScopedTestShellItem(const ScopedTestShellItem&) = delete; ScopedTestShellItem& operator=(const ScopedTestShellItem&) = delete; // Returns the file's IShellItem reference. IShellItemPtr file() { return item_; } // Returns the file's path. const std::wstring& path() { return path_; } private: IShellItemPtr item_; std::wstring path_; }; // Creates a temp file, managed as an ITEMIDLIST, which will be deleted when // the instance goes out of scope. // // This creates a file on the filesystem since creating IShellItem instances for // files that don't exist is non-trivial, and this is intended for use in // creating IShellItemArray instances. class ScopedTestFileIdList { public: ScopedTestFileIdList(); ~ScopedTestFileIdList(); // Disallow copy and assign. ScopedTestFileIdList(const ScopedTestFileIdList&) = delete; ScopedTestFileIdList& operator=(const ScopedTestFileIdList&) = delete; // Returns the file's ITEMIDLIST reference. PIDLIST_ABSOLUTE file() { return item_.get(); } // Returns the file's path. const std::wstring& path() { return path_; } private: // Smart pointer for managing ITEMIDLIST instances. struct ItemIdListDeleter { void operator()(LPITEMIDLIST item) { if (item) { ::ILFree(item); } } }; using ItemIdListPtr = std::unique_ptr<std::remove_pointer_t<PIDLIST_ABSOLUTE>, ItemIdListDeleter>; ItemIdListPtr item_; std::wstring path_; }; } // namespace test } // namespace file_selector_windows #endif // PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_TEST_TEST_UTILS_H_
coral-labs/plugins
packages/camera/camera_windows/windows/camera.h
<filename>packages/camera/camera_windows/windows/camera.h // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAMERA_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAMERA_H_ #include <flutter/method_channel.h> #include <flutter/standard_method_codec.h> #include <functional> #include "capture_controller.h" namespace camera_windows { using flutter::EncodableMap; using flutter::MethodChannel; using flutter::MethodResult; // A set of result types that are stored // for processing asynchronous commands. enum class PendingResultType { kCreateCamera, kInitialize, kTakePicture, kStartRecord, kStopRecord, kPausePreview, kResumePreview, }; // Interface implemented by cameras. // // Access is provided to an associated |CaptureController|, which can be used // to capture video or photo from the camera. class Camera : public CaptureControllerListener { public: explicit Camera(const std::string& device_id) {} virtual ~Camera() = default; // Disallow copy and move. Camera(const Camera&) = delete; Camera& operator=(const Camera&) = delete; // Tests if this camera has the specified device ID. virtual bool HasDeviceId(std::string& device_id) const = 0; // Tests if this camera has the specified camera ID. virtual bool HasCameraId(int64_t camera_id) const = 0; // Adds a pending result. // // Returns an error result if the result has already been added. virtual bool AddPendingResult(PendingResultType type, std::unique_ptr<MethodResult<>> result) = 0; // Checks if a pending result of the specified type already exists. virtual bool HasPendingResultByType(PendingResultType type) const = 0; // Returns a |CaptureController| that allows capturing video or still photos // from this camera. virtual camera_windows::CaptureController* GetCaptureController() = 0; // Initializes this camera and its associated capture controller. virtual void InitCamera(flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger, bool record_audio, ResolutionPreset resolution_preset) = 0; }; // Concrete implementation of the |Camera| interface. // // This implementation is responsible for initializing the capture controller, // listening for camera events, processing pending results, and notifying // application code of processed events via the method channel. class CameraImpl : public Camera { public: explicit CameraImpl(const std::string& device_id); virtual ~CameraImpl(); // Disallow copy and move. CameraImpl(const CameraImpl&) = delete; CameraImpl& operator=(const CameraImpl&) = delete; // CaptureControllerListener void OnCreateCaptureEngineSucceeded(int64_t texture_id) override; void OnCreateCaptureEngineFailed(const std::string& error) override; void OnStartPreviewSucceeded(int32_t width, int32_t height) override; void OnStartPreviewFailed(const std::string& error) override; void OnPausePreviewSucceeded() override; void OnPausePreviewFailed(const std::string& error) override; void OnResumePreviewSucceeded() override; void OnResumePreviewFailed(const std::string& error) override; void OnStartRecordSucceeded() override; void OnStartRecordFailed(const std::string& error) override; void OnStopRecordSucceeded(const std::string& file_path) override; void OnStopRecordFailed(const std::string& error) override; void OnTakePictureSucceeded(const std::string& file_path) override; void OnTakePictureFailed(const std::string& error) override; void OnVideoRecordSucceeded(const std::string& file_path, int64_t video_duration) override; void OnVideoRecordFailed(const std::string& error) override; void OnCaptureError(const std::string& error) override; // Camera bool HasDeviceId(std::string& device_id) const override { return device_id_ == device_id; } bool HasCameraId(int64_t camera_id) const override { return camera_id_ == camera_id; } bool AddPendingResult(PendingResultType type, std::unique_ptr<MethodResult<>> result) override; bool HasPendingResultByType(PendingResultType type) const override; camera_windows::CaptureController* GetCaptureController() override { return capture_controller_.get(); } void InitCamera(flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger, bool record_audio, ResolutionPreset resolution_preset) override; // Initializes the camera and its associated capture controller. // // This is a convenience method called by |InitCamera| but also used in // tests. void InitCamera( std::unique_ptr<CaptureControllerFactory> capture_controller_factory, flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger, bool record_audio, ResolutionPreset resolution_preset); private: // Loops through all pending results and calls their error handler with given // error ID and description. Pending results are cleared in the process. // // error_code: A string error code describing the error. // error_message: A user-readable error message (optional). void SendErrorForPendingResults(const std::string& error_code, const std::string& descripion); // Called when camera is disposed. // Sends camera closing message to the cameras method channel. void OnCameraClosing(); // Initializes method channel instance and returns pointer it. MethodChannel<>* GetMethodChannel(); // Finds pending result by type. // Returns nullptr if type is not present. std::unique_ptr<MethodResult<>> GetPendingResultByType( PendingResultType type); std::map<PendingResultType, std::unique_ptr<MethodResult<>>> pending_results_; std::unique_ptr<CaptureController> capture_controller_; std::unique_ptr<MethodChannel<>> camera_channel_; flutter::BinaryMessenger* messenger_ = nullptr; int64_t camera_id_ = -1; std::string device_id_; }; // Factory class for creating |Camera| instances from a specified device ID. class CameraFactory { public: CameraFactory() {} virtual ~CameraFactory() = default; // Disallow copy and move. CameraFactory(const CameraFactory&) = delete; CameraFactory& operator=(const CameraFactory&) = delete; // Creates camera for given device id. virtual std::unique_ptr<Camera> CreateCamera( const std::string& device_id) = 0; }; // Concrete implementation of |CameraFactory|. class CameraFactoryImpl : public CameraFactory { public: CameraFactoryImpl() {} virtual ~CameraFactoryImpl() = default; // Disallow copy and move. CameraFactoryImpl(const CameraFactoryImpl&) = delete; CameraFactoryImpl& operator=(const CameraFactoryImpl&) = delete; std::unique_ptr<Camera> CreateCamera(const std::string& device_id) override { return std::make_unique<CameraImpl>(device_id); } }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAMERA_H_
coral-labs/plugins
packages/camera/camera_windows/windows/com_heap_ptr.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_COMHEAPPTR_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_COMHEAPPTR_H_ #include <windows.h> #include <cassert> namespace camera_windows { // Wrapper for COM object for automatic memory release support // Destructor uses CoTaskMemFree to release memory allocations. template <typename T> class ComHeapPtr { public: ComHeapPtr() : p_obj_(nullptr) {} ComHeapPtr(T* p_obj) : p_obj_(p_obj) {} // Frees memory on destruction. ~ComHeapPtr() { Free(); } // Prevent copying / ownership transfer as not currently needed. ComHeapPtr(ComHeapPtr const&) = delete; ComHeapPtr& operator=(ComHeapPtr const&) = delete; // Returns the pointer to the memory. operator T*() { return p_obj_; } // Returns the pointer to the memory. T* operator->() { assert(p_obj_ != nullptr); return p_obj_; } // Returns the pointer to the memory. const T* operator->() const { assert(p_obj_ != nullptr); return p_obj_; } // Returns the pointer to the memory. T** operator&() { // Wrapped object must be nullptr to avoid memory leaks. // Object can be released with Reset(nullptr). assert(p_obj_ == nullptr); return &p_obj_; } // Frees the memory pointed to, and sets the pointer to nullptr. void Free() { if (p_obj_) { CoTaskMemFree(p_obj_); } p_obj_ = nullptr; } private: // Pointer to memory. T* p_obj_; }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_COMHEAPPTR_H_
coral-labs/plugins
packages/file_selector/file_selector_windows/windows/test/test_file_dialog_controller.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_TEST_TEST_FILE_DIALOG_CONTROLLER_H_ #define PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_TEST_TEST_FILE_DIALOG_CONTROLLER_H_ #include <comdef.h> #include <comip.h> #include <windows.h> #include <functional> #include <memory> #include <variant> #include <vector> #include "file_dialog_controller.h" #include "test/test_utils.h" _COM_SMARTPTR_TYPEDEF(IFileDialog, IID_IFileDialog); namespace file_selector_windows { namespace test { class TestFileDialogController; // A value to use for GetResult(s) in TestFileDialogController. The type depends // on whether the dialog is an open or save dialog. using MockShowResult = std::variant<std::monostate, IShellItemPtr, IShellItemArrayPtr>; // Called for TestFileDialogController::Show, to do validation and provide a // mock return value for GetResult(s). using MockShow = std::function<MockShowResult(const TestFileDialogController&, HWND)>; // A C++-friendly version of a COMDLG_FILTERSPEC. struct DialogFilter { std::wstring name; std::wstring spec; DialogFilter(const wchar_t* name, const wchar_t* spec) : name(name), spec(spec) {} }; // An extension of the normal file dialog controller that: // - Allows for inspection of set values. // - Allows faking the 'Show' interaction, providing tests an opportunity to // validate the dialog settings and provide a return value, via MockShow. class TestFileDialogController : public FileDialogController { public: TestFileDialogController(IFileDialog* dialog, MockShow mock_show); ~TestFileDialogController(); // FileDialogController: HRESULT SetFileTypes(UINT count, COMDLG_FILTERSPEC* filters) override; HRESULT SetOkButtonLabel(const wchar_t* text) override; HRESULT Show(HWND parent) override; HRESULT GetResult(IShellItem** out_item) const override; HRESULT GetResults(IShellItemArray** out_items) const override; // Accessors for validating IFileDialogController setter calls. std::wstring GetDefaultFolderPath() const; std::wstring GetFileName() const; const std::vector<DialogFilter>& GetFileTypes() const; std::wstring GetOkButtonLabel() const; private: IFileDialogPtr dialog_; MockShow mock_show_; MockShowResult mock_result_; // The last set values, for IFileDialog properties that have setters but no // corresponding getters. std::wstring ok_button_label_; std::vector<DialogFilter> filter_groups_; }; // A controller factory that vends TestFileDialogController instances. class TestFileDialogControllerFactory : public FileDialogControllerFactory { public: // Creates a factory whose instances use mock_show for the Show callback. TestFileDialogControllerFactory(MockShow mock_show); virtual ~TestFileDialogControllerFactory(); // Disallow copy and assign. TestFileDialogControllerFactory(const TestFileDialogControllerFactory&) = delete; TestFileDialogControllerFactory& operator=( const TestFileDialogControllerFactory&) = delete; // FileDialogControllerFactory: std::unique_ptr<FileDialogController> CreateController( IFileDialog* dialog) const override; private: MockShow mock_show_; }; } // namespace test } // namespace file_selector_windows #endif // PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_TEST_TEST_FILE_DIALOG_CONTROLLER_H_
coral-labs/plugins
packages/camera/camera_windows/windows/record_handler.h
<gh_stars>1-10 // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_RECORD_HANDLER_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_RECORD_HANDLER_H_ #include <mfapi.h> #include <mfcaptureengine.h> #include <wrl/client.h> #include <memory> #include <string> namespace camera_windows { using Microsoft::WRL::ComPtr; enum class RecordingType { // Recording continues until it is stopped with a separate stop command. kContinuous, // Recording stops automatically after requested record time is passed. kTimed }; // States that the record handler can be in. // // When created, the handler starts in |kNotStarted| state and transtions in // sequential order through the states. enum class RecordState { kNotStarted, kStarting, kRunning, kStopping }; // Handler for video recording via the camera. // // Handles record sink initialization and manages the state of video recording. class RecordHandler { public: RecordHandler(bool record_audio) : record_audio_(record_audio) {} virtual ~RecordHandler() = default; // Prevent copying. RecordHandler(RecordHandler const&) = delete; RecordHandler& operator=(RecordHandler const&) = delete; // Initializes record sink and requests capture engine to start recording. // // Sets record state to: starting. // Returns false if recording cannot be started. // // file_path: A string that hold file path for video capture. // max_duration: A int64 value of maximun recording duration. // If value is -1 video recording is considered as // a continuous recording. // capture_engine: A pointer to capture engine instance. Used to start // the actual recording. // base_media_type: A pointer to base media type used as a base // for the actual video capture media type. bool StartRecord(const std::string& file_path, int64_t max_duration, IMFCaptureEngine* capture_engine, IMFMediaType* base_media_type); // Stops existing recording. // Returns false if recording cannot be stopped. // // capture_engine: A pointer to capture engine instance. Used to stop // the ongoing recording. bool StopRecord(IMFCaptureEngine* capture_engine); // Set the record handler recording state to: running. void OnRecordStarted(); // Resets the record handler state and // sets recording state to: not started. void OnRecordStopped(); // Returns true if recording type is continuous recording. bool IsContinuousRecording() const { return type_ == RecordingType::kContinuous; } // Returns true if recording type is timed recording. bool IsTimedRecording() const { return type_ == RecordingType::kTimed; } // Returns true if new recording can be started. bool CanStart() const { return recording_state_ == RecordState::kNotStarted; } // Returns true if recording can be stopped. bool CanStop() const { return recording_state_ == RecordState::kRunning; } // Returns the filesystem path of the video recording. std::string GetRecordPath() const { return file_path_; } // Returns the duration of the video recording in microseconds. uint64_t GetRecordedDuration() const { return recording_duration_us_; } // Calculates new recording time from capture timestamp. void UpdateRecordingTime(uint64_t timestamp); // Returns true if recording time has exceeded the maximum duration for timed // recordings. bool ShouldStopTimedRecording() const; private: // Initializes record sink for video file capture. HRESULT InitRecordSink(IMFCaptureEngine* capture_engine, IMFMediaType* base_media_type); bool record_audio_ = false; int64_t max_video_duration_ms_ = -1; int64_t recording_start_timestamp_us_ = -1; uint64_t recording_duration_us_ = 0; std::string file_path_; RecordState recording_state_ = RecordState::kNotStarted; RecordingType type_; ComPtr<IMFCaptureRecordSink> record_sink_; }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_RECORD_HANDLER_H_
coral-labs/plugins
packages/camera/camera_windows/windows/photo_handler.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_PHOTO_HANDLER_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_PHOTO_HANDLER_H_ #include <mfapi.h> #include <mfcaptureengine.h> #include <wrl/client.h> #include <memory> #include <string> #include "capture_engine_listener.h" namespace camera_windows { using Microsoft::WRL::ComPtr; // Various states that the photo handler can be in. // // When created, the handler is in |kNotStarted| state and transtions in // sequential order through the states. enum class PhotoState { kNotStarted, kIdle, kTakingPhoto, }; // Handles photo sink initialization and tracks photo capture states. class PhotoHandler { public: PhotoHandler() {} virtual ~PhotoHandler() = default; // Prevent copying. PhotoHandler(PhotoHandler const&) = delete; PhotoHandler& operator=(PhotoHandler const&) = delete; // Initializes photo sink if not initialized and requests the capture engine // to take photo. // // Sets photo state to: kTakingPhoto. // Returns false if photo cannot be taken. // // capture_engine: A pointer to capture engine instance. // Called to take the photo. // base_media_type: A pointer to base media type used as a base // for the actual photo capture media type. // file_path: A string that hold file path for photo capture. bool TakePhoto(const std::string& file_path, IMFCaptureEngine* capture_engine, IMFMediaType* base_media_type); // Set the photo handler recording state to: kIdel. void OnPhotoTaken(); // Returns true if photo state is kIdle. bool IsInitialized() const { return photo_state_ == PhotoState::kIdle; } // Returns true if photo state is kTakingPhoto. bool IsTakingPhoto() const { return photo_state_ == PhotoState::kTakingPhoto; } // Returns the filesystem path of the captured photo. std::string GetPhotoPath() const { return file_path_; } private: // Initializes record sink for video file capture. HRESULT InitPhotoSink(IMFCaptureEngine* capture_engine, IMFMediaType* base_media_type); std::string file_path_; PhotoState photo_state_ = PhotoState::kNotStarted; ComPtr<IMFCapturePhotoSink> photo_sink_; }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_PHOTO_HANDLER_H_
coral-labs/plugins
packages/file_selector/file_selector_windows/windows/string_utils.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_STRING_UTILS_H_ #define PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_STRING_UTILS_H_ #include <shobjidl.h> #include <string> namespace file_selector_windows { // Converts the given UTF-16 string to UTF-8. std::string Utf8FromUtf16(const std::wstring& utf16_string); // Converts the given UTF-8 string to UTF-16. std::wstring Utf16FromUtf8(const std::string& utf8_string); } // namespace file_selector_windows #endif // PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_STRING_UTILS_H_
coral-labs/plugins
packages/camera/camera/ios/Classes/CameraProperties.h
<gh_stars>1-10 // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import AVFoundation; @import Foundation; NS_ASSUME_NONNULL_BEGIN #pragma mark - flash mode /** * Represents camera's flash mode. Mirrors `FlashMode` enum in flash_mode.dart. */ typedef NS_ENUM(NSInteger, FLTFlashMode) { FLTFlashModeOff, FLTFlashModeAuto, FLTFlashModeAlways, FLTFlashModeTorch, }; /** * Gets FLTFlashMode from its string representation. * @param mode a string representation of the FLTFlashMode. */ extern FLTFlashMode FLTGetFLTFlashModeForString(NSString *mode); /** * Gets AVCaptureFlashMode from FLTFlashMode. * @param mode flash mode. */ extern AVCaptureFlashMode FLTGetAVCaptureFlashModeForFLTFlashMode(FLTFlashMode mode); #pragma mark - exposure mode /** * Represents camera's exposure mode. Mirrors ExposureMode in camera.dart. */ typedef NS_ENUM(NSInteger, FLTExposureMode) { FLTExposureModeAuto, FLTExposureModeLocked, }; /** * Gets a string representation of exposure mode. * @param mode exposure mode */ extern NSString *FLTGetStringForFLTExposureMode(FLTExposureMode mode); /** * Gets FLTExposureMode from its string representation. * @param mode a string representation of the FLTExposureMode. */ extern FLTExposureMode FLTGetFLTExposureModeForString(NSString *mode); #pragma mark - focus mode /** * Represents camera's focus mode. Mirrors FocusMode in camera.dart. */ typedef NS_ENUM(NSInteger, FLTFocusMode) { FLTFocusModeAuto, FLTFocusModeLocked, }; /** * Gets a string representation from FLTFocusMode. * @param mode focus mode */ extern NSString *FLTGetStringForFLTFocusMode(FLTFocusMode mode); /** * Gets FLTFocusMode from its string representation. * @param mode a string representation of focus mode. */ extern FLTFocusMode FLTGetFLTFocusModeForString(NSString *mode); #pragma mark - device orientation /** * Gets UIDeviceOrientation from its string representation. */ extern UIDeviceOrientation FLTGetUIDeviceOrientationForString(NSString *orientation); /** * Gets a string representation of UIDeviceOrientation. */ extern NSString *FLTGetStringForUIDeviceOrientation(UIDeviceOrientation orientation); #pragma mark - resolution preset /** * Represents camera's resolution present. Mirrors ResolutionPreset in camera.dart. */ typedef NS_ENUM(NSInteger, FLTResolutionPreset) { FLTResolutionPresetVeryLow, FLTResolutionPresetLow, FLTResolutionPresetMedium, FLTResolutionPresetHigh, FLTResolutionPresetVeryHigh, FLTResolutionPresetUltraHigh, FLTResolutionPresetMax, }; /** * Gets FLTResolutionPreset from its string representation. * @param preset a string representation of FLTResolutionPreset. */ extern FLTResolutionPreset FLTGetFLTResolutionPresetForString(NSString *preset); #pragma mark - video format /** * Gets VideoFormat from its string representation. */ extern OSType FLTGetVideoFormatFromString(NSString *videoFormatString); NS_ASSUME_NONNULL_END
coral-labs/plugins
packages/camera/camera/ios/Classes/FLTThreadSafeTextureRegistry.h
<gh_stars>1-10 // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Flutter/Flutter.h> NS_ASSUME_NONNULL_BEGIN /** * A thread safe wrapper for FlutterTextureRegistry that can be called from any thread, by * dispatching its underlying engine calls to the main thread. */ @interface FLTThreadSafeTextureRegistry : NSObject /** * Creates a FLTThreadSafeTextureRegistry by wrapping an object conforming to * FlutterTextureRegistry. * @param registry The FlutterTextureRegistry object to be wrapped. */ - (instancetype)initWithTextureRegistry:(NSObject<FlutterTextureRegistry> *)registry; /** * Registers a `FlutterTexture` on the main thread for usage in Flutter and returns an id that can * be used to reference that texture when calling into Flutter with channels. * * On success the completion block completes with the pointer to the registered texture, else with * 0. The completion block runs on the main thread. */ - (void)registerTexture:(NSObject<FlutterTexture> *)texture completion:(void (^)(int64_t))completion; /** * Notifies the Flutter engine on the main thread that the given texture has been updated. */ - (void)textureFrameAvailable:(int64_t)textureId; /** * Notifies the Flutter engine on the main thread to unregister a `FlutterTexture` that has been * previously registered with `registerTexture:`. * @param textureId The result that was previously returned from `registerTexture:`. */ - (void)unregisterTexture:(int64_t)textureId; @end NS_ASSUME_NONNULL_END
coral-labs/plugins
packages/camera/camera/ios/Classes/FLTCam_Test.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FLTCam.h" // APIs exposed for unit testing. @interface FLTCam () @property(readonly, nonatomic) AVCaptureVideoDataOutput *captureVideoOutput; @end
coral-labs/plugins
packages/google_maps_flutter/google_maps_flutter/ios/Classes/JsonConversions.h
<filename>packages/google_maps_flutter/google_maps_flutter/ios/Classes/JsonConversions.h // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Flutter/Flutter.h> #import <GoogleMaps/GoogleMaps.h> @interface FLTGoogleMapJsonConversions : NSObject + (bool)toBool:(NSNumber *)data; + (int)toInt:(NSNumber *)data; + (double)toDouble:(NSNumber *)data; + (float)toFloat:(NSNumber *)data; + (CLLocationCoordinate2D)toLocation:(NSArray *)data; + (CGPoint)toPoint:(NSArray *)data; + (NSArray *)positionToJson:(CLLocationCoordinate2D)position; + (UIColor *)toColor:(NSNumber *)data; + (NSArray<CLLocation *> *)toPoints:(NSArray *)data; + (NSArray<NSArray<CLLocation *> *> *)toHoles:(NSArray *)data; @end
rgarcia87/automk
test-11-HER-vs-WR/09/itm.csv.c
<filename>test-11-HER-vs-WR/09/itm.csv.c label phase G mw ne frq note g0201 gas -0.2718000000 2.00 2 [] "Excess entropy added." g0101 gas 0.0000000000 1.00 0 [] "CHE Rossmeisl et al., pH=0" i0000 cat 0.0000000000 0.00 0 [] " " i0101 cat -0.1357950735 0.00 1 [] "PQC "
rgarcia87/automk
test-11-HER-vs-WR/09/rxn.csv.c
label is1 is2 fs1 fs2 G ad0201 g0201 i0000 i0101 i0101 -0.271800000 ad0101 g0101 i0000 i0101 None 0.000000000
zhibin-huang/xv6-labs-2020
user/primes.c
#include "kernel/types.h" #include "user/user.h" void prime(int pfd[]) { int p, n; int next_pfd[2]; if (read(pfd[0], &p, 4) != 0) { printf("prime %d\n", p); } else { close(pfd[0]); exit(0); } pipe(next_pfd); if (fork() == 0) { close(next_pfd[1]); prime(next_pfd); } else { close(next_pfd[0]); while (1) { if (read(pfd[0], &n, 4)) { if (n % p != 0) write(next_pfd[1], &n, 4); } else { close(next_pfd[1]); while (wait(0) != -1) ; exit(0); } } } } int main(int argc, char *argv[]) { int i, pfd[2]; pipe(pfd); if (fork() == 0) { close(pfd[1]); prime(pfd); } else { close(pfd[0]); for (i = 2; i <= 35; ++i) { write(pfd[1], &i, 4); } close(pfd[1]); } while (wait(0) != -1) ; exit(0); }
zhibin-huang/xv6-labs-2020
user/pingpong.c
<filename>user/pingpong.c #include "kernel/types.h" #include "user/user.h" int main(int argc, char *argv[]){ int p2c[2], c2p[2]; char msg[20]; pipe(p2c); pipe(c2p); if(fork() == 0){ close(p2c[1]); close(c2p[0]); read(p2c[0], msg ,14); printf("%d: %s\n", getpid(), msg); write(c2p[1], "received pong", 14); exit(0); } close(p2c[0]); close(c2p[1]); write(p2c[1], "received ping", 14); read(c2p[0], msg, 14); printf("%d: %s\n", getpid(), msg); exit(0); }
zhibin-huang/xv6-labs-2020
user/xargs.c
<filename>user/xargs.c #include "kernel/param.h" #include "kernel/types.h" #include "kernel/stat.h" #include "user/user.h" int main(int argc, char *argv[]) { char c; char buf[128]; char *c_argv[MAXARG]; if (argc < 2) { fprintf(2, "usage: xargs commend\n"); exit(0); } int i, j; for(i = 0; i < argc - 1; ++i){ c_argv[i] = argv[i + 1]; } c_argv[i] = buf; j = 0; while (read(0, &c, 1)) { if (c == '\n') { buf[j] = 0; c_argv[i + 1] = 0; if (fork() == 0) { exec(argv[1], c_argv); } else { i = argc - 1, j = 0; wait(0); } } else { if (c == ' ') { buf[j] = 0; } else { if (buf[j] == 0) c_argv[++i] = &buf[++j]; buf[j++] = c; } } } exit(0); }
mekala-yogitha/right-angled-triangle
pattern.c
<gh_stars>0 #include<stdio.h> int main() { int i, j, rows; int count = 1; printf("Enter the number of rows\n"); scanf("%d", &rows); for (i = 0; i < rows; i++) { for (j = 0; j <= i; j++) { printf("%d ", count); count = !count; } count = i % 2; printf("\n"); } return(0); }
borjaIgartua/BIAddressBook
AddressBookExample/Contact.h
<filename>AddressBookExample/Contact.h // // Contact.h // AddressBookExample // // Created by Borja on 20/2/16. // Copyright © 2016 Borja. All rights reserved. // #import <Foundation/Foundation.h> @interface Contact : NSObject - (instancetype)initWithName:(NSString *)name lastname:(NSString *)lasname imageData:(NSData *)imageData recordID:(NSInteger)recordID telephones:(NSArray *)telephones; @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *lastname; @property (nonatomic, strong) NSData *imageData; @property (nonatomic, assign) NSInteger recordID; @property (nonatomic, strong) NSArray *telephones; @end
borjaIgartua/BIAddressBook
BIAddressBook/BIAddressBook.h
// // AddressBookTool.h // AddressBookExample // // Created by Borja on 20/2/16. // Copyright © 2016 Borja. All rights reserved. // #import <Foundation/Foundation.h> @interface BIAddressBook : NSObject /** * Read all the agenda contacts * * @param completionHandler. The block called when the contacs are read */ - (void)readAllContactsCompletion:(void (^)(NSArray *contacts, BOOL permissionsGranted))completionHandler; @end
juiceleee/DeepCache
src/mrect.h
<filename>src/mrect.h #ifndef NCNN_MRECT_H #define NCNN_MRECT_H #if NCNN_CNNCACHE namespace ncnn { #if NCNN_CNNCACHE #include <android/log.h> #endif #define LOG_TAG "NCNN_CNNCache" #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__) #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) struct timeval tv_begin, tv_end; inline void log_time_begin() { gettimeofday(&tv_begin, NULL); } inline void log_time_end(char* str) { static int LOG_TIME_CNT = 0; if (strcmp("__reset", str) == 0) { // This is ugly, better to use extern LOG_TIME_CNT = 0; return; } gettimeofday(&tv_end, NULL); int elapsed = ((tv_end.tv_sec - tv_begin.tv_sec) * 1000000.0f + tv_end.tv_usec - tv_begin.tv_usec) / 1000.0f; LOGI("[%d-%s]\telapsed: %dms", LOG_TIME_CNT, str, elapsed); LOG_TIME_CNT ++; } inline bool skip_reuse(bool* cached_map, int outw, int outh) { int changed_pixel = 0; for (int i = 0; i < outw * outh; i ++) { changed_pixel += cached_map[i] ? 1 : 0; } float ratio = 1.0 * changed_pixel / outw / outh; if (ratio > 0.8) return true; else return false; } struct rect{ int x1; int y1; int x2; int y2; rect(int arg0, int arg1,int arg2, int arg3) { x1 = arg0; y1 = arg1; x2 = arg2; y2 = arg3; } rect() {} }; class MRect { public: MRect() {} void set_offset(int x, int y) { x_offset = x; y_offset = y; } void add_rect(int arg0, int arg1, int arg2, int arg3) { changed_vecs.push_back(rect(arg0, arg1, arg2, arg3)); } void copyFrom(MRect other) { x_offset = other.x_offset; y_offset = other.y_offset; changed_vecs.resize(0); for (struct rect r: other.changed_vecs) { this->changed_vecs.push_back(r); } } std::string info() { std::string ret(""); char a[64]; for (unsigned i = 0; i < changed_vecs.size(); i ++) { if (i > 0) ret += ", "; struct rect r1 = changed_vecs[i]; sprintf(a, "(%d,%d,%d,%d)", r1.x1, r1.y1, r1.x2, r1.y2); ret += a; } return ret; } int size() { return changed_vecs.size(); } void forward_rect_conv_or_pool( struct rect& r1, struct rect& r2, int pad, int ksize, int stride) { // TODO: not correct yet // int off = stride > 1 ? 1 : 0; if (pad >= 0) { // SAME r1.x1 = std::max(0, (r2.x1 - ksize / 2) / stride); r1.y1 = std::max(0, (r2.y1 - ksize / 2) / stride); r1.x2 = (r2.x2 + ksize / 2) / stride; r1.y2 = (r2.y2 + ksize / 2) / stride; } else if (pad == -233) { // VALID r1.x1 = std::max(0, (r2.x1 - ksize / 2) / stride); r1.y1 = std::max(0, (r2.y1 - ksize / 2) / stride); r1.x2 = (r2.x2 + ksize / 2) / stride; r1.y2 = (r2.y2 + ksize / 2) / stride; } // LOGI("Yes (%d,%d,%d,%d) -> (%d,%d,%d,%d)\n", // r2.x1, r2.y1, r2.x2, r2.y2, r1.x1, r1.y1, r1.x2, r1.y2); } int forward_in_conv_or_pool(MRect& bottom_mrect, int pad, int ksize, int stride) { // offset x_offset = bottom_mrect.x_offset / stride; y_offset = bottom_mrect.y_offset / stride; size_t size = bottom_mrect.size(); changed_vecs.resize(size); for (size_t i = 0; i < size; i ++) { forward_rect_conv_or_pool( changed_vecs[i], bottom_mrect.changed_vecs[i], pad, ksize, stride); } return 0; } int x_offset; int y_offset; std::vector<struct rect> changed_vecs; }; } // namespace ncnn #endif // NCNN_CNNCACHE #endif // NCNN_MRECT_H
juiceleee/DeepCache
src/layer/arm/convolution_3x3.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #if __ARM_NEON #include <arm_neon.h> #endif // __ARM_NEON static void conv3x3s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); const float* kernel0 = kernel + p*inch*9; for (int q=0; q<inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* r3 = img0 + w*3; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(kernel0); float32x4_t _k3456 = vld1q_f32(kernel0+3); float32x4_t _k6789 = vld1q_f32(kernel0+6); #endif // __ARM_NEON int i = 0; for (; i+1 < outh; i+=2) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _sum1 = vld1q_f32(outptr); float32x4_t _sum2 = vdupq_n_f32(0.f); float32x4_t _sum3 = vld1q_f32(outptr2); float32x4_t _sum4 = vdupq_n_f32(0.f); float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r00n = vld1q_f32(r0 + 4); float32x4_t _r01 = vextq_f32(_r00, _r00n, 1); float32x4_t _r02 = vextq_f32(_r00, _r00n, 2); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r10n = vld1q_f32(r1 + 4); float32x4_t _r11 = vextq_f32(_r10, _r10n, 1); float32x4_t _r12 = vextq_f32(_r10, _r10n, 2); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r20n = vld1q_f32(r2 + 4); float32x4_t _r21 = vextq_f32(_r20, _r20n, 1); float32x4_t _r22 = vextq_f32(_r20, _r20n, 2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _r30n = vld1q_f32(r3 + 4); float32x4_t _r31 = vextq_f32(_r30, _r30n, 1); float32x4_t _r32 = vextq_f32(_r30, _r30n, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r00, _k0123, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r01, _k0123, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r02, _k0123, 2); _sum2 = vfmaq_laneq_f32(_sum2, _r10, _k3456, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r11, _k3456, 1); _sum2 = vfmaq_laneq_f32(_sum2, _r12, _k3456, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r20, _k6789, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r21, _k6789, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r22, _k6789, 2); _sum3 = vfmaq_laneq_f32(_sum3, _r10, _k0123, 0); _sum4 = vfmaq_laneq_f32(_sum4, _r11, _k0123, 1); _sum3 = vfmaq_laneq_f32(_sum3, _r12, _k0123, 2); _sum4 = vfmaq_laneq_f32(_sum4, _r20, _k3456, 0); _sum3 = vfmaq_laneq_f32(_sum3, _r21, _k3456, 1); _sum4 = vfmaq_laneq_f32(_sum4, _r22, _k3456, 2); _sum3 = vfmaq_laneq_f32(_sum3, _r30, _k6789, 0); _sum4 = vfmaq_laneq_f32(_sum4, _r31, _k6789, 1); _sum3 = vfmaq_laneq_f32(_sum3, _r32, _k6789, 2); _sum1 = vaddq_f32(_sum1, _sum2); _sum3 = vaddq_f32(_sum3, _sum4); vst1q_f32(outptr, _sum1); vst1q_f32(outptr2, _sum3); r0 += 4; r1 += 4; r2 += 4; r3 += 4; outptr += 4; outptr2 += 4; } #else if (nn > 0) { asm volatile( "veor q6, q6 \n" "veor q15, q15 \n" "pld [%3, #192] \n" "vld1.f32 {d18-d20}, [%3 :64] \n"// r0 "add %3, #16 \n" "veor q13, q13 \n" "veor q14, q14 \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1 :64] \n"// _sum "vmla.f32 q7, q9, %e14[0] \n" "vmla.f32 q6, q11, %e14[1] \n" "vmla.f32 q13, q12, %f14[0] \n" "pld [%4, #192] \n" "vld1.f32 {d18-d20}, [%4] \n"// r1 "add %4, #16 \n" "vmla.f32 q7, q9, %e15[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q6, q11, %e15[1] \n" "vmla.f32 q13, q12, %f15[0] \n" "pld [%2, #128] \n" "vld1.f32 {d16-d17}, [%2] \n"// _sum2 "vmla.f32 q8, q9, %e14[0] \n" "vmla.f32 q14, q11, %e14[1] \n" "vmla.f32 q15, q12, %f14[0] \n" "pld [%5, #192] \n" "vld1.f32 {d18-d20}, [%5 :64] \n"// r2 "add %5, #16 \n" "vmla.f32 q7, q9, %e16[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q6, q11, %e16[1] \n" "vmla.f32 q13, q12, %f16[0] \n" "vmla.f32 q8, q9, %e15[0] \n" "vmla.f32 q14, q11, %e15[1] \n" "vmla.f32 q15, q12, %f15[0] \n" "pld [%6, #192] \n" "vld1.f32 {d18-d20}, [%6] \n"// r3 "add %6, #16 \n" "vmla.f32 q8, q9, %e16[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q14, q11, %e16[1] \n" "vmla.f32 q15, q12, %f16[0] \n" "vadd.f32 q7, q7, q6 \n" "veor q6, q6 \n" "pld [%3, #192] \n" "vld1.f32 {d18-d20}, [%3 :64] \n"// r0 "vadd.f32 q8, q8, q14 \n" "veor q14, q14 \n" "vadd.f32 q7, q7, q13 \n" "veor q13, q13 \n" "vadd.f32 q8, q8, q15 \n" "veor q15, q15 \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "add %3, #16 \n" "vst1.f32 {d14-d15}, [%1]! \n" "vst1.f32 {d16-d17}, [%2]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %3, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(outptr2), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3) // %6 : "0"(nn), "1"(outptr), "2"(outptr2), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "w"(_k0123), // %14 "w"(_k3456), // %15 "w"(_k6789) // %16 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); float32x4_t _sum2 = vmulq_f32(_r10, _k0123); _sum2 = vmlaq_f32(_sum2, _r20, _k3456); _sum2 = vmlaq_f32(_sum2, _r30, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); _sum2 = vsetq_lane_f32(*outptr2, _sum2, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); *outptr2 = vaddvq_f32(_sum2); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); float32x2_t _ss2 = vadd_f32(vget_low_f32(_sum2), vget_high_f32(_sum2)); float32x2_t _sss2 = vpadd_f32(_ss, _ss2); *outptr = vget_lane_f32(_sss2, 0); *outptr2 = vget_lane_f32(_sss2, 1); #endif // __aarch64__ #else float sum = 0; float sum2 = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; *outptr += sum; *outptr2 += sum2; #endif r0++; r1++; r2++; r3++; outptr++; outptr2++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _sum1 = vld1q_f32(outptr); float32x4_t _sum2 = vdupq_n_f32(0.f); float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r00n = vld1q_f32(r0 + 4); float32x4_t _r01 = vextq_f32(_r00, _r00n, 1); float32x4_t _r02 = vextq_f32(_r00, _r00n, 2); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r10n = vld1q_f32(r1 + 4); float32x4_t _r11 = vextq_f32(_r10, _r10n, 1); float32x4_t _r12 = vextq_f32(_r10, _r10n, 2); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r20n = vld1q_f32(r2 + 4); float32x4_t _r21 = vextq_f32(_r20, _r20n, 1); float32x4_t _r22 = vextq_f32(_r20, _r20n, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r00, _k0123, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r01, _k0123, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r02, _k0123, 2); _sum2 = vfmaq_laneq_f32(_sum2, _r10, _k3456, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r11, _k3456, 1); _sum2 = vfmaq_laneq_f32(_sum2, _r12, _k3456, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r20, _k6789, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r21, _k6789, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r22, _k6789, 2); _sum1 = vaddq_f32(_sum1, _sum2); vst1q_f32(outptr, _sum1); r0 += 4; r1 += 4; r2 += 4; outptr += 4; } #else if (nn > 0) { asm volatile( "pld [%2, #192] \n" "vld1.f32 {d16-d18}, [%2] \n"// r0 "add %2, #16 \n" "veor q13, q13 \n" "veor q14, q14 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1] \n"// _sum "vmla.f32 q7, q8, %e10[0] \n" "vmla.f32 q13, q10, %e10[1] \n" "vmla.f32 q14, q11, %f10[0] \n" "pld [%3, #192] \n" "vld1.f32 {d16-d18}, [%3] \n"// r1 "add %3, #16 \n" "vmla.f32 q7, q8, %e11[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q13, q10, %e11[1] \n" "vmla.f32 q14, q11, %f11[0] \n" "pld [%4, #192] \n" "vld1.f32 {d16-d18}, [%4] \n"// r2 "add %4, #16 \n" "vmla.f32 q7, q8, %e12[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q13, q10, %e12[1] \n" "vmla.f32 q14, q11, %f12[0] \n" "pld [%2, #192] \n" "vld1.f32 {d16-d18}, [%2] \n"// r0 "add %2, #16 \n" "vadd.f32 q7, q7, q13 \n" "veor q13, q13 \n" "vadd.f32 q7, q7, q14 \n" "veor q14, q14 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vst1.f32 {d14-d15}, [%1]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %2, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; #endif r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } kernel0 += 9; } } } static void conv3x3s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); const float* kernel0 = kernel + p*inch*9; for (int q=0; q<inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(k0); float32x4_t _k3456 = vld1q_f32(k1); float32x4_t _k6789 = vld1q_f32(k2); #endif // __ARM_NEON int i = 0; for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _outp = vld1q_f32(outptr); float32x4x2_t _r0 = vld2q_f32(r0); float32x4x2_t _r0n = vld2q_f32(r0+8); float32x4_t _r00 = _r0.val[0];// 0 2 4 6 float32x4_t _r01 = _r0.val[1];// 1 3 5 7 float32x4_t _r02 = vextq_f32(_r00, _r0n.val[0], 1);// 2 4 6 8 _outp = vfmaq_laneq_f32(_outp, _r00, _k0123, 0); _outp = vfmaq_laneq_f32(_outp, _r01, _k0123, 1); _outp = vfmaq_laneq_f32(_outp, _r02, _k0123, 2); float32x4x2_t _r1 = vld2q_f32(r1); float32x4x2_t _r1n = vld2q_f32(r1+8); float32x4_t _r10 = _r1.val[0]; float32x4_t _r11 = _r1.val[1]; float32x4_t _r12 = vextq_f32(_r10, _r1n.val[0], 1); _outp = vfmaq_laneq_f32(_outp, _r10, _k3456, 0); _outp = vfmaq_laneq_f32(_outp, _r11, _k3456, 1); _outp = vfmaq_laneq_f32(_outp, _r12, _k3456, 2); float32x4x2_t _r2 = vld2q_f32(r2); float32x4x2_t _r2n = vld2q_f32(r2+8); float32x4_t _r20 = _r2.val[0]; float32x4_t _r21 = _r2.val[1]; float32x4_t _r22 = vextq_f32(_r20, _r2n.val[0], 1); _outp = vfmaq_laneq_f32(_outp, _r20, _k6789, 0); _outp = vfmaq_laneq_f32(_outp, _r21, _k6789, 1); _outp = vfmaq_laneq_f32(_outp, _r22, _k6789, 2); vst1q_f32(outptr, _outp); r0 += 8; r1 += 8; r2 += 8; outptr += 4; } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "veor q10, q10 \n" "veor q11, q11 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d0-d1}, [%1] \n" "vmla.f32 q0, q2, %e10[0] \n" "vmla.f32 q10, q3, %e10[1] \n" "pld [%2, #256] \n" "vld2.f32 {d16-d19}, [%2] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f10[0] \n" "pld [%3, #256] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vmla.f32 q0, q2, %e11[0] \n" "vmla.f32 q10, q3, %e11[1] \n" "pld [%3, #256] \n" "vld2.f32 {d16-d19}, [%3] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f11[0] \n" "pld [%4, #256] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vmla.f32 q0, q2, %e12[0] \n" "vmla.f32 q10, q3, %e12[1] \n" "pld [%4, #256] \n" "vld2.f32 {d16-d19}, [%4] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f12[0] \n" "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vadd.f32 q0, q0, q10 \n" "veor q10, q10 \n" "vadd.f32 q0, q0, q11 \n" "veor q11, q11 \n" "subs %0, #1 \n" "vst1.f32 {d0-d1}, [%1]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), "=r"(r2) : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; #endif // __ARM_NEON r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } kernel0 += 9; } } } #if NCNN_CNNCACHE static void conv3x3s1_neon_cached( const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, bool* cached_map) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; // const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); // const float bias0 = bias ? bias[p] : 0.f; // out.fill(bias0); const float* kernel0 = kernel + p*inch*9; for (int q=0; q<inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* r3 = img0 + w*3; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(kernel0); float32x4_t _k3456 = vld1q_f32(kernel0+3); float32x4_t _k6789 = vld1q_f32(kernel0+6); #endif // __ARM_NEON int i = 0; for (; i+1 < outh; i+=2) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _sum1 = vld1q_f32(outptr); float32x4_t _sum2 = vdupq_n_f32(0.f); float32x4_t _sum3 = vld1q_f32(outptr2); float32x4_t _sum4 = vdupq_n_f32(0.f); float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r00n = vld1q_f32(r0 + 4); float32x4_t _r01 = vextq_f32(_r00, _r00n, 1); float32x4_t _r02 = vextq_f32(_r00, _r00n, 2); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r10n = vld1q_f32(r1 + 4); float32x4_t _r11 = vextq_f32(_r10, _r10n, 1); float32x4_t _r12 = vextq_f32(_r10, _r10n, 2); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r20n = vld1q_f32(r2 + 4); float32x4_t _r21 = vextq_f32(_r20, _r20n, 1); float32x4_t _r22 = vextq_f32(_r20, _r20n, 2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _r30n = vld1q_f32(r3 + 4); float32x4_t _r31 = vextq_f32(_r30, _r30n, 1); float32x4_t _r32 = vextq_f32(_r30, _r30n, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r00, _k0123, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r01, _k0123, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r02, _k0123, 2); _sum2 = vfmaq_laneq_f32(_sum2, _r10, _k3456, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r11, _k3456, 1); _sum2 = vfmaq_laneq_f32(_sum2, _r12, _k3456, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r20, _k6789, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r21, _k6789, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r22, _k6789, 2); _sum3 = vfmaq_laneq_f32(_sum3, _r10, _k0123, 0); _sum4 = vfmaq_laneq_f32(_sum4, _r11, _k0123, 1); _sum3 = vfmaq_laneq_f32(_sum3, _r12, _k0123, 2); _sum4 = vfmaq_laneq_f32(_sum4, _r20, _k3456, 0); _sum3 = vfmaq_laneq_f32(_sum3, _r21, _k3456, 1); _sum4 = vfmaq_laneq_f32(_sum4, _r22, _k3456, 2); _sum3 = vfmaq_laneq_f32(_sum3, _r30, _k6789, 0); _sum4 = vfmaq_laneq_f32(_sum4, _r31, _k6789, 1); _sum3 = vfmaq_laneq_f32(_sum3, _r32, _k6789, 2); _sum1 = vaddq_f32(_sum1, _sum2); _sum3 = vaddq_f32(_sum3, _sum4); vst1q_f32(outptr, _sum1); vst1q_f32(outptr2, _sum3); r0 += 4; r1 += 4; r2 += 4; r3 += 4; outptr += 4; outptr2 += 4; } #else if (nn > 0) { asm volatile( "veor q6, q6 \n" "veor q15, q15 \n" "pld [%3, #192] \n" "vld1.f32 {d18-d20}, [%3 :64] \n"// r0 "add %3, #16 \n" "veor q13, q13 \n" "veor q14, q14 \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1 :64] \n"// _sum "vmla.f32 q7, q9, %e14[0] \n" "vmla.f32 q6, q11, %e14[1] \n" "vmla.f32 q13, q12, %f14[0] \n" "pld [%4, #192] \n" "vld1.f32 {d18-d20}, [%4] \n"// r1 "add %4, #16 \n" "vmla.f32 q7, q9, %e15[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q6, q11, %e15[1] \n" "vmla.f32 q13, q12, %f15[0] \n" "pld [%2, #128] \n" "vld1.f32 {d16-d17}, [%2] \n"// _sum2 "vmla.f32 q8, q9, %e14[0] \n" "vmla.f32 q14, q11, %e14[1] \n" "vmla.f32 q15, q12, %f14[0] \n" "pld [%5, #192] \n" "vld1.f32 {d18-d20}, [%5 :64] \n"// r2 "add %5, #16 \n" "vmla.f32 q7, q9, %e16[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q6, q11, %e16[1] \n" "vmla.f32 q13, q12, %f16[0] \n" "vmla.f32 q8, q9, %e15[0] \n" "vmla.f32 q14, q11, %e15[1] \n" "vmla.f32 q15, q12, %f15[0] \n" "pld [%6, #192] \n" "vld1.f32 {d18-d20}, [%6] \n"// r3 "add %6, #16 \n" "vmla.f32 q8, q9, %e16[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q14, q11, %e16[1] \n" "vmla.f32 q15, q12, %f16[0] \n" "vadd.f32 q7, q7, q6 \n" "veor q6, q6 \n" "pld [%3, #192] \n" "vld1.f32 {d18-d20}, [%3 :64] \n"// r0 "vadd.f32 q8, q8, q14 \n" "veor q14, q14 \n" "vadd.f32 q7, q7, q13 \n" "veor q13, q13 \n" "vadd.f32 q8, q8, q15 \n" "veor q15, q15 \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "add %3, #16 \n" "vst1.f32 {d14-d15}, [%1]! \n" "vst1.f32 {d16-d17}, [%2]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %3, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(outptr2), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3) // %6 : "0"(nn), "1"(outptr), "2"(outptr2), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "w"(_k0123), // %14 "w"(_k3456), // %15 "w"(_k6789) // %16 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); float32x4_t _sum2 = vmulq_f32(_r10, _k0123); _sum2 = vmlaq_f32(_sum2, _r20, _k3456); _sum2 = vmlaq_f32(_sum2, _r30, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); _sum2 = vsetq_lane_f32(*outptr2, _sum2, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); *outptr2 = vaddvq_f32(_sum2); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); float32x2_t _ss2 = vadd_f32(vget_low_f32(_sum2), vget_high_f32(_sum2)); float32x2_t _sss2 = vpadd_f32(_ss, _ss2); *outptr = vget_lane_f32(_sss2, 0); *outptr2 = vget_lane_f32(_sss2, 1); #endif // __aarch64__ #else if (cached_map[outptr - out]) { float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; } if (cached_map[outptr2 - out]) { float sum2 = 0; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; *outptr2 += sum2; } #endif r0++; r1++; r2++; r3++; outptr++; outptr2++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _sum1 = vld1q_f32(outptr); float32x4_t _sum2 = vdupq_n_f32(0.f); float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r00n = vld1q_f32(r0 + 4); float32x4_t _r01 = vextq_f32(_r00, _r00n, 1); float32x4_t _r02 = vextq_f32(_r00, _r00n, 2); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r10n = vld1q_f32(r1 + 4); float32x4_t _r11 = vextq_f32(_r10, _r10n, 1); float32x4_t _r12 = vextq_f32(_r10, _r10n, 2); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r20n = vld1q_f32(r2 + 4); float32x4_t _r21 = vextq_f32(_r20, _r20n, 1); float32x4_t _r22 = vextq_f32(_r20, _r20n, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r00, _k0123, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r01, _k0123, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r02, _k0123, 2); _sum2 = vfmaq_laneq_f32(_sum2, _r10, _k3456, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r11, _k3456, 1); _sum2 = vfmaq_laneq_f32(_sum2, _r12, _k3456, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r20, _k6789, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r21, _k6789, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r22, _k6789, 2); _sum1 = vaddq_f32(_sum1, _sum2); vst1q_f32(outptr, _sum1); r0 += 4; r1 += 4; r2 += 4; outptr += 4; } #else if (nn > 0) { asm volatile( "pld [%2, #192] \n" "vld1.f32 {d16-d18}, [%2] \n"// r0 "add %2, #16 \n" "veor q13, q13 \n" "veor q14, q14 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1] \n"// _sum "vmla.f32 q7, q8, %e10[0] \n" "vmla.f32 q13, q10, %e10[1] \n" "vmla.f32 q14, q11, %f10[0] \n" "pld [%3, #192] \n" "vld1.f32 {d16-d18}, [%3] \n"// r1 "add %3, #16 \n" "vmla.f32 q7, q8, %e11[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q13, q10, %e11[1] \n" "vmla.f32 q14, q11, %f11[0] \n" "pld [%4, #192] \n" "vld1.f32 {d16-d18}, [%4] \n"// r2 "add %4, #16 \n" "vmla.f32 q7, q8, %e12[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q13, q10, %e12[1] \n" "vmla.f32 q14, q11, %f12[0] \n" "pld [%2, #192] \n" "vld1.f32 {d16-d18}, [%2] \n"// r0 "add %2, #16 \n" "vadd.f32 q7, q7, q13 \n" "veor q13, q13 \n" "vadd.f32 q7, q7, q14 \n" "veor q14, q14 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vst1.f32 {d14-d15}, [%1]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %2, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else if (cached_map[outptr - out]) { float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; } #endif r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } kernel0 += 9; } } } static void conv3x3s2_neon_cached( const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, bool* cached_map) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; // const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); // const float bias0 = bias ? bias[p] : 0.f; // out.fill(bias0); const float* kernel0 = kernel + p*inch*9; for (int q=0; q<inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(k0); float32x4_t _k3456 = vld1q_f32(k1); float32x4_t _k6789 = vld1q_f32(k2); #endif // __ARM_NEON int i = 0; for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _outp = vld1q_f32(outptr); float32x4x2_t _r0 = vld2q_f32(r0); float32x4x2_t _r0n = vld2q_f32(r0+8); float32x4_t _r00 = _r0.val[0];// 0 2 4 6 float32x4_t _r01 = _r0.val[1];// 1 3 5 7 float32x4_t _r02 = vextq_f32(_r00, _r0n.val[0], 1);// 2 4 6 8 _outp = vfmaq_laneq_f32(_outp, _r00, _k0123, 0); _outp = vfmaq_laneq_f32(_outp, _r01, _k0123, 1); _outp = vfmaq_laneq_f32(_outp, _r02, _k0123, 2); float32x4x2_t _r1 = vld2q_f32(r1); float32x4x2_t _r1n = vld2q_f32(r1+8); float32x4_t _r10 = _r1.val[0]; float32x4_t _r11 = _r1.val[1]; float32x4_t _r12 = vextq_f32(_r10, _r1n.val[0], 1); _outp = vfmaq_laneq_f32(_outp, _r10, _k3456, 0); _outp = vfmaq_laneq_f32(_outp, _r11, _k3456, 1); _outp = vfmaq_laneq_f32(_outp, _r12, _k3456, 2); float32x4x2_t _r2 = vld2q_f32(r2); float32x4x2_t _r2n = vld2q_f32(r2+8); float32x4_t _r20 = _r2.val[0]; float32x4_t _r21 = _r2.val[1]; float32x4_t _r22 = vextq_f32(_r20, _r2n.val[0], 1); _outp = vfmaq_laneq_f32(_outp, _r20, _k6789, 0); _outp = vfmaq_laneq_f32(_outp, _r21, _k6789, 1); _outp = vfmaq_laneq_f32(_outp, _r22, _k6789, 2); vst1q_f32(outptr, _outp); r0 += 8; r1 += 8; r2 += 8; outptr += 4; } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "veor q10, q10 \n" "veor q11, q11 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d0-d1}, [%1] \n" "vmla.f32 q0, q2, %e10[0] \n" "vmla.f32 q10, q3, %e10[1] \n" "pld [%2, #256] \n" "vld2.f32 {d16-d19}, [%2] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f10[0] \n" "pld [%3, #256] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vmla.f32 q0, q2, %e11[0] \n" "vmla.f32 q10, q3, %e11[1] \n" "pld [%3, #256] \n" "vld2.f32 {d16-d19}, [%3] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f11[0] \n" "pld [%4, #256] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vmla.f32 q0, q2, %e12[0] \n" "vmla.f32 q10, q3, %e12[1] \n" "pld [%4, #256] \n" "vld2.f32 {d16-d19}, [%4] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f12[0] \n" "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vadd.f32 q0, q0, q10 \n" "veor q10, q10 \n" "vadd.f32 q0, q0, q11 \n" "veor q11, q11 \n" "subs %0, #1 \n" "vst1.f32 {d0-d1}, [%1]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), "=r"(r2) : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; #endif // __ARM_NEON r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } kernel0 += 9; } } } #endif // NCNN_CNNCACHE
SergeyNewcastle/draco
src/draco/compression/attributes/mesh_traversal_sequencer.h
// Copyright 2016 The Draco Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef DRACO_COMPRESSION_ATTRIBUTES_MESH_TRAVERSAL_SEQUENCER_H_ #define DRACO_COMPRESSION_ATTRIBUTES_MESH_TRAVERSAL_SEQUENCER_H_ #include "draco/attributes/geometry_indices.h" #include "draco/compression/attributes/mesh_attribute_indices_encoding_data.h" #include "draco/compression/attributes/points_sequencer.h" #include "draco/mesh/mesh.h" namespace draco { // Sequencer that generates point sequence in an order given by a deterministic // traversal on the mesh surface. Note that all attributes encoded with this // sequence must share the same connectivity. template <class TraverserT> class MeshTraversalSequencer : public PointsSequencer { public: MeshTraversalSequencer(const Mesh *mesh, const MeshAttributeIndicesEncodingData *encoding_data) : mesh_(mesh), encoding_data_(encoding_data), corner_order_(nullptr) {} void SetTraverser(const TraverserT &t) { traverser_ = t; } // Function that can be used to set an order in which the mesh corners should // be processed. This is an optional flag used usually only by the encoder // to match the same corner order that is going to be used by the decoder. // Note that |corner_order| should contain only one corner per face (it can // have all corners but only the first encountered corner for each face is // going to be used to start a traversal). If the corner order is not set, the // corners are processed sequentially based on their ids. void SetCornerOrder(const std::vector<CornerIndex> &corner_order) { corner_order_ = &corner_order; } bool UpdatePointToAttributeIndexMapping(PointAttribute *attribute) override { const auto *corner_table = traverser_.corner_table(); attribute->SetExplicitMapping(mesh_->num_points()); const size_t num_faces = mesh_->num_faces(); const size_t num_points = mesh_->num_points(); for (FaceIndex f(0); f < static_cast<uint32_t>(num_faces); ++f) { const auto &face = mesh_->face(f); for (int p = 0; p < 3; ++p) { const PointIndex point_id = face[p]; const VertexIndex vert_id = corner_table->Vertex(CornerIndex(3 * f.value() + p)); if (vert_id == kInvalidVertexIndex) return false; const AttributeValueIndex att_entry_id( encoding_data_ ->vertex_to_encoded_attribute_value_index_map[vert_id.value()]); if (att_entry_id.value() >= num_points) { // There cannot be more attribute values than the number of points. return false; } attribute->SetPointMapEntry(point_id, att_entry_id); } } return true; } protected: bool GenerateSequenceInternal() override { // Preallocate memory for storing point indices. We expect the number of // points to be the same as the number of corner table vertices. out_point_ids()->reserve(traverser_.corner_table()->num_vertices()); traverser_.OnTraversalStart(); if (corner_order_) { for (uint32_t i = 0; i < corner_order_->size(); ++i) { if (!ProcessCorner(corner_order_->at(i))) return false; } } else { const int32_t num_faces = traverser_.corner_table()->num_faces(); for (int i = 0; i < num_faces; ++i) { if (!ProcessCorner(CornerIndex(3 * i))) return false; } } traverser_.OnTraversalEnd(); return true; } private: bool ProcessCorner(CornerIndex corner_id) { return traverser_.TraverseFromCorner(corner_id); } TraverserT traverser_; const Mesh *mesh_; const MeshAttributeIndicesEncodingData *encoding_data_; const std::vector<CornerIndex> *corner_order_; }; } // namespace draco #endif // DRACO_COMPRESSION_ATTRIBUTES_MESH_TRAVERSAL_SEQUENCER_H_
SergeyNewcastle/draco
src/draco/compression/attributes/prediction_schemes/prediction_scheme_normal_octahedron_transform_base.h
<filename>src/draco/compression/attributes/prediction_schemes/prediction_scheme_normal_octahedron_transform_base.h // Copyright 2016 The Draco Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef DRACO_COMPRESSION_ATTRIBUTES_PREDICTION_SCHEMES_PREDICTION_SCHEME_NORMAL_OCTAHEDRON_TRANSFORM_BASE_H_ #define DRACO_COMPRESSION_ATTRIBUTES_PREDICTION_SCHEMES_PREDICTION_SCHEME_NORMAL_OCTAHEDRON_TRANSFORM_BASE_H_ #include <cmath> #include "draco/compression/attributes/normal_compression_utils.h" #include "draco/compression/config/compression_shared.h" #include "draco/core/bit_utils.h" #include "draco/core/macros.h" #include "draco/core/vector_d.h" namespace draco { // Base class containing shared functionality used by both encoding and decoding // octahedral normal prediction scheme transforms. See the encoding transform // for more details about the method. template <typename DataTypeT> class PredictionSchemeNormalOctahedronTransformBase { public: typedef VectorD<DataTypeT, 2> Point2; typedef DataTypeT DataType; PredictionSchemeNormalOctahedronTransformBase() {} // We expect the mod value to be of the form 2^b-1. explicit PredictionSchemeNormalOctahedronTransformBase( DataType max_quantized_value) { this->set_max_quantized_value(max_quantized_value); } static constexpr PredictionSchemeTransformType GetType() { return PREDICTION_TRANSFORM_NORMAL_OCTAHEDRON; } // We can return true as we keep correction values positive. bool AreCorrectionsPositive() const { return true; } inline DataTypeT max_quantized_value() const { return octahedron_tool_box_.max_quantized_value(); } inline DataTypeT center_value() const { return octahedron_tool_box_.center_value(); } inline int32_t quantization_bits() const { return octahedron_tool_box_.quantization_bits(); } protected: inline bool set_max_quantized_value(DataTypeT max_quantized_value) { if (max_quantized_value % 2 == 0) return false; int q = bits::MostSignificantBit(max_quantized_value) + 1; return octahedron_tool_box_.SetQuantizationBits(q); } bool IsInDiamond(DataTypeT s, DataTypeT t) const { return octahedron_tool_box_.IsInDiamond(s, t); } void InvertDiamond(DataTypeT *s, DataTypeT *t) const { return octahedron_tool_box_.InvertDiamond(s, t); } int32_t ModMax(int32_t x) const { return octahedron_tool_box_.ModMax(x); } // For correction values. int32_t MakePositive(int32_t x) const { return octahedron_tool_box_.MakePositive(x); } private: OctahedronToolBox octahedron_tool_box_; }; } // namespace draco #endif // DRACO_COMPRESSION_ATTRIBUTES_PREDICTION_SCHEMES_PREDICTION_SCHEME_NORMAL_OCTAHEDRON_TRANSFORM_BASE_H_
SergeyNewcastle/draco
src/draco/compression/attributes/prediction_schemes/mesh_prediction_scheme_parallelogram_decoder.h
<reponame>SergeyNewcastle/draco<gh_stars>0 // Copyright 2016 The Draco Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef DRACO_COMPRESSION_ATTRIBUTES_PREDICTION_SCHEMES_MESH_PREDICTION_SCHEME_PARALLELOGRAM_DECODER_H_ #define DRACO_COMPRESSION_ATTRIBUTES_PREDICTION_SCHEMES_MESH_PREDICTION_SCHEME_PARALLELOGRAM_DECODER_H_ #include "draco/compression/attributes/prediction_schemes/mesh_prediction_scheme_decoder.h" #include "draco/compression/attributes/prediction_schemes/mesh_prediction_scheme_parallelogram_shared.h" namespace draco { // Decoder for attribute values encoded with the standard parallelogram // prediction. See the description of the corresponding encoder for more // details. template <typename DataTypeT, class TransformT, class MeshDataT> class MeshPredictionSchemeParallelogramDecoder : public MeshPredictionSchemeDecoder<DataTypeT, TransformT, MeshDataT> { public: using CorrType = typename PredictionSchemeDecoder<DataTypeT, TransformT>::CorrType; using CornerTable = typename MeshDataT::CornerTable; explicit MeshPredictionSchemeParallelogramDecoder( const PointAttribute *attribute) : MeshPredictionSchemeDecoder<DataTypeT, TransformT, MeshDataT>( attribute) {} MeshPredictionSchemeParallelogramDecoder(const PointAttribute *attribute, const TransformT &transform, const MeshDataT &mesh_data) : MeshPredictionSchemeDecoder<DataTypeT, TransformT, MeshDataT>( attribute, transform, mesh_data) {} bool ComputeOriginalValues(const CorrType *in_corr, DataTypeT *out_data, int size, int num_components, const PointIndex *entry_to_point_id_map) override; PredictionSchemeMethod GetPredictionMethod() const override { return MESH_PREDICTION_PARALLELOGRAM; } bool IsInitialized() const override { return this->mesh_data().IsInitialized(); } }; template <typename DataTypeT, class TransformT, class MeshDataT> bool MeshPredictionSchemeParallelogramDecoder<DataTypeT, TransformT, MeshDataT>:: ComputeOriginalValues(const CorrType *in_corr, DataTypeT *out_data, int /* size */, int num_components, const PointIndex * /* entry_to_point_id_map */) { this->transform().Initialize(num_components); const CornerTable *const table = this->mesh_data().corner_table(); const std::vector<int32_t> *const vertex_to_data_map = this->mesh_data().vertex_to_data_map(); std::unique_ptr<DataTypeT[]> pred_vals(new DataTypeT[num_components]()); // Restore the first value. this->transform().ComputeOriginalValue(pred_vals.get(), in_corr, out_data); const int corner_map_size = static_cast<int>(this->mesh_data().data_to_corner_map()->size()); for (int p = 1; p < corner_map_size; ++p) { const CornerIndex corner_id = this->mesh_data().data_to_corner_map()->at(p); const int dst_offset = p * num_components; if (!ComputeParallelogramPrediction(p, corner_id, table, *vertex_to_data_map, out_data, num_components, pred_vals.get())) { // Parallelogram could not be computed, Possible because some of the // vertices are not valid (not encoded yet). // We use the last encoded point as a reference (delta coding). const int src_offset = (p - 1) * num_components; this->transform().ComputeOriginalValue( out_data + src_offset, in_corr + dst_offset, out_data + dst_offset); } else { // Apply the parallelogram prediction. this->transform().ComputeOriginalValue( pred_vals.get(), in_corr + dst_offset, out_data + dst_offset); } } return true; } } // namespace draco #endif // DRACO_COMPRESSION_ATTRIBUTES_PREDICTION_SCHEMES_MESH_PREDICTION_SCHEME_PARALLELOGRAM_DECODER_H_
emileb/Raze
source/core/gamestruct.h
<reponame>emileb/Raze #pragma once bool System_WantGuiCapture(); // During playing this tells us whether the game must be paused due to active GUI elememts. #include <stdint.h> #include "vectors.h" #include "engineerrors.h" #include "stats.h" #include "packet.h" #include "binaryangle.h" #include "inputstate.h" class FSerializer; struct FRenderViewpoint; struct spritetype; struct GameStats { int kill, tkill; int secret, tsecret; int timesecnd; int frags; }; struct FNewGameStartup { int Episode; int Level; int Skill; }; struct FSavegameInfo { const char *savesig; int minsavever; int currentsavever; }; struct ReservedSpace { int top; int statusbar; }; enum EMenuSounds : int; struct MapRecord; extern cycle_t drawtime, actortime, thinktime, gameupdatetime; struct GeoEffect { int* geosectorwarp; int* geosectorwarp2; int* geosector; int* geox; int* geoy; int* geox2; int* geoy2; int geocnt; }; struct GameInterface { virtual const char* Name() { return "$"; } virtual ~GameInterface() {} virtual bool GenerateSavePic() { return false; } virtual void app_init() = 0; virtual void LoadGameTextures() {} virtual void loadPalette(); virtual void clearlocalinputstate() {} virtual void UpdateScreenSize() {} virtual void FreeLevelData(); virtual void FreeGameData() {} virtual void PlayHudSound() {} virtual GameStats getStats() { return {}; } virtual void MainMenuOpened() {} virtual void MenuOpened() {} virtual void MenuClosed() {} virtual void MenuSound(EMenuSounds snd) {} virtual bool CanSave() { return true; } virtual void CustomMenuSelection(int menu, int item) {} virtual bool StartGame(FNewGameStartup& gs) { return true; } virtual FSavegameInfo GetSaveSig() { return { "", 0, 0}; } virtual double SmallFontScale() { return 1; } virtual void SerializeGameState(FSerializer& arc) {} virtual void DrawPlayerSprite(const DVector2& origin, bool onteam) {} virtual void SetAmbience(bool on) {} virtual FString GetCoordString() { return "'stat coord' not implemented"; } virtual void ExitFromMenu() { throw CExitEvent(0); } virtual ReservedSpace GetReservedScreenSpace(int viewsize) { return { 0, 0 }; } virtual void GetInput(InputPacket* packet, ControlInfo* const hidInput) {} virtual void UpdateSounds() {} virtual void ErrorCleanup() {} virtual void Startup() {} virtual void DrawBackground() {} virtual void Render() {} virtual void Ticker() {} virtual int GetPlayerChecksum(int pnum) { return 0x12345678 + pnum; } virtual const char *CheckCheatMode() { return nullptr; } virtual const char* GenericCheat(int player, int cheat) = 0; virtual void NextLevel(MapRecord* map, int skill) {} virtual void NewGame(MapRecord* map, int skill, bool special = false) {} virtual void LevelCompleted(MapRecord* map, int skill) {} virtual bool DrawAutomapPlayer(int x, int y, int z, int a, double const smoothratio) { return false; } virtual void SetTileProps(int tile, int surf, int vox, int shade) {} virtual fixed_t playerHorizMin() { return IntToFixed(-200); } virtual fixed_t playerHorizMax() { return IntToFixed(200); } virtual int playerKeyMove() { return 0; } virtual void WarpToCoords(int x, int y, int z, int a, int h) {} virtual void ToggleThirdPerson() { } virtual void SwitchCoopView() { Printf("Unsupported command\n"); } virtual void ToggleShowWeapon() { Printf("Unsupported command\n"); } virtual int chaseCamX(binangle ang) { return 0; } virtual int chaseCamY(binangle ang) { return 0; } virtual int chaseCamZ(fixedhoriz horiz) { return 0; } virtual void processSprites(spritetype* tsprite, int& spritesortcnt, int viewx, int viewy, int viewz, binangle viewang, double smoothRatio) = 0; virtual void UpdateCameras(double smoothratio) {} virtual void EnterPortal(spritetype* viewer, int type) {} virtual void LeavePortal(spritetype* viewer, int type) {} virtual bool GetGeoEffect(GeoEffect* eff, int viewsector) { return false; } virtual int Voxelize(int sprnum) { return -1; } virtual void AddMultiplayerEpisode(FString name) {} virtual FString statFPS() { FString output; output.AppendFormat("Actor think time: %.3f ms\n", actortime.TimeMS()); output.AppendFormat("Total think time: %.3f ms\n", thinktime.TimeMS()); output.AppendFormat("Game Update: %.3f ms\n", gameupdatetime.TimeMS()); output.AppendFormat("Draw time: %.3f ms\n", drawtime.TimeMS()); return output; } }; extern GameInterface* gi; void ImGui_Begin_Frame();
emileb/Raze
source/common/rendering/hwrenderer/data/buffers.h
#pragma once #include <stddef.h> #include <assert.h> class FRenderState; #define HW_MAX_PIPELINE_BUFFERS 8 // The low level code needs to know which attributes exist. // OpenGL needs to change the state of all of them per buffer binding. // VAOs are mostly useless for this because they lump buffer and binding state together which the model code does not want. enum { VATTR_VERTEX, VATTR_TEXCOORD, VATTR_COLOR, VATTR_VERTEX2, VATTR_NORMAL, VATTR_NORMAL2, VATTR_MAX }; enum EVertexAttributeFormat { VFmt_Float4, VFmt_Float3, VFmt_Float2, VFmt_Float, VFmt_Byte4, VFmt_Packed_A2R10G10B10, }; struct FVertexBufferAttribute { int binding; int location; int format; int offset; }; class IBuffer { protected: size_t buffersize = 0; void *map = nullptr; public: IBuffer() = default; IBuffer(const IBuffer &) = delete; IBuffer &operator=(const IBuffer &) = delete; virtual ~IBuffer() = default; virtual void SetData(size_t size, const void *data, bool staticdata = true) = 0; virtual void SetSubData(size_t offset, size_t size, const void *data) = 0; virtual void *Lock(unsigned int size) = 0; virtual void Unlock() = 0; virtual void Resize(size_t newsize) = 0; virtual void Upload(size_t start, size_t size) {} // For unmappable buffers virtual void Map() {} // Only needed by old OpenGL but this needs to be in the interface. virtual void Unmap() {} void *Memory() { return map; } size_t Size() { return buffersize; } virtual void GPUDropSync() {} virtual void GPUWaitSync() {} }; class IVertexBuffer : virtual public IBuffer { public: virtual void SetFormat(int numBindingPoints, int numAttributes, size_t stride, const FVertexBufferAttribute *attrs) = 0; }; // This merely exists to have a dedicated type for index buffers to inherit from. class IIndexBuffer : virtual public IBuffer { // Element size is fixed to 4, thanks to OpenGL requiring this info to be coded into the glDrawElements call. // This mostly prohibits a more flexible buffer setup but GZDoom doesn't use any other format anyway. // Ob Vulkam, element size is a buffer property and of no concern to the drawing functions (as it should be.) }; class IDataBuffer : virtual public IBuffer { // Can be either uniform or shader storage buffer, depending on its needs. public: virtual void BindRange(FRenderState *state, size_t start, size_t length) = 0; };
emileb/Raze
source/games/duke/src/duke3d.h
<reponame>emileb/Raze<gh_stars>1-10 #pragma once #include "build.h" #include "compat.h" #include "polymost.h" #include "gamecvars.h" #include "razemenu.h" #include "gamecontrol.h" #include "gamevar.h" #include "global.h" #include "funct.h" #include "names.h" #include "quotemgr.h" #include "rts.h" #include "sounds.h" #include "soundefs.h" #include "gamestruct.h" #include "v_draw.h" BEGIN_DUKE_NS struct GameInterface : public ::GameInterface { const char* Name() override { return "Duke"; } void app_init() override; void loadPalette(); void clearlocalinputstate() override; bool GenerateSavePic() override; void PlayHudSound() override; GameStats getStats() override; void MenuOpened() override; void MenuSound(EMenuSounds snd) override; bool CanSave() override; bool StartGame(FNewGameStartup& gs) override; FSavegameInfo GetSaveSig() override; double SmallFontScale() override { return isRR() ? 0.5 : 1.; } void SerializeGameState(FSerializer& arc) override; FString GetCoordString() override; void ExitFromMenu() override; ReservedSpace GetReservedScreenSpace(int viewsize) override; void DrawPlayerSprite(const DVector2& origin, bool onteam) override; void GetInput(InputPacket* packet, ControlInfo* const hidInput) override; void UpdateSounds() override; void Startup() override; void DrawBackground() override; void Render() override; void Ticker() override; const char* GenericCheat(int player, int cheat) override; const char* CheckCheatMode() override; void NextLevel(MapRecord* map, int skill) override; void NewGame(MapRecord* map, int skill, bool) override; void LevelCompleted(MapRecord* map, int skill) override; bool DrawAutomapPlayer(int x, int y, int z, int a, double const smoothratio) override; int playerKeyMove() override { return 40; } void WarpToCoords(int x, int y, int z, int a, int h) override; void ToggleThirdPerson() override; void SwitchCoopView() override; void ToggleShowWeapon() override; int chaseCamX(binangle ang) { return -ang.bcos(-4); } int chaseCamY(binangle ang) { return -ang.bsin(-4); } int chaseCamZ(fixedhoriz horiz) { return horiz.asq16() >> 9; } void processSprites(spritetype* tsprite, int& spritesortcnt, int viewx, int viewy, int viewz, binangle viewang, double smoothRatio) override; void UpdateCameras(double smoothratio) override; void EnterPortal(spritetype* viewer, int type) override; void LeavePortal(spritetype* viewer, int type) override; bool GetGeoEffect(GeoEffect* eff, int viewsector) override; void AddMultiplayerEpisode(FString name) override; }; struct Dispatcher { // sectors_?.cpp void (*think)(); void (*initactorflags)(); bool (*isadoorwall)(int dapic); void (*animatewalls)(); void (*operaterespawns)(int low); void (*operateforcefields)(DDukeActor* act, int low); bool (*checkhitswitch)(int snum, int w, DDukeActor* act); void (*activatebysector)(int sect, DDukeActor* j); void (*checkhitwall)(DDukeActor* spr, int dawallnum, int x, int y, int z, int atwith); bool (*checkhitceiling)(int sn); void (*checkhitsprite)(DDukeActor* i, DDukeActor* sn); void (*checksectors)(int low); bool (*ceilingspace)(int sectnum); bool (*floorspace)(int sectnum); void (*addweapon)(struct player_struct *p, int weapon); void (*hitradius)(DDukeActor* i, int r, int hp1, int hp2, int hp3, int hp4); void (*lotsofmoney)(DDukeActor *s, short n); void (*lotsofmail)(DDukeActor *s, short n); void (*lotsofpaper)(DDukeActor *s, short n); void (*guts)(DDukeActor* s, short gtype, short n, short p); DDukeActor* (*ifhitsectors)(int sectnum); int (*ifhitbyweapon)(DDukeActor* sectnum); void (*fall)(DDukeActor* actor, int g_p); bool (*spawnweapondebris)(int picnum, int dnum); void (*respawnhitag)(DDukeActor* g_sp); void (*checktimetosleep)(DDukeActor* actor); void (*move)(DDukeActor* i, int g_p, int g_x); // player void (*incur_damage)(struct player_struct* p); void (*shoot)(DDukeActor*, int); void (*selectweapon)(int snum, int j); int (*doincrements)(struct player_struct* p); void (*checkweapons)(struct player_struct* p); void (*processinput)(int snum); void (*displayweapon)(int snum, double smoothratio); void (*displaymasks)(int snum, int p, double smoothratio); void (*animatesprites)(spritetype* tsprite, int& spritesortcnt, int x, int y, int a, int smoothratio); }; extern Dispatcher fi; END_DUKE_NS
winksaville/sel4-app-test-nolibc
src/main.c
<reponame>winksaville/sel4-app-test-nolibc /* * Copyright 2015, <NAME> * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. */ #include <autoconf.h> #include <sel4/simple_types.h> #include <sel4/string.h> #include <sel4/printf.h> #include <sel4/debug_printf.h> #include <sel4/putchar.h> #include <sel4/assert.h> #include <sel4/debug_assert.h> #include <sel4/benchmark.h> #include <sel4/sel4.h> volatile seL4_Uint32 volatile0 = 0; /** * Return seL4_True if the expr was not true signifying a failure */ static inline seL4_Bool test_failure(seL4_Bool expr, const char* exprStrg, const char* function, const char* file, const int lineNumber) { seL4_Bool failure = !expr; if (failure) { if (seL4_StrLen(exprStrg) == 0) { seL4_Printf("TEST was not true. func=%s file=%s:%d\n", function, file, lineNumber); } else { seL4_Printf("TEST '%s' was not true. func=%s file=%s:%d\n", exprStrg, function, file, lineNumber); } } return failure; } /** * Macro which returns seL4_True if the expr did NOT evaluate to true */ #define TEST(expr) test_failure((seL4_Bool)(expr), #expr, __FUNCTION__, __FILE__, __LINE__) seL4_Bool test_strlen(void) { seL4_Bool failure = seL4_False; failure |= TEST(seL4_StrLen(seL4_Null) == 0); failure |= TEST(seL4_StrLen("") == 0); failure |= TEST(seL4_StrLen("1") == 1); failure |= TEST(seL4_StrLen("\n") == 1); failure |= TEST(seL4_StrLen("12") == 2); return failure; } seL4_Bool test_strncmp(void) { seL4_Bool failure = seL4_False; char *str1 = "str1"; char *str2 = "str2"; failure |= TEST(seL4_StrNCmp(seL4_Null, seL4_Null, 0) == 0); failure |= TEST(seL4_StrNCmp(str1, seL4_Null, 0) == 0); failure |= TEST(seL4_StrNCmp(seL4_Null, str1, 0) == 0); failure |= TEST(seL4_StrNCmp(str1, str1, 4) == 0); failure |= TEST(seL4_StrNCmp(str1, str2, 3) == 0); failure |= TEST(seL4_StrNCmp(str1, str2, 4) < 0); failure |= TEST(seL4_StrNCmp(str2, str1, 4) > 0); return failure; } seL4_Bool test_putchar(void) { // Just verify we can call it. seL4_PutChar('h'); seL4_PutChar('i'); seL4_PutChar('\n'); return seL4_False; } seL4_Bool test_simple_types(void) { seL4_Bool failure = seL4_False; seL4_Int8 i8 = 1; failure |= TEST(i8 == 1); failure |= TEST(sizeof(i8) == 1); seL4_Int16 i16 = 2; failure |= TEST(i16 == 2); failure |= TEST(sizeof(i16) == 2); seL4_Int32 i32 = 3; failure |= TEST(i32 == 3); failure |= TEST(sizeof(i32) == 4); seL4_Int64 i64 = 4; failure |= TEST(i64 == 4); failure |= TEST(sizeof(i64) == 8); seL4_Uint8 u8 = 1; failure |= TEST(u8 == 1); failure |= TEST(sizeof(u8) == 1); seL4_Uint16 u16 = 2; failure |= TEST(u16 == 2); failure |= TEST(sizeof(u16) == 2); seL4_Uint32 u32 = 3; failure |= TEST(u32 == 3); failure |= TEST(sizeof(u32) == 4); seL4_Uint64 u64 = 4; failure |= TEST(u64 == 4); failure |= TEST(sizeof(u64) == 8); seL4_Uint8 *p = seL4_Null; failure |= TEST(p == seL4_Null); return failure; } seL4_Bool test_sel4_assert() { seL4_Bool failure = seL4_False; /* * Manually test these compile time errors by enabling both * and the compilation should fail. */ //seL4_CompileTimeAssert(1 == 0); //seL4_CompileTimeAssert(volatile0 == 0); /* * Manually test these runtime errors, enable one at a time * and compile and run, each statement should fail. */ //seL4_Fail("failing"); //seL4_Assert(0 == 1); //seL4_Assert(volatile0 == 1); //seL4_DebugAssert(1 == 2); /* * Manually uncomment the statement below and in .config * set CONFIG_USER_DEBUG_BUILD=y this causes NDEBUG to NOT * be defined. Compile and run and you should see a runtime * error. * * Next set CONFIG_USER_DEBUG_BUILD=n recompile and rerun. * The statement will NOT fail because NDEBUG is now defined. * This verifies seL4_DebugAssert compiles to a NOP when * NDEBUG is defined. */ //seL4_DebugAssert(volatile0 == 2); // None of this should fail seL4_Assert(0 == 0); seL4_Assert(volatile0 == 0); seL4_DebugAssert(0 == 0); seL4_DebugAssert(volatile0 == 0); seL4_CompileTimeAssert(0 == 0); seL4_Bool b = seL4_True; seL4_Assert(b != seL4_False); return failure; } #if defined(CONFIG_BENCHMARK) seL4_Bool test_benchmark(void) { seL4_BenchmarkResetLog(); seL4_BenchmarkDumpFullLog(); return seL4_False; } #else // CONFIG_BENCHMARK is not defined #pragma message "In " __FILE__ " CONFIG_BENCHMARK is not defined. Edit .config setting 'CONFIG_BENCHMARK=y'" #endif // CONFIG_BENCHMARK // Test BootInfo if it gets initialized, currently it isn't seL4_Bool test_bootinfo() { seL4_Bool failure = seL4_False; seL4_BootInfo *bi = seL4_GetBootInfo(); failure |= TEST(bi != seL4_Null); failure |= TEST(bi->nodeID == 0); return failure; } typedef struct { int idx; char buff[256]; } Buffer; /** * writeBeg called before first writeCharToBuff */ static void writeBeg(seL4_Writer* this) { Buffer *pBuffer = (Buffer*)this->data; pBuffer->idx = 0; } /** * writeEnd called after the last writeCharToBuff */ static void writeEnd(seL4_Writer* this) { Buffer *pBuffer = (Buffer*)this->data; pBuffer->buff[pBuffer->idx] = 0; } /** * Write a character to the buffer */ static void writeCharToBuff(seL4_Writer* this, void* param) { Buffer *pBuffer = (Buffer*)this->data; char ch = ((char)(((int)param) & 0xff)); pBuffer->buff[pBuffer->idx++] = ch; if (pBuffer->idx >= sizeof(pBuffer->buff)) { pBuffer->idx = 0; } } static inline seL4_Bool testPrintingResult(const char* expected, Buffer *pBuffer, const char* function, const char* file, const int lineNumber) { seL4_Bool failure = seL4_False; if (pBuffer->idx != seL4_StrLen(expected)) { seL4_Printf("buff:%s != expected:%s idx=%d\n", pBuffer->buff, expected, pBuffer->idx); failure |= test_failure(pBuffer->idx == seL4_StrLen(expected), "", function, file, lineNumber); } else if (seL4_StrNCmp(expected, pBuffer->buff, pBuffer->idx) != 0) { seL4_Printf("buff:%s != expected:%s idx=%d\n", pBuffer->buff, expected, pBuffer->idx); failure |= test_failure(seL4_StrNCmp(expected, pBuffer->buff, pBuffer->idx) == 0l, "", function, file, lineNumber); } return failure; } #define TEST_PRINTING_NO_PARAM(formatting, expectedVal) \ ({ seL4_Bool failure; \ seL4_WPrintf(&writer, formatting); \ failure = testPrintingResult(expectedVal, (Buffer*)(writer.data), __FUNCTION__, __FILE__, __LINE__); \ failure; }) #define TEST_PRINTING(formatting, param, expectedVal) \ ({ seL4_Bool failure; \ seL4_WPrintf(&writer, formatting, param); \ failure = testPrintingResult(expectedVal, (Buffer*)(writer.data), __FUNCTION__, __FILE__, __LINE__); \ failure; }) seL4_Bool test_printf(void) { seL4_Bool failure = seL4_False; seL4_Printf("Hello, World\n"); seL4_DebugPrintf("Hello, World: via seL4_DebugDrintf\n"); // Define a buffer and a writer for testing printf Buffer buffer; seL4_Writer writer = { .writeBeg = writeBeg, .writeParam = writeCharToBuff, .writeEnd = writeEnd, .data = &buffer }; failure |= TEST_PRINTING_NO_PARAM("Hello", "Hello"); failure |= TEST_PRINTING_NO_PARAM("%", ""); failure |= TEST_PRINTING_NO_PARAM("%1", "%1"); failure |= TEST_PRINTING_NO_PARAM("%%", "%"); failure |= TEST_PRINTING("%s", "string", "string"); failure |= TEST_PRINTING("%b", 0, "0"); failure |= TEST_PRINTING("%b", 0x87654321, "10000111011001010100001100100001"); failure |= TEST_PRINTING("%b", 0xFFFFFFFF, "11111111111111111111111111111111"); failure |= TEST_PRINTING("%d", 1, "1"); failure |= TEST_PRINTING("%d", 0x7FFFFFFF, "2147483647"); failure |= TEST_PRINTING("%d", 0x80000000, "-2147483648"); failure |= TEST_PRINTING("%d", 0x80000001, "-2147483647"); failure |= TEST_PRINTING("%d", 0xFFFFFFFF, "-1"); failure |= TEST_PRINTING("%d", -1, "-1"); failure |= TEST_PRINTING("%u", 2, "2"); failure |= TEST_PRINTING("%u", 0x7FFFFFFF, "2147483647"); failure |= TEST_PRINTING("%u", 0x80000000, "2147483648"); failure |= TEST_PRINTING("%u", 0x80000001, "2147483649"); failure |= TEST_PRINTING("%u", 0xFFFFFFFF, "4294967295"); failure |= TEST_PRINTING("%u", -1, "4294967295"); failure |= TEST_PRINTING("%x", 0, "0"); failure |= TEST_PRINTING("%x", 9, "9"); failure |= TEST_PRINTING("%x", 10, "a"); failure |= TEST_PRINTING("%x", 15, "f"); failure |= TEST_PRINTING("%x", 16, "10"); failure |= TEST_PRINTING("0x%x", 0x12345678, "0x12345678"); failure |= TEST_PRINTING("0x%x", 0x9abcdef0, "0x9abcdef0"); failure |= TEST_PRINTING_NO_PARAM("%l", "%l"); failure |= TEST_PRINTING_NO_PARAM("%la", "%la"); failure |= TEST_PRINTING_NO_PARAM("%ll", "%ll"); failure |= TEST_PRINTING_NO_PARAM("%llz1", "%llz1"); failure |= TEST_PRINTING("%llx", 0ll, "0"); failure |= TEST_PRINTING("%llx", 9ll, "9"); failure |= TEST_PRINTING("%x", 10ll, "a"); failure |= TEST_PRINTING("%x", 15ll, "f"); failure |= TEST_PRINTING("%llx", 16ll, "10"); // Test we are "filling" zeros correctly as we print using writeUint32 twice failure |= TEST_PRINTING("%llx", 0x80000000ll, "80000000"); failure |= TEST_PRINTING("%llx", 0x800000000ll, "800000000"); failure |= TEST_PRINTING("%llx", 0x800000000000ll, "800000000000"); failure |= TEST_PRINTING("%llx", 0x80000000000000ll, "80000000000000"); failure |= TEST_PRINTING("%llx", 0x8000000000000000ll, "8000000000000000"); failure |= TEST_PRINTING("%llx", 0x8000000000000001ll, "8000000000000001"); failure |= TEST_PRINTING("%llx", 0xFEDCBA9876543210ll, "fedcba9876543210"); failure |= TEST_PRINTING("%llx", 0x7fffffffffffffffll, "7fffffffffffffff"); failure |= TEST_PRINTING("%llx", -1ll, "ffffffffffffffff"); void *pv = (void *)0xf7654321; failure |= TEST_PRINTING("%p", pv, "f7654321"); return failure; } /** * No parameters are passed to main, the return * value is ignored and the program hangs. */ int main(void) { seL4_Bool failure = seL4_False; seL4_Printf("\ntest-nolibc:\n"); failure |= test_strlen(); failure |= test_strncmp(); failure |= test_putchar(); failure |= test_simple_types(); failure |= test_sel4_assert(); #if defined(CONFIG_BENCHMARK) failure |= test_benchmark(); #endif failure |= test_bootinfo(); failure |= test_printf(); seL4_Printf(failure ? "-FAILURE-\n" : "+SUCCESS+\n"); return 0; }
3drobotics/PotreeConverter
PotreeConverter/include/Vector3.h
<gh_stars>10-100 #ifndef VECTOR3_H #define VECTOR3_H #include <math.h> #include <iostream> using std::ostream; #ifndef _MSC_VER using std::max; #endif namespace Potree{ template<class T> class Vector3{ public: T x = 0; T y = 0; T z = 0; Vector3() = default; Vector3(T x, T y, T z){ this->x = x; this->y = y; this->z = z; } Vector3(T value){ this->x = value; this->y = value; this->z = value; } Vector3(const Vector3<T> &other) :x(other.x), y(other.y), z(other.z) { } ~Vector3() = default; T length(){ return sqrt(x*x + y*y + z*z); } T squaredLength(){ return x*x + y*y + z*z; } T distanceTo(Vector3<T> p) const{ return ((*this) - p).length(); } T squaredDistanceTo(const Vector3<T> &p) const{ return ((*this) - p).squaredLength(); } T maxValue(){ return max(x, max(y,z)); } Vector3<T> operator-(const Vector3<T>& right) const { return Vector3<T>(x - right.x, y - right.y, z - right.z); } Vector3<T> operator+(const Vector3<T>& right) const { return Vector3<T>(x + right.x, y + right.y, z + right.z); } Vector3<T> operator+(const T right) const { return Vector3<T>(x + right, y + right, z + right); } Vector3<T> operator/(const T &a) const{ return Vector3<T>(x / a, y / a, z / a); } friend ostream &operator<<( ostream &output, const Vector3<T> &value ){ output << "[" << value.x << ", " << value.y << ", " << value.z << "]" ; return output; } }; } #endif
pgmarchenko/skillset_metrics
xcode/HardcodedUI/HardcodedUI/ViewController.h
<reponame>pgmarchenko/skillset_metrics // // ViewController.h // HardcodedUI // // Created by <NAME> on 10/19/15. // Copyright © 2015 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
pgmarchenko/skillset_metrics
xcode/HardcodedUI/HardcodedUI/MainView.h
// // MainView.h // HardcodedUI // // Created by <NAME> on 10/19/15. // Copyright © 2015 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface MainView : UIView @property (nonatomic, readonly) UIButton *pushButton; @property (nonatomic, readonly) UIButton *modalButton; @end
superdump/openwebrtc-gst-plugins
ext/erdtls/src/plugin.c
/* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gsterdtlsdec.h" #include "gsterdtlsenc.h" #include "gsterdtlssrtpenc.h" #include "gsterdtlssrtpdec.h" #include "gsterdtlssrtpdemux.h" #include <gst/gst.h> static gboolean plugin_init(GstPlugin *plugin) { return gst_element_register(plugin, "erdtlsenc", GST_RANK_NONE, GST_TYPE_ER_DTLS_ENC) && gst_element_register(plugin, "erdtlsdec", GST_RANK_NONE, GST_TYPE_ER_DTLS_DEC) && gst_element_register(plugin, "erdtlssrtpdec", GST_RANK_NONE, GST_TYPE_ER_DTLS_SRTP_DEC) && gst_element_register(plugin, "erdtlssrtpenc", GST_RANK_NONE, GST_TYPE_ER_DTLS_SRTP_ENC) && gst_element_register(plugin, "erdtlssrtpdemux", GST_RANK_NONE, GST_TYPE_ER_DTLS_SRTP_DEMUX); } /* PACKAGE: this is usually set by autotools depending on some _INIT macro * in configure.ac and then written into and defined in config.h, but we can * just set it ourselves here in case someone doesn't use autotools to * compile this code. GST_PLUGIN_DEFINE needs PACKAGE to be defined. */ #ifndef PACKAGE #define PACKAGE "erdtls" #endif /* gstreamer looks for this structure to register plugins */ GST_PLUGIN_DEFINE( GST_VERSION_MAJOR, GST_VERSION_MINOR, erdtls, "Ericsson DTLS decoder and encoder plugins", plugin_init, PACKAGE_VERSION, "BSD", "OpenWebRTC GStreamer plugins", "http://www.ericsson.com/" )
superdump/openwebrtc-gst-plugins
ext/erdtls/src/erdtlscertificate.c
/* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "erdtlscertificate.h" #include "erdtlsagent.h" #include "erdtlscommon.h" #ifdef __APPLE__ # define __AVAILABILITYMACROS__ # define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER #endif #include <openssl/ssl.h> #if ER_DTLS_USE_GST_LOG GST_DEBUG_CATEGORY_STATIC(er_dtls_certificate_debug); # define GST_CAT_DEFAULT er_dtls_certificate_debug G_DEFINE_TYPE_WITH_CODE(ErDtlsCertificate, er_dtls_certificate, G_TYPE_OBJECT, GST_DEBUG_CATEGORY_INIT(er_dtls_certificate_debug, "erdtlscertificate", 0, "Ericsson DTLS Certificate")); #else G_DEFINE_TYPE(ErDtlsCertificate, er_dtls_certificate, G_TYPE_OBJECT); #endif #define ER_DTLS_CERTIFICATE_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), ER_TYPE_DTLS_CERTIFICATE, ErDtlsCertificatePrivate)) enum { PROP_0, PROP_PEM, NUM_PROPERTIES }; static GParamSpec *properties[NUM_PROPERTIES]; #define DEFAULT_PEM NULL struct _ErDtlsCertificatePrivate { X509 *x509; EVP_PKEY *private_key; gchar *pem; }; static void er_dtls_certificate_finalize(GObject *gobject); static void er_dtls_certificate_set_property(GObject *, guint prop_id, const GValue *, GParamSpec *); static void er_dtls_certificate_get_property(GObject *, guint prop_id, GValue *, GParamSpec *); static void init_generated(ErDtlsCertificate *); static void init_from_pem_string(ErDtlsCertificate *, const gchar *pem); static void er_dtls_certificate_class_init(ErDtlsCertificateClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS(klass); g_type_class_add_private(klass, sizeof(ErDtlsCertificatePrivate)); gobject_class->set_property = er_dtls_certificate_set_property; gobject_class->get_property = er_dtls_certificate_get_property; properties[PROP_PEM] = g_param_spec_string("pem", "Pem string", "A string containing a X509 certificate and RSA private key in PEM format", DEFAULT_PEM, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS); g_object_class_install_properties(gobject_class, NUM_PROPERTIES, properties); _er_dtls_init_openssl(); gobject_class->finalize = er_dtls_certificate_finalize; } static void er_dtls_certificate_init(ErDtlsCertificate *self) { ErDtlsCertificatePrivate *priv = ER_DTLS_CERTIFICATE_GET_PRIVATE(self); self->priv = priv; priv->x509 = NULL; priv->private_key = NULL; priv->pem = NULL; } static void er_dtls_certificate_finalize(GObject *gobject) { ErDtlsCertificatePrivate *priv = ER_DTLS_CERTIFICATE(gobject)->priv; X509_free(priv->x509); priv->x509 = NULL; EVP_PKEY_free(priv->private_key); priv->private_key = NULL; g_free(priv->pem); priv->pem = NULL; G_OBJECT_CLASS(er_dtls_certificate_parent_class)->finalize(gobject); } static void er_dtls_certificate_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { ErDtlsCertificate *self = ER_DTLS_CERTIFICATE(object); const gchar *pem; switch (prop_id) { case PROP_PEM: pem = g_value_get_string(value); if (pem) { init_from_pem_string(self, pem); } else { init_generated(self); } break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(self, prop_id, pspec); } } static void er_dtls_certificate_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { ErDtlsCertificate *self = ER_DTLS_CERTIFICATE(object); switch (prop_id) { case PROP_PEM: g_return_if_fail(self->priv->pem); g_value_set_string(value, self->priv->pem); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(self, prop_id, pspec); } } static void init_generated(ErDtlsCertificate *self) { ErDtlsCertificatePrivate *priv = self->priv; RSA *rsa; X509_NAME *name = NULL; g_return_if_fail(!priv->x509); g_return_if_fail(!priv->private_key); priv->private_key = EVP_PKEY_new(); if (!priv->private_key) { LOG_WARNING(self, "failed to create private key"); return; } priv->x509 = X509_new(); if (!priv->x509) { LOG_WARNING(self, "failed to create certificate"); EVP_PKEY_free(priv->private_key); priv->private_key = NULL; return; } rsa = RSA_generate_key(2048, RSA_F4, NULL, NULL); if (!rsa) { LOG_WARNING(self, "failed to generate RSA"); EVP_PKEY_free(priv->private_key); priv->private_key = NULL; X509_free(priv->x509); priv->x509 = NULL; return; } if (!EVP_PKEY_assign_RSA(priv->private_key, rsa)) { LOG_WARNING(self, "failed to assign RSA"); RSA_free(rsa); rsa = NULL; EVP_PKEY_free(priv->private_key); priv->private_key = NULL; X509_free(priv->x509); priv->x509 = NULL; return; } rsa = NULL; X509_set_version(priv->x509, 2); ASN1_INTEGER_set(X509_get_serialNumber(priv->x509), 0); X509_gmtime_adj(X509_get_notBefore(priv->x509), 0); X509_gmtime_adj(X509_get_notAfter(priv->x509), 31536000L); /* A year */ X509_set_pubkey(priv->x509, priv->private_key); name = X509_get_subject_name(priv->x509); X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned char*) "SE", -1, -1, 0); X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char*) "OpenWebRTC", -1, -1, 0); X509_set_issuer_name(priv->x509, name); name = NULL; if (!X509_sign(priv->x509, priv->private_key, EVP_sha256())) { LOG_WARNING(self, "failed to sign certificate"); EVP_PKEY_free(priv->private_key); priv->private_key = NULL; X509_free(priv->x509); priv->x509 = NULL; return; } self->priv->pem = _er_dtls_x509_to_pem(priv->x509); } static void init_from_pem_string(ErDtlsCertificate *self, const gchar *pem) { ErDtlsCertificatePrivate *priv = self->priv; BIO *bio; g_return_if_fail(pem); g_return_if_fail(!priv->x509); g_return_if_fail(!priv->private_key); bio = BIO_new_mem_buf((gpointer) pem, -1); g_return_if_fail(bio); priv->x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL); if (!priv->x509) { LOG_WARNING(self, "failed to read certificate from pem string"); return; } (void) BIO_reset(bio); priv->private_key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL); BIO_free(bio); bio = NULL; if (!priv->private_key) { LOG_WARNING(self, "failed to read private key from pem string"); X509_free(priv->x509); priv->x509 = NULL; return; } self->priv->pem = g_strdup(pem); } gchar *_er_dtls_x509_to_pem(gpointer x509) { #define ER_DTLS_BIO_BUFFER_SIZE 4096 BIO *bio; gchar buffer[ER_DTLS_BIO_BUFFER_SIZE] = {0}; gint len; gchar *pem = NULL; bio = BIO_new(BIO_s_mem()); g_return_val_if_fail(bio, NULL); if (!PEM_write_bio_X509(bio, (X509 *) x509)) { g_warn_if_reached(); goto beach; } len = BIO_read(bio, buffer, ER_DTLS_BIO_BUFFER_SIZE); if (!len) { g_warn_if_reached(); goto beach; } pem = g_strndup(buffer, len); beach: BIO_free(bio); return pem; } ErDtlsCertificateInternalCertificate _er_dtls_certificate_get_internal_certificate(ErDtlsCertificate *self) { g_return_val_if_fail(ER_IS_DTLS_CERTIFICATE(self), NULL); return self->priv->x509; } ErDtlsCertificateInternalKey _er_dtls_certificate_get_internal_key(ErDtlsCertificate *self) { g_return_val_if_fail(ER_IS_DTLS_CERTIFICATE(self), NULL); return self->priv->private_key; }
superdump/openwebrtc-gst-plugins
ext/erdtls/src/gsterdtlssrtpenc.c
<filename>ext/erdtls/src/gsterdtlssrtpenc.c /* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gsterdtlssrtpenc.h" #include <stdio.h> static GstStaticPadTemplate rtp_sink_template = GST_STATIC_PAD_TEMPLATE("rtp_sink_%d", GST_PAD_SINK, GST_PAD_REQUEST, GST_STATIC_CAPS("application/x-rtp;application/x-rtcp") ); static GstStaticPadTemplate rtcp_sink_template = GST_STATIC_PAD_TEMPLATE("rtcp_sink_%d", GST_PAD_SINK, GST_PAD_REQUEST, GST_STATIC_CAPS("application/x-rtp;application/x-rtcp") ); static GstStaticPadTemplate data_sink_template = GST_STATIC_PAD_TEMPLATE("data_sink", GST_PAD_SINK, GST_PAD_REQUEST, GST_STATIC_CAPS_ANY ); static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS_ANY ); GST_DEBUG_CATEGORY_STATIC(er_dtls_srtp_enc_debug); #define GST_CAT_DEFAULT er_dtls_srtp_enc_debug #define gst_er_dtls_srtp_enc_parent_class parent_class G_DEFINE_TYPE_WITH_CODE(GstErDtlsSrtpEnc, gst_er_dtls_srtp_enc, GST_TYPE_ER_DTLS_SRTP_BIN, GST_DEBUG_CATEGORY_INIT(er_dtls_srtp_enc_debug, "erdtlssrtpenc", 0, "Ericsson DTLS Decoder")); enum { PROP_0, PROP_IS_CLIENT, NUM_PROPERTIES }; static GParamSpec *properties[NUM_PROPERTIES]; #define DEFAULT_IS_CLIENT FALSE static gboolean transform_enum(GBinding *, const GValue *source_value, GValue *target_value, GEnumClass *); static void gst_er_dtls_srtp_enc_set_property(GObject *, guint prop_id, const GValue *, GParamSpec *); static void gst_er_dtls_srtp_enc_get_property(GObject *, guint prop_id, GValue *, GParamSpec *); static GstPad *add_ghost_pad(GstElement *, const gchar *name, GstPad *, GstPadTemplate *); static GstPad *gst_er_dtls_srtp_enc_request_new_pad(GstElement *, GstPadTemplate *, const gchar *name, const GstCaps *); static void on_key_received(GObject *encoder, GstErDtlsSrtpEnc *); static void gst_er_dtls_srtp_enc_remove_dtls_element(GstErDtlsSrtpBin *); static GstPadProbeReturn remove_dtls_encoder_probe_callback(GstPad *, GstPadProbeInfo *, GstElement *); static void gst_er_dtls_srtp_enc_class_init(GstErDtlsSrtpEncClass *klass) { GObjectClass *gobject_class; GstElementClass *element_class; GstErDtlsSrtpBinClass *dtls_srtp_bin_class; gobject_class = (GObjectClass *) klass; element_class = (GstElementClass *) klass; dtls_srtp_bin_class = (GstErDtlsSrtpBinClass *) klass; gobject_class->set_property = GST_DEBUG_FUNCPTR(gst_er_dtls_srtp_enc_set_property); gobject_class->get_property = GST_DEBUG_FUNCPTR(gst_er_dtls_srtp_enc_get_property); element_class->request_new_pad = GST_DEBUG_FUNCPTR(gst_er_dtls_srtp_enc_request_new_pad); dtls_srtp_bin_class->remove_dtls_element = GST_DEBUG_FUNCPTR(gst_er_dtls_srtp_enc_remove_dtls_element); properties[PROP_IS_CLIENT] = g_param_spec_boolean("is-client", "Is client", "Set to true if the decoder should act as " "client and initiate the handshake", DEFAULT_IS_CLIENT, GST_PARAM_MUTABLE_READY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); g_object_class_install_properties(gobject_class, NUM_PROPERTIES, properties); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&rtp_sink_template)); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&rtcp_sink_template)); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&data_sink_template)); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&src_template)); gst_element_class_set_static_metadata(element_class, "DTLS-SRTP Encoder", "Encoder/Network/DTLS/SRTP", "Encodes SRTP packets with a key received from DTLS", "<NAME> <EMAIL>"); } static void gst_er_dtls_srtp_enc_init(GstErDtlsSrtpEnc *self) { GstElementClass *klass = GST_ELEMENT_GET_CLASS(GST_ELEMENT(self)); static GEnumClass *cipher_enum_class, *auth_enum_class; gboolean ret; /* +--------------------+ +-----------------+ rtp_sink-R-o|rtp_sink rtp_src|o-R-o| | | srtpenc | | | rtcp_sink-R-o|srtcp_sink rtcp_src|o-R-o| | +--------------------+ | funnel |o---src | | +--------------------+ | | data_sink-R-o| erdtlsenc |o---o| | +--------------------+ +-----------------+ */ self->srtp_enc = gst_element_factory_make("srtpenc", "srtp-encoder"); if (!self->srtp_enc) { GST_ERROR_OBJECT(self, "failed to create srtp encoder, is the srtp plugin registered?"); return; } g_return_if_fail(self->srtp_enc); self->bin.dtls_element = gst_element_factory_make("erdtlsenc", "dtls-encoder"); if (!self->bin.dtls_element) { GST_ERROR_OBJECT(self, "failed to create dtls encoder"); return; } self->funnel = gst_element_factory_make("funnel", "funnel"); if (!self->funnel) { GST_ERROR_OBJECT(self, "failed to create funnel"); return; } gst_bin_add_many(GST_BIN(self), self->bin.dtls_element, self->srtp_enc, self->funnel, NULL); ret = gst_element_link(self->bin.dtls_element, self->funnel); g_return_if_fail(ret); add_ghost_pad(GST_ELEMENT(self), "src", gst_element_get_static_pad(self->funnel, "src"), gst_element_class_get_pad_template(klass, "src")); g_signal_connect(self->bin.dtls_element, "on-key-received", G_CALLBACK(on_key_received), self); if (g_once_init_enter(&cipher_enum_class)) { GType type = g_type_from_name("GstSrtpCipherType"); g_assert(type); g_once_init_leave(&cipher_enum_class, g_type_class_peek(type)); } if (g_once_init_enter(&auth_enum_class)) { GType type = g_type_from_name("GstSrtpAuthType"); g_assert(type); g_once_init_leave(&auth_enum_class, g_type_class_peek(type)); } g_object_set(self->srtp_enc, "random-key", TRUE, NULL); g_object_bind_property(G_OBJECT(self), "key", self->srtp_enc, "key", G_BINDING_DEFAULT); g_object_bind_property_full(G_OBJECT(self), "srtp-cipher", self->srtp_enc, "rtp-cipher", G_BINDING_DEFAULT, (GBindingTransformFunc) transform_enum, NULL, cipher_enum_class, NULL); g_object_bind_property_full(G_OBJECT(self), "srtcp-cipher", self->srtp_enc, "rtcp-cipher", G_BINDING_DEFAULT, (GBindingTransformFunc) transform_enum, NULL, cipher_enum_class, NULL); g_object_bind_property_full(G_OBJECT(self), "srtp-auth", self->srtp_enc, "rtp-auth", G_BINDING_DEFAULT, (GBindingTransformFunc) transform_enum, NULL, auth_enum_class, NULL); g_object_bind_property_full(G_OBJECT(self), "srtcp-auth", self->srtp_enc, "rtcp-auth", G_BINDING_DEFAULT, (GBindingTransformFunc) transform_enum, NULL, auth_enum_class, NULL); } static gboolean transform_enum(GBinding *binding, const GValue *source_value, GValue *target_value, GEnumClass *enum_class) { GEnumValue *enum_value; const gchar *nick; nick = g_value_get_string(source_value); g_return_val_if_fail(nick, FALSE); enum_value = g_enum_get_value_by_nick(enum_class, nick); g_return_val_if_fail(enum_value, FALSE); GST_DEBUG_OBJECT(g_binding_get_source(binding), "transforming enum from %s to %d", nick, enum_value->value); g_value_set_enum(target_value, enum_value->value); return TRUE; } static void gst_er_dtls_srtp_enc_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { GstErDtlsSrtpEnc *self = GST_ER_DTLS_SRTP_ENC(object); switch (prop_id) { case PROP_IS_CLIENT: if (self->bin.dtls_element) { g_object_set_property(G_OBJECT(self->bin.dtls_element), "is-client", value); } else { GST_WARNING_OBJECT(self, "tried to set is-client after disabling DTLS"); } break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(self, prop_id, pspec); } } static void gst_er_dtls_srtp_enc_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { GstErDtlsSrtpEnc *self = GST_ER_DTLS_SRTP_ENC(object); switch (prop_id) { case PROP_IS_CLIENT: if (self->bin.dtls_element) { g_object_get_property(G_OBJECT(self->bin.dtls_element), "is-client", value); } else { GST_WARNING_OBJECT(self, "tried to get is-client after disabling DTLS"); } break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(self, prop_id, pspec); } } static GstPad *add_ghost_pad(GstElement *element, const gchar *name, GstPad *target, GstPadTemplate *templ) { GstPad *pad; gboolean ret; pad = gst_ghost_pad_new_from_template(name, target, templ); gst_object_unref(target); target = NULL; ret = gst_pad_set_active(pad, TRUE); g_warn_if_fail(ret); ret = gst_element_add_pad(element, pad); g_warn_if_fail(ret); return pad; } static GstPad *gst_er_dtls_srtp_enc_request_new_pad(GstElement *element, GstPadTemplate *templ, const gchar *name, const GstCaps *caps) { GstErDtlsSrtpEnc *self = GST_ER_DTLS_SRTP_ENC(element); GstElementClass *klass = GST_ELEMENT_GET_CLASS(element); GstPad *target_pad; GstPad *ghost_pad = NULL; guint pad_n; gchar *srtp_src_name; GST_DEBUG_OBJECT(element, "pad requested"); g_return_val_if_fail(templ->direction == GST_PAD_SINK, NULL); g_return_val_if_fail(self->srtp_enc, NULL); if (templ == gst_element_class_get_pad_template(klass, "rtp_sink_%d")) { target_pad = gst_element_get_request_pad(self->srtp_enc, name); g_return_val_if_fail(target_pad, NULL); sscanf(GST_PAD_NAME(target_pad), "rtp_sink_%d", &pad_n); srtp_src_name = g_strdup_printf("rtp_src_%d", pad_n); gst_element_link_pads(self->srtp_enc, srtp_src_name, self->funnel, NULL); g_free(srtp_src_name); ghost_pad = add_ghost_pad(element, name, target_pad, templ); GST_LOG_OBJECT(self, "added rtp sink pad"); } else if (templ == gst_element_class_get_pad_template(klass, "rtcp_sink_%d")) { target_pad = gst_element_get_request_pad(self->srtp_enc, name); g_return_val_if_fail(target_pad, NULL); sscanf(GST_PAD_NAME(target_pad), "rtcp_sink_%d", &pad_n); srtp_src_name = g_strdup_printf("rtcp_src_%d", pad_n); gst_element_link_pads(self->srtp_enc, srtp_src_name, self->funnel, NULL); g_free(srtp_src_name); ghost_pad = add_ghost_pad(element, name, target_pad, templ); GST_LOG_OBJECT(self, "added rtcp sink pad"); } else if (templ == gst_element_class_get_pad_template(klass, "data_sink")) { g_return_val_if_fail(self->bin.dtls_element, NULL); target_pad = gst_element_get_request_pad(self->bin.dtls_element, "sink"); ghost_pad = add_ghost_pad(element, name, target_pad, templ); GST_LOG_OBJECT(self, "added data sink pad"); } else { g_warn_if_reached(); } if (caps && ghost_pad) { g_object_set(ghost_pad, "caps", caps, NULL); } return ghost_pad; } static void on_key_received(GObject *encoder, GstErDtlsSrtpEnc *self) { GstErDtlsSrtpBin *bin = GST_ER_DTLS_SRTP_BIN(self); GstBuffer *buffer = NULL; guint cipher, auth; if (!(bin->key_is_set || bin->srtp_cipher || bin->srtp_auth || bin->srtcp_cipher || bin->srtcp_auth)) { g_object_get(encoder, "encoder-key", &buffer, "srtp-cipher", &cipher, "srtp-auth", &auth, NULL); g_object_set(self->srtp_enc, "rtp-cipher", cipher, "rtcp-cipher", cipher, "rtp-auth", auth, "rtcp-auth", auth, "key", buffer, "random-key", FALSE, NULL); } else { GST_DEBUG_OBJECT(self, "ignoring keys received from DTLS handshake, key struct is set"); } } static void gst_er_dtls_srtp_enc_remove_dtls_element(GstErDtlsSrtpBin *bin) { GstErDtlsSrtpEnc *self = GST_ER_DTLS_SRTP_ENC(bin); GstPad *dtls_sink_pad, *peer_pad; gulong id; guint rtp_cipher = 1, rtcp_cipher = 1, rtp_auth = 1, rtcp_auth = 1; if (!bin->dtls_element) { return; } g_object_get(self->srtp_enc, "rtp-cipher", &rtp_cipher, "rtcp-cipher", &rtcp_cipher, "rtp-auth", &rtp_auth, "rtcp-auth", &rtcp_auth, NULL); if (!rtp_cipher && !rtcp_cipher && !rtp_auth && !rtcp_auth) { g_object_set(self->srtp_enc, "random-key", FALSE, NULL); } dtls_sink_pad = gst_element_get_static_pad(bin->dtls_element, "sink"); if (!dtls_sink_pad) { gst_element_set_state(GST_ELEMENT(bin->dtls_element), GST_STATE_NULL); gst_bin_remove(GST_BIN(self), bin->dtls_element); bin->dtls_element = NULL; return; } peer_pad = gst_pad_get_peer(dtls_sink_pad); g_return_if_fail(peer_pad); gst_object_unref(dtls_sink_pad); dtls_sink_pad = NULL; id = gst_pad_add_probe(peer_pad, GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM, (GstPadProbeCallback) remove_dtls_encoder_probe_callback, bin->dtls_element, NULL); g_return_if_fail(id); bin->dtls_element = NULL; gst_pad_push_event(peer_pad, gst_event_new_custom(GST_EVENT_CUSTOM_DOWNSTREAM, gst_structure_new_empty("dummy"))); gst_object_unref(peer_pad); } static GstPadProbeReturn remove_dtls_encoder_probe_callback(GstPad *pad, GstPadProbeInfo *info, GstElement *element) { gst_pad_remove_probe(pad, GST_PAD_PROBE_INFO_ID(info)); gst_element_set_state(GST_ELEMENT(element), GST_STATE_NULL); gst_bin_remove(GST_BIN(GST_ELEMENT_PARENT(element)), element); return GST_PAD_PROBE_OK; }
superdump/openwebrtc-gst-plugins
ext/erdtls/src/erdtlsconnection.c
<gh_stars>0 /* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "erdtlsconnection.h" #include "erdtlsagent.h" #include "erdtlscertificate.h" #include "erdtlscommon.h" #ifdef __APPLE__ # define __AVAILABILITYMACROS__ # define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER #endif #include <openssl/err.h> #include <openssl/ssl.h> #if ER_DTLS_USE_GST_LOG GST_DEBUG_CATEGORY_STATIC(er_dtls_connection_debug); # define GST_CAT_DEFAULT er_dtls_connection_debug G_DEFINE_TYPE_WITH_CODE(ErDtlsConnection, er_dtls_connection, G_TYPE_OBJECT, GST_DEBUG_CATEGORY_INIT(er_dtls_connection_debug, "erdtlsconnection", 0, "Ericsson DTLS Connection")); #else G_DEFINE_TYPE(ErDtlsConnection, er_dtls_connection, G_TYPE_OBJECT); #endif #define ER_DTLS_CONNECTION_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), ER_TYPE_DTLS_CONNECTION, ErDtlsConnectionPrivate)) #define SRTP_KEY_LEN 16 #define SRTP_SALT_LEN 14 enum { SIGNAL_ON_ENCODER_KEY, SIGNAL_ON_DECODER_KEY, SIGNAL_ON_PEER_CERTIFICATE, NUM_SIGNALS }; static guint signals[NUM_SIGNALS]; enum { PROP_0, PROP_AGENT, NUM_PROPERTIES }; static GParamSpec *properties[NUM_PROPERTIES]; static int connection_ex_index; struct _ErDtlsConnectionPrivate { SSL *ssl; BIO *bio; GThread *thread; gboolean is_client; gboolean is_alive; gboolean keys_exported; gboolean timeout_set; GMutex mutex; GCond condition; gpointer bio_buffer; gint bio_buffer_len; gint bio_buffer_offset; GClosure *send_closure; }; static void er_dtls_connection_finalize(GObject *gobject); static void er_dtls_connection_set_property(GObject *, guint prop_id, const GValue *, GParamSpec *); static void log_state(ErDtlsConnection *, const gchar *str); static gpointer connection_timeout_thread_func(ErDtlsConnection *); static void export_srtp_keys(ErDtlsConnection *); static void openssl_poll(ErDtlsConnection *); static int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx); static BIO_METHOD* BIO_s_er_dtls_connection(); static int bio_method_write(BIO *, const char *data, int size); static int bio_method_read(BIO *, char *out_buffer, int size); static long bio_method_ctrl(BIO *, int cmd, long arg1, void *arg2); static int bio_method_new(BIO *); static int bio_method_free(BIO *); static void er_dtls_connection_class_init(ErDtlsConnectionClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS(klass); g_type_class_add_private(klass, sizeof(ErDtlsConnectionPrivate)); gobject_class->set_property = er_dtls_connection_set_property; connection_ex_index = SSL_get_ex_new_index(0, "erdtlsagent connection index", NULL, NULL, NULL); signals[SIGNAL_ON_DECODER_KEY] = g_signal_new("on-decoder-key", G_TYPE_FROM_CLASS(klass), G_SIGNAL_RUN_LAST, 0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 3, G_TYPE_POINTER, G_TYPE_UINT, G_TYPE_UINT); signals[SIGNAL_ON_ENCODER_KEY] = g_signal_new("on-encoder-key", G_TYPE_FROM_CLASS(klass), G_SIGNAL_RUN_LAST, 0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 3, G_TYPE_POINTER, G_TYPE_UINT, G_TYPE_UINT); signals[SIGNAL_ON_PEER_CERTIFICATE] = g_signal_new("on-peer-certificate", G_TYPE_FROM_CLASS(klass), G_SIGNAL_RUN_LAST, 0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 1, G_TYPE_STRING); properties[PROP_AGENT] = g_param_spec_object("agent", "ERDtlsAgent", "Agent to use in creation of the connection", ER_TYPE_DTLS_AGENT, G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS); g_object_class_install_properties(gobject_class, NUM_PROPERTIES, properties); _er_dtls_init_openssl(); gobject_class->finalize = er_dtls_connection_finalize; } static void er_dtls_connection_init(ErDtlsConnection *self) { ErDtlsConnectionPrivate *priv = ER_DTLS_CONNECTION_GET_PRIVATE(self); self->priv = priv; priv->ssl = NULL; priv->bio = NULL; priv->thread = NULL; priv->send_closure = NULL; priv->is_client = FALSE; priv->is_alive = TRUE; priv->keys_exported = FALSE; priv->timeout_set = FALSE; priv->bio_buffer = NULL; priv->bio_buffer_len = 0; priv->bio_buffer_offset = 0; g_mutex_init(&priv->mutex); g_cond_init(&priv->condition); } static void er_dtls_connection_finalize(GObject *gobject) { ErDtlsConnection *self = ER_DTLS_CONNECTION(gobject); ErDtlsConnectionPrivate *priv = self->priv; SSL_free(priv->ssl); priv->ssl = NULL; if (priv->send_closure) { g_closure_unref(priv->send_closure); priv->send_closure = NULL; } g_mutex_clear(&priv->mutex); g_cond_clear(&priv->condition); LOG_DEBUG(self, "finalized"); G_OBJECT_CLASS(er_dtls_connection_parent_class)->finalize(gobject); } static void er_dtls_connection_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { ErDtlsConnection *self = ER_DTLS_CONNECTION(object); ErDtlsAgent *agent; ErDtlsConnectionPrivate *priv = self->priv; SSL_CTX *ssl_context; switch (prop_id) { case PROP_AGENT: g_return_if_fail(!priv->ssl); agent = ER_DTLS_AGENT(g_value_get_object(value)); g_return_if_fail(ER_IS_DTLS_AGENT(agent)); ssl_context = _er_dtls_agent_peek_context(agent); priv->ssl = SSL_new(ssl_context); g_return_if_fail(priv->ssl); priv->bio = BIO_new(BIO_s_er_dtls_connection()); g_return_if_fail(priv->bio); priv->bio->ptr = self; SSL_set_bio(priv->ssl, priv->bio, priv->bio); SSL_set_verify(priv->ssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, openssl_verify_callback); SSL_set_ex_data(priv->ssl, connection_ex_index, self); log_state(self, "connection created"); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(self, prop_id, pspec); } } void er_dtls_connection_start(ErDtlsConnection *self, gboolean is_client) { g_return_if_fail(ER_IS_DTLS_CONNECTION(self)); ErDtlsConnectionPrivate *priv = self->priv; g_return_if_fail(priv->send_closure); g_return_if_fail(priv->ssl); g_return_if_fail(priv->bio); LOG_TRACE(self, "locking @ start"); g_mutex_lock(&priv->mutex); LOG_TRACE(self, "locked @ start"); priv->keys_exported = FALSE; priv->is_client = is_client; if (priv->is_client) { SSL_set_connect_state(priv->ssl); } else { SSL_set_accept_state(priv->ssl); } log_state(self, "initial state set"); openssl_poll(self); log_state(self, "first poll done"); priv->thread = NULL; LOG_TRACE(self, "unlocking @ start"); g_mutex_unlock(&priv->mutex); } void er_dtls_connection_start_timeout(ErDtlsConnection *self) { g_return_if_fail(ER_IS_DTLS_CONNECTION(self)); ErDtlsConnectionPrivate *priv = self->priv; GError *error = NULL; gchar *thread_name = g_strdup_printf("connection_thread_%p", self); LOG_TRACE(self, "locking @ start_timeout"); g_mutex_lock(&priv->mutex); LOG_TRACE(self, "locked @ start_timeout"); LOG_INFO(self, "starting connection timeout"); priv->thread = g_thread_try_new(thread_name, (GThreadFunc) connection_timeout_thread_func, self, &error); if (error) { LOG_WARNING(self, "error creating connection thread: %s (%d)", error->message, error->code); g_clear_error(&error); } g_free(thread_name); LOG_TRACE(self, "unlocking @ start_timeout"); g_mutex_unlock(&priv->mutex); } void er_dtls_connection_stop(ErDtlsConnection *self) { g_return_if_fail(ER_IS_DTLS_CONNECTION(self)); g_return_if_fail(self->priv->ssl); g_return_if_fail(self->priv->bio); LOG_DEBUG(self, "stopping connection"); LOG_TRACE(self, "locking @ stop"); g_mutex_lock(&self->priv->mutex); LOG_TRACE(self, "locked @ stop"); self->priv->is_alive = FALSE; LOG_TRACE(self, "signaling @ stop"); g_cond_signal(&self->priv->condition); LOG_TRACE(self, "signaled @ stop"); LOG_TRACE(self, "unlocking @ stop"); g_mutex_unlock(&self->priv->mutex); LOG_DEBUG(self, "stopped connection"); } void er_dtls_connection_close(ErDtlsConnection *self) { g_return_if_fail(ER_IS_DTLS_CONNECTION(self)); g_return_if_fail(self->priv->ssl); g_return_if_fail(self->priv->bio); LOG_DEBUG(self, "closing connection"); LOG_TRACE(self, "locking @ close"); g_mutex_lock(&self->priv->mutex); LOG_TRACE(self, "locked @ close"); if (self->priv->is_alive) { self->priv->is_alive = FALSE; g_cond_signal(&self->priv->condition); } LOG_TRACE(self, "unlocking @ close"); g_mutex_unlock(&self->priv->mutex); if (self->priv->thread) { g_thread_join(self->priv->thread); self->priv->thread = NULL; } LOG_DEBUG(self, "closed connection"); } void er_dtls_connection_set_send_callback(ErDtlsConnection *self, GClosure *closure) { g_return_if_fail(ER_IS_DTLS_CONNECTION(self)); LOG_TRACE(self, "locking @ set_send_callback"); g_mutex_lock(&self->priv->mutex); LOG_TRACE(self, "locked @ set_send_callback"); self->priv->send_closure = closure; if (closure && G_CLOSURE_NEEDS_MARSHAL(closure)) { g_closure_set_marshal(closure, g_cclosure_marshal_generic); } LOG_TRACE(self, "unlocking @ set_send_callback"); g_mutex_unlock(&self->priv->mutex); } gint er_dtls_connection_process(ErDtlsConnection *self, gpointer data, gint len) { g_return_val_if_fail(ER_IS_DTLS_CONNECTION(self), 0); ErDtlsConnectionPrivate *priv = self->priv; gint result; g_return_val_if_fail(self->priv->ssl, 0); g_return_val_if_fail(self->priv->bio, 0); g_return_val_if_fail(!priv->bio_buffer, 0); LOG_TRACE(self, "locking @ process"); g_mutex_lock(&priv->mutex); LOG_TRACE(self, "locked @ process"); priv->bio_buffer = data; priv->bio_buffer_len = len; priv->bio_buffer_offset = 0; log_state(self, "process start"); if (SSL_want_write(priv->ssl)) { openssl_poll(self); log_state(self, "process want write, after poll"); } result = SSL_read(priv->ssl, data, len); log_state(self, "process after read"); openssl_poll(self); log_state(self, "process after poll"); LOG_DEBUG(self, "read result: %d", result); LOG_TRACE(self, "unlocking @ process"); g_mutex_unlock(&priv->mutex); return result; } gint er_dtls_connection_send(ErDtlsConnection *self, gpointer data, gint len) { g_return_val_if_fail(ER_IS_DTLS_CONNECTION(self), 0); int ret = 0; g_return_val_if_fail(self->priv->ssl, 0); g_return_val_if_fail(self->priv->bio, 0); LOG_TRACE(self, "locking @ send"); g_mutex_lock(&self->priv->mutex); LOG_TRACE(self, "locked @ send"); if (SSL_is_init_finished(self->priv->ssl)) { ret = SSL_write(self->priv->ssl, data, len); LOG_DEBUG(self, "data sent: input was %d B, output is %d B", len, ret); } else { LOG_WARNING(self, "tried to send data before handshake was complete"); ret = 0; } LOG_TRACE(self, "unlocking @ send"); g_mutex_unlock(&self->priv->mutex); return ret; } /* ###### ####### ## ## ## ## ## ## ### ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## #### ## ## ## ## ## ### ###### ####### ## ## */ static void log_state(ErDtlsConnection *self, const gchar *str) { ErDtlsConnectionPrivate *priv = self->priv; guint states = 0; states |= (!!SSL_is_init_finished(priv->ssl) << 0); states |= (!!SSL_in_init(priv->ssl) << 4); states |= (!!SSL_in_before(priv->ssl) << 8); states |= (!!SSL_in_connect_init(priv->ssl) << 12); states |= (!!SSL_in_accept_init(priv->ssl) << 16); states |= (!!SSL_want_write(priv->ssl) << 20); states |= (!!SSL_want_read(priv->ssl) << 24); LOG_LOG(self, "%s: role=%s buf=(%d,%p:%d/%d) %x|%x %s", str, priv->is_client ? "client" : "server", pqueue_size(priv->ssl->d1->sent_messages), priv->bio_buffer, priv->bio_buffer_offset, priv->bio_buffer_len, states, SSL_get_state(priv->ssl), SSL_state_string_long(priv->ssl)); } static gpointer connection_timeout_thread_func(ErDtlsConnection *self) { ErDtlsConnectionPrivate *priv = self->priv; struct timeval timeout; gint64 end_time, wait_time; gint ret; while (priv->is_alive) { LOG_TRACE(self, "locking @ timeout"); g_mutex_lock(&priv->mutex); LOG_TRACE(self, "locked @ timeout"); if (DTLSv1_get_timeout(priv->ssl, &timeout)) { wait_time = timeout.tv_sec * G_USEC_PER_SEC + timeout.tv_usec; if (wait_time) { LOG_DEBUG(self, "waiting for %" G_GINT64_FORMAT " usec", wait_time); end_time = g_get_monotonic_time() + wait_time; LOG_TRACE(self, "wait @ timeout"); g_cond_wait_until(&priv->condition, &priv->mutex, end_time); LOG_TRACE(self, "continued @ timeout"); } ret = DTLSv1_handle_timeout(priv->ssl); LOG_DEBUG(self, "handle timeout returned %d, is_alive: %d", ret, priv->is_alive); if (ret < 0) { LOG_TRACE(self, "unlocking @ timeout failed"); g_mutex_unlock(&priv->mutex); break; /* self failed after DTLS1_TMO_ALERT_COUNT (12) attempts */ } if (ret > 0) { log_state(self, "handling timeout before poll"); openssl_poll(self); log_state(self, "handling timeout after poll"); } } else { LOG_DEBUG(self, "waiting indefinitely"); priv->timeout_set = FALSE; while (!priv->timeout_set && priv->is_alive) { LOG_TRACE(self, "wait @ timeout"); g_cond_wait(&priv->condition, &priv->mutex); } LOG_TRACE(self, "continued @ timeout"); } LOG_TRACE(self, "unlocking @ timeout"); g_mutex_unlock(&priv->mutex); } log_state(self, "timeout thread exiting"); return NULL; } static void export_srtp_keys(ErDtlsConnection *self) { typedef struct { guint8 v[SRTP_KEY_LEN]; } Key; typedef struct { guint8 v[SRTP_SALT_LEN]; } Salt; struct { Key client_key; Key server_key; Salt client_salt; Salt server_salt; } exported_keys; struct { Key key; Salt salt; } client_key, server_key; SRTP_PROTECTION_PROFILE *profile; ErDtlsSrtpCipher cipher; ErDtlsSrtpAuth auth; gint success; static gchar export_string[] = "EXTRACTOR-dtls_srtp"; success = SSL_export_keying_material(self->priv->ssl, (gpointer) &exported_keys, 60, export_string, strlen(export_string), NULL, 0, 0); if (!success) { LOG_WARNING(self, "failed to export srtp keys"); return; } profile = SSL_get_selected_srtp_profile(self->priv->ssl); LOG_INFO(self, "keys received, profile is %s", profile->name); switch (profile->id) { case SRTP_AES128_CM_SHA1_80: cipher = ER_DTLS_SRTP_CIPHER_AES_128_ICM; auth = ER_DTLS_SRTP_AUTH_HMAC_SHA1_80; break; case SRTP_AES128_CM_SHA1_32: cipher = ER_DTLS_SRTP_CIPHER_AES_128_ICM; auth = ER_DTLS_SRTP_AUTH_HMAC_SHA1_32; break; default: LOG_WARNING(self, "invalid crypto suite set by handshake"); goto beach; } client_key.key = exported_keys.client_key; server_key.key = exported_keys.server_key; client_key.salt = exported_keys.client_salt; server_key.salt = exported_keys.server_salt; if (self->priv->is_client) { g_signal_emit(self, signals[SIGNAL_ON_ENCODER_KEY], 0, &client_key, cipher, auth); g_signal_emit(self, signals[SIGNAL_ON_DECODER_KEY], 0, &server_key, cipher, auth); } else { g_signal_emit(self, signals[SIGNAL_ON_ENCODER_KEY], 0, &server_key, cipher, auth); g_signal_emit(self, signals[SIGNAL_ON_DECODER_KEY], 0, &client_key, cipher, auth); } beach: self->priv->keys_exported = TRUE; } static void openssl_poll(ErDtlsConnection *self) { int ret; char buf[512]; int error; log_state(self, "poll: before handshake"); ret = SSL_do_handshake(self->priv->ssl); log_state(self, "poll: after handshake"); if (ret == 1) { if (!self->priv->keys_exported) { LOG_INFO(self, "handshake just completed successfully, exporting keys"); export_srtp_keys(self); } else { LOG_INFO(self, "handshake is completed"); } return; } else { if (ret == 0) { LOG_DEBUG(self, "do_handshake encountered EOF"); } else if (ret == -1) { LOG_WARNING(self, "do_handshake encountered BIO error"); } else { LOG_DEBUG(self, "do_handshake returned %d", ret); } } error = SSL_get_error(self->priv->ssl, ret); switch (error) { case SSL_ERROR_NONE: LOG_WARNING(self, "no error, handshake should be done"); break; case SSL_ERROR_SSL: LOG_LOG(self, "SSL error %d: %s", error, ERR_error_string(ERR_get_error(), buf)); break; case SSL_ERROR_WANT_READ: LOG_LOG(self, "SSL wants read"); break; case SSL_ERROR_WANT_WRITE: LOG_LOG(self, "SSL wants write"); break; case SSL_ERROR_SYSCALL: { LOG_LOG(self, "SSL syscall (error) : %lu", ERR_get_error()); break; } default: LOG_WARNING(self, "Unknown SSL error: %d, ret: %d", error, ret); } } static int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) { ErDtlsConnection *self; SSL *ssl; BIO *bio; gchar *pem = NULL; gboolean accepted = FALSE; ssl = X509_STORE_CTX_get_ex_data(x509_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); self = SSL_get_ex_data(ssl, connection_ex_index); g_return_val_if_fail(ER_IS_DTLS_CONNECTION(self), FALSE); pem = _er_dtls_x509_to_pem(x509_ctx->cert); if (!pem) { LOG_WARNING(self, "failed to convert received certificate to pem format"); } else { bio = BIO_new(BIO_s_mem()); if (bio) { gchar buffer[2048]; gint len; len = X509_NAME_print_ex(bio, X509_get_subject_name(x509_ctx->cert), 1, XN_FLAG_MULTILINE); BIO_read(bio, buffer, len); buffer[len] = '\0'; LOG_DEBUG(self, "Peer certificate received:\n%s", buffer); BIO_free(bio); } else { LOG_DEBUG(self, "failed to create certificate print membio"); } g_signal_emit(self, signals[SIGNAL_ON_PEER_CERTIFICATE], 0, pem, &accepted); g_free(pem); } return accepted; } /* ######## #### ####### ## ## ## ## ## ## ## ## ## ## ######## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## #### ####### */ static BIO_METHOD custom_bio_methods = { BIO_TYPE_BIO, "stream", bio_method_write, bio_method_read, NULL, NULL, bio_method_ctrl, bio_method_new, bio_method_free, NULL, }; static BIO_METHOD* BIO_s_er_dtls_connection() { return &custom_bio_methods; } static int bio_method_write(BIO *bio, const char *data, int size) { ErDtlsConnection *self = ER_DTLS_CONNECTION(bio->ptr); LOG_LOG(self, "BIO: writing %d", size); if (self->priv->send_closure) { GValue values[3] = { G_VALUE_INIT }; g_value_init(&values[0], ER_TYPE_DTLS_CONNECTION); g_value_set_object(&values[0], self); g_value_init(&values[1], G_TYPE_POINTER); g_value_set_pointer(&values[1], (gpointer) data); g_value_init(&values[2], G_TYPE_INT); g_value_set_int(&values[2], size); g_closure_invoke(self->priv->send_closure, NULL, 3, values, NULL); } return size; } static int bio_method_read(BIO *bio, char *out_buffer, int size) { ErDtlsConnection *self = ER_DTLS_CONNECTION(bio->ptr); ErDtlsConnectionPrivate *priv = self->priv; guint internal_size; gint copy_size; internal_size = priv->bio_buffer_len - priv->bio_buffer_offset; if (!priv->bio_buffer) { LOG_LOG(self, "BIO: EOF"); return 0; } if (!out_buffer || size <= 0) { LOG_WARNING(self, "BIO: read got invalid arguments"); if (internal_size) { BIO_set_retry_read(bio); } return internal_size; } if (size > internal_size) { copy_size = internal_size; } else { copy_size = size; } LOG_DEBUG(self, "reading %d/%d bytes %d at offset %d, output buff size is %d", copy_size, priv->bio_buffer_len, internal_size, priv->bio_buffer_offset, size); memcpy(out_buffer, priv->bio_buffer + priv->bio_buffer_offset, copy_size); priv->bio_buffer_offset += copy_size; if (priv->bio_buffer_len == priv->bio_buffer_offset) { priv->bio_buffer = NULL; } return copy_size; } static long bio_method_ctrl(BIO *bio, int cmd, long arg1, void *arg2) { ErDtlsConnection *self = ER_DTLS_CONNECTION(bio->ptr); ErDtlsConnectionPrivate *priv = self->priv; switch (cmd) { case BIO_CTRL_DGRAM_SET_RECV_TIMEOUT: LOG_LOG(self, "BIO: Timeout set"); priv->timeout_set = TRUE; g_cond_signal(&priv->condition); return 1; case BIO_CTRL_RESET: priv->bio_buffer = NULL; priv->bio_buffer_len = 0; priv->bio_buffer_offset = 0; LOG_LOG(self, "BIO: EOF reset"); return 1; case BIO_CTRL_EOF: { gint eof = !(priv->bio_buffer_len - priv->bio_buffer_offset); LOG_LOG(self, "BIO: EOF query returned %d", eof); return eof; } case BIO_CTRL_WPENDING: LOG_LOG(self, "BIO: pending write"); return 1; case BIO_CTRL_PENDING: { gint pending = priv->bio_buffer_len - priv->bio_buffer_offset; LOG_LOG(self, "BIO: %d bytes pending", pending); return pending; } case BIO_CTRL_FLUSH: LOG_LOG(self, "BIO: flushing"); return 1; case BIO_CTRL_DGRAM_QUERY_MTU: LOG_DEBUG(self, "BIO: MTU query, returning 0..."); return 0; case BIO_CTRL_DGRAM_MTU_EXCEEDED: LOG_WARNING(self, "BIO: MTU exceeded"); return 0; default: LOG_LOG(self, "BIO: unhandled ctrl, %d", cmd); return 0; } } static int bio_method_new(BIO *bio) { LOG_LOG(NULL, "BIO: new"); bio->shutdown = 0; bio->init = 1; return 1; } static int bio_method_free(BIO *bio) { if (!bio) { LOG_LOG(NULL, "BIO free called with null bio"); return 0; } LOG_LOG(ER_DTLS_CONNECTION(bio->ptr), "BIO free"); return 0; }
superdump/openwebrtc-gst-plugins
ext/erdtls/src/gsterdtlssrtpdemux.c
<filename>ext/erdtls/src/gsterdtlssrtpdemux.c /* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gsterdtlssrtpdemux.h" #define PACKET_IS_DTLS(b) (b > 0x13 && b < 0x40) #define PACKET_IS_RTP(b) (b > 0x7f && b < 0xc0) static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS_ANY ); static GstStaticPadTemplate rtp_src_template = GST_STATIC_PAD_TEMPLATE("rtp_src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS( "application/x-rtp;" "application/x-rtcp;" "application/x-srtp;" "application/x-srtcp") ); static GstStaticPadTemplate dtls_src_template = GST_STATIC_PAD_TEMPLATE("dtls_src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS("application/x-dtls") ); GST_DEBUG_CATEGORY_STATIC(er_er_dtls_srtp_demux_debug); #define GST_CAT_DEFAULT er_er_dtls_srtp_demux_debug #define gst_er_dtls_srtp_demux_parent_class parent_class G_DEFINE_TYPE_WITH_CODE(GstErDtlsSrtpDemux, gst_er_dtls_srtp_demux, GST_TYPE_ELEMENT, GST_DEBUG_CATEGORY_INIT(er_er_dtls_srtp_demux_debug, "erdtlssrtpdemux", 0, "Ericsson DTLS SRTP Demultiplexer")); static GstFlowReturn sink_chain(GstPad *, GstObject *self, GstBuffer *); static void gst_er_dtls_srtp_demux_class_init(GstErDtlsSrtpDemuxClass *klass) { GstElementClass *element_class; element_class = (GstElementClass *) klass; gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&sink_template)); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&rtp_src_template)); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&dtls_src_template)); gst_element_class_set_static_metadata(element_class, "DTLS SRTP Demultiplexer", "DTLS/SRTP/Demux", "Demultiplexes DTLS and SRTP packets", "<NAME> <EMAIL>"); } static void gst_er_dtls_srtp_demux_init(GstErDtlsSrtpDemux *self) { GstPad *sink; sink = gst_pad_new_from_static_template(&sink_template, "sink"); self->rtp_src = gst_pad_new_from_static_template(&rtp_src_template, "rtp_src"); self->dtls_src = gst_pad_new_from_static_template(&dtls_src_template, "dtls_src"); g_return_if_fail(sink); g_return_if_fail(self->rtp_src); g_return_if_fail(self->dtls_src); gst_pad_set_chain_function(sink, GST_DEBUG_FUNCPTR(sink_chain)); gst_element_add_pad(GST_ELEMENT(self), sink); gst_element_add_pad(GST_ELEMENT(self), self->rtp_src); gst_element_add_pad(GST_ELEMENT(self), self->dtls_src); } static GstFlowReturn sink_chain(GstPad *pad, GstObject *parent, GstBuffer *buffer) { GstErDtlsSrtpDemux *self = GST_ER_DTLS_SRTP_DEMUX(parent); guint8 first_byte; if (gst_buffer_get_size(buffer) == 0) { GST_LOG_OBJECT(self, "received buffer with size 0"); gst_buffer_unref(buffer); return GST_FLOW_OK; } if (gst_buffer_extract(buffer, 0, &first_byte, 1) != 1) { GST_WARNING_OBJECT(self, "could not extract first byte from buffer"); gst_buffer_unref(buffer); return GST_FLOW_OK; } if (PACKET_IS_DTLS(first_byte)) { GST_LOG_OBJECT(self, "pushing dtls packet"); return gst_pad_push(self->dtls_src, buffer); } if (PACKET_IS_RTP(first_byte)) { GST_LOG_OBJECT(self, "pushing rtp packet"); return gst_pad_push(self->rtp_src, buffer); } GST_WARNING_OBJECT(self, "received invalid buffer: %x", first_byte); gst_buffer_unref(buffer); return GST_FLOW_OK; }
superdump/openwebrtc-gst-plugins
ext/erdtls/src/gsterdtlsenc.c
/* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gsterdtlsenc.h" #include "gsterdtlsdec.h" static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE("sink", GST_PAD_SINK, GST_PAD_REQUEST, GST_STATIC_CAPS_ANY ); static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS("application/x-dtls") ); GST_DEBUG_CATEGORY_STATIC(er_dtls_enc_debug); #define GST_CAT_DEFAULT er_dtls_enc_debug #define gst_er_dtls_enc_parent_class parent_class G_DEFINE_TYPE_WITH_CODE(GstErDtlsEnc, gst_er_dtls_enc, GST_TYPE_ELEMENT, GST_DEBUG_CATEGORY_INIT(er_dtls_enc_debug, "erdtlsenc", 0, "Ericsson DTLS Encoder")); enum { SIGNAL_ON_KEY_RECEIVED, NUM_SIGNALS }; static guint signals[NUM_SIGNALS]; enum { PROP_0, PROP_CONNECTION_ID, PROP_IS_CLIENT, PROP_ENCODER_KEY, PROP_SRTP_CIPHER, PROP_SRTP_AUTH, NUM_PROPERTIES }; static GParamSpec *properties[NUM_PROPERTIES]; #define DEFAULT_CONNECTION_ID NULL #define DEFAULT_IS_CLIENT FALSE #define DEFAULT_ENCODER_KEY NULL #define DEFAULT_SRTP_CIPHER 0 #define DEFAULT_SRTP_AUTH 0 #define INITIAL_QUEUE_SIZE 64 static void gst_er_dtls_enc_finalize(GObject *); static void gst_er_dtls_enc_set_property(GObject *, guint prop_id, const GValue *, GParamSpec *); static void gst_er_dtls_enc_get_property(GObject *, guint prop_id, GValue *, GParamSpec *); static GstStateChangeReturn gst_er_dtls_enc_change_state(GstElement *, GstStateChange); static GstPad *gst_er_dtls_enc_request_new_pad(GstElement *, GstPadTemplate *, const gchar *name, const GstCaps *); static gboolean src_activate_mode(GstPad *, GstObject *, GstPadMode, gboolean active); static void src_task_loop(GstPad *); static GstFlowReturn sink_chain(GstPad *, GstObject *, GstBuffer *); static void on_key_received(ErDtlsConnection *, gpointer key, guint cipher, guint auth, GstErDtlsEnc *); static void on_send_data(ErDtlsConnection *, gconstpointer data, gint length, GstErDtlsEnc *); static void gst_er_dtls_enc_class_init(GstErDtlsEncClass *klass) { GObjectClass *gobject_class; GstElementClass *element_class; gobject_class = (GObjectClass *) klass; element_class = (GstElementClass *) klass; gobject_class->finalize = GST_DEBUG_FUNCPTR(gst_er_dtls_enc_finalize); gobject_class->set_property = GST_DEBUG_FUNCPTR(gst_er_dtls_enc_set_property); gobject_class->get_property = GST_DEBUG_FUNCPTR(gst_er_dtls_enc_get_property); element_class->change_state = GST_DEBUG_FUNCPTR(gst_er_dtls_enc_change_state); element_class->request_new_pad = GST_DEBUG_FUNCPTR(gst_er_dtls_enc_request_new_pad); signals[SIGNAL_ON_KEY_RECEIVED] = g_signal_new("on-key-received", G_TYPE_FROM_CLASS(klass), G_SIGNAL_RUN_LAST, 0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 0); properties[PROP_CONNECTION_ID] = g_param_spec_string("connection-id", "Connection id", "Every encoder/decoder pair should have the same, unique, connection-id", DEFAULT_CONNECTION_ID, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); properties[PROP_IS_CLIENT] = g_param_spec_boolean("is-client", "Is client", "Set to true if the decoder should act as" "client and initiate the handshake", DEFAULT_IS_CLIENT, GST_PARAM_MUTABLE_READY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); properties[PROP_ENCODER_KEY] = g_param_spec_boxed("encoder-key", "Encoder key", "Master key that should be used by the SRTP encoder", GST_TYPE_BUFFER, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); properties[PROP_SRTP_CIPHER] = g_param_spec_uint("srtp-cipher", "SRTP cipher", "The SRTP cipher selected in the DTLS handshake. " "The value will be set to an ErDtlsSrtpCipher.", 0, ER_DTLS_SRTP_CIPHER_AES_128_ICM, DEFAULT_SRTP_CIPHER, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); properties[PROP_SRTP_AUTH] = g_param_spec_uint("srtp-auth", "SRTP authentication", "The SRTP authentication selected in the DTLS handshake. " "The value will be set to an ErDtlsSrtpAuth.", 0, ER_DTLS_SRTP_AUTH_HMAC_SHA1_80, DEFAULT_SRTP_AUTH, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); g_object_class_install_properties(gobject_class, NUM_PROPERTIES, properties); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&src_template)); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&sink_template)); gst_element_class_set_static_metadata(element_class, "DTLS Encoder", "Encoder/Network/DTLS", "Encodes packets with DTLS", "<NAME> <EMAIL>"); } static void gst_er_dtls_enc_init(GstErDtlsEnc *self) { self->connection_id = NULL; self->connection = NULL; self->is_client = DEFAULT_IS_CLIENT; self->encoder_key = NULL; self->srtp_cipher = DEFAULT_SRTP_CIPHER; self->srtp_auth = DEFAULT_SRTP_AUTH; self->queue = g_ptr_array_sized_new(INITIAL_QUEUE_SIZE); g_mutex_init(&self->queue_lock); g_cond_init(&self->queue_cond_add); self->src = gst_pad_new_from_static_template(&src_template, "src"); g_return_if_fail(self->src); gst_pad_set_activatemode_function(self->src, GST_DEBUG_FUNCPTR(src_activate_mode)); gst_element_add_pad(GST_ELEMENT(self), self->src); } static void gst_er_dtls_enc_finalize(GObject *object) { GstErDtlsEnc *self = GST_ER_DTLS_ENC(object); if (self->encoder_key) { gst_buffer_unref(self->encoder_key); self->encoder_key = NULL; } g_mutex_lock(&self->queue_lock); g_ptr_array_set_free_func(self->queue, (GDestroyNotify) gst_buffer_unref); g_ptr_array_unref(self->queue); self->queue = NULL; g_mutex_unlock(&self->queue_lock); g_mutex_clear(&self->queue_lock); g_cond_clear(&self->queue_cond_add); GST_LOG_OBJECT(self, "finalized"); G_OBJECT_CLASS(parent_class)->finalize(object); } static void gst_er_dtls_enc_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { GstErDtlsEnc *self = GST_ER_DTLS_ENC(object); switch (prop_id) { case PROP_CONNECTION_ID: self->connection_id = g_value_dup_string(value); break; case PROP_IS_CLIENT: self->is_client = g_value_get_boolean(value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(self, prop_id, pspec); } } static void gst_er_dtls_enc_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { GstErDtlsEnc *self = GST_ER_DTLS_ENC(object); switch (prop_id) { case PROP_CONNECTION_ID: g_value_set_string(value, self->connection_id); break; case PROP_IS_CLIENT: g_value_set_boolean(value, self->is_client); break; case PROP_ENCODER_KEY: g_value_set_boxed(value, self->encoder_key); break; case PROP_SRTP_CIPHER: g_value_set_uint(value, self->srtp_cipher); break; case PROP_SRTP_AUTH: g_value_set_uint(value, self->srtp_auth); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(self, prop_id, pspec); } } static GstStateChangeReturn gst_er_dtls_enc_change_state(GstElement *element, GstStateChange transition) { GstErDtlsEnc *self = GST_ER_DTLS_ENC(element); GstStateChangeReturn ret; switch (transition) { case GST_STATE_CHANGE_NULL_TO_READY: if (self->connection_id) { self->connection = gst_er_dtls_dec_fetch_connection(self->connection_id); if (!self->connection) { GST_WARNING_OBJECT(self, "invalid connection id: '%s', connection not found or already in use", self->connection_id); return GST_STATE_CHANGE_FAILURE; } g_signal_connect_object(self->connection, "on-encoder-key", G_CALLBACK(on_key_received), self, 0); er_dtls_connection_set_send_callback(self->connection, g_cclosure_new(G_CALLBACK(on_send_data), self, NULL)); } else { GST_WARNING_OBJECT(self, "trying to change state to ready without connection id"); return GST_STATE_CHANGE_FAILURE; } break; case GST_STATE_CHANGE_READY_TO_PAUSED: GST_DEBUG_OBJECT(self, "starting connection %s", self->connection_id); er_dtls_connection_start(self->connection, self->is_client); gst_pad_set_active(self->src, TRUE); break; case GST_STATE_CHANGE_PAUSED_TO_READY: GST_DEBUG_OBJECT(self, "stopping connection %s", self->connection_id); gst_pad_set_active(self->src, FALSE); er_dtls_connection_stop(self->connection); break; case GST_STATE_CHANGE_READY_TO_NULL: GST_DEBUG_OBJECT(self, "closing connection %s", self->connection_id); if (self->connection) { er_dtls_connection_close(self->connection); er_dtls_connection_set_send_callback(self->connection, NULL); g_object_unref(self->connection); self->connection = NULL; } break; default: break; } ret = GST_ELEMENT_CLASS(parent_class)->change_state(element, transition); return ret; } static GstPad *gst_er_dtls_enc_request_new_pad(GstElement *element, GstPadTemplate *templ, const gchar *name, const GstCaps *caps) { GstPad *sink; gboolean ret; GST_DEBUG_OBJECT(element, "sink pad requested"); g_return_val_if_fail(templ->direction == GST_PAD_SINK, NULL); sink = gst_pad_new_from_template(templ, name); g_return_val_if_fail(sink, NULL); if (caps) { g_object_set(sink, "caps", caps, NULL); } gst_pad_set_chain_function(sink, GST_DEBUG_FUNCPTR(sink_chain)); ret = gst_pad_set_active(sink, TRUE); g_warn_if_fail(ret); gst_element_add_pad(element, sink); return sink; } static gboolean src_activate_mode(GstPad *pad, GstObject *parent, GstPadMode mode, gboolean active) { GstErDtlsEnc *self = GST_ER_DTLS_ENC (parent); gboolean success = TRUE; g_return_val_if_fail(mode == GST_PAD_MODE_PUSH, FALSE); if (active) { GST_DEBUG_OBJECT(self, "src pad activating in push mode"); self->send_initial_events = TRUE; success = gst_pad_start_task(pad, (GstTaskFunction) src_task_loop, self->src, NULL); if (!success) { GST_WARNING_OBJECT(self, "failed to activate pad task"); } } else { GST_DEBUG_OBJECT(self, "deactivating src pad"); g_cond_signal(&self->queue_cond_add); success = gst_pad_stop_task(pad); if (!success) { GST_WARNING_OBJECT(self, "failed to deactivate pad task"); } } return success; } static void src_task_loop(GstPad *pad) { GstErDtlsEnc *self = GST_ER_DTLS_ENC(GST_PAD_PARENT(pad)); GstFlowReturn ret; GstPad *peer; gboolean peer_is_active; if (!gst_pad_is_active(pad)) { GST_LOG_OBJECT(self, "src task loop entered on inactive pad"); return; } GST_TRACE_OBJECT(self, "src loop: acquiring lock"); g_mutex_lock(&self->queue_lock); GST_TRACE_OBJECT(self, "src loop: acquired lock"); while (!self->queue->len) { GST_TRACE_OBJECT(self, "src loop: queue empty, waiting for add"); g_cond_wait(&self->queue_cond_add, &self->queue_lock); GST_TRACE_OBJECT(self, "src loop: add signaled"); if (!gst_pad_is_active(pad)) { GST_LOG_OBJECT(self, "pad inactive, task returning"); GST_TRACE_OBJECT(self, "src loop: releasing lock"); g_mutex_unlock(&self->queue_lock); return; } } GST_TRACE_OBJECT(self, "src loop: queue has element"); peer = gst_pad_get_peer(pad); peer_is_active = gst_pad_is_active(peer); gst_object_unref(peer); if (peer_is_active) { GstBuffer *buffer; gboolean start_connection_timeout = FALSE; if (self->send_initial_events) { GstSegment segment; gchar s_id[32]; GstCaps *caps; g_snprintf (s_id, sizeof (s_id), "erdtlsenc-%08x", g_random_int ()); gst_pad_push_event (self->src, gst_event_new_stream_start (s_id)); caps = gst_caps_new_empty_simple ("application/x-dtls"); gst_pad_push_event (self->src, gst_event_new_caps (caps)); gst_caps_unref (caps); gst_segment_init (&segment, GST_FORMAT_BYTES); gst_pad_push_event (self->src, gst_event_new_segment (&segment)); self->send_initial_events = FALSE; start_connection_timeout = TRUE; } buffer = g_ptr_array_remove_index(self->queue, 0); GST_TRACE_OBJECT(self, "src loop: releasing lock"); g_mutex_unlock(&self->queue_lock); ret = gst_pad_push(self->src, buffer); if (start_connection_timeout) er_dtls_connection_start_timeout (self->connection); if (G_UNLIKELY(ret != GST_FLOW_OK)) { GST_WARNING_OBJECT(self, "failed to push buffer on src pad: %s", gst_flow_get_name(ret)); } } else { g_warn_if_reached(); GST_TRACE_OBJECT(self, "src loop: releasing lock"); g_mutex_unlock(&self->queue_lock); } } static GstFlowReturn sink_chain(GstPad *pad, GstObject *parent, GstBuffer *buffer) { GstErDtlsEnc *self = GST_ER_DTLS_ENC(parent); GstMapInfo map_info; gint ret; gst_buffer_map(buffer, &map_info, GST_MAP_READ); if (map_info.size) { ret = er_dtls_connection_send(self->connection, map_info.data, map_info.size); if (ret != map_info.size) { GST_WARNING_OBJECT(self, "error sending data: %d B were written, expected value was %zd B", ret, map_info.size); } } gst_buffer_unmap(buffer, &map_info); gst_buffer_unref(buffer); return GST_FLOW_OK; } static void on_key_received(ErDtlsConnection *connection, gpointer key, guint cipher, guint auth, GstErDtlsEnc *self) { gpointer key_dup; gchar *key_str; g_return_if_fail(GST_IS_ER_DTLS_ENC(self)); g_return_if_fail(ER_IS_DTLS_CONNECTION(connection)); self->srtp_cipher = cipher; self->srtp_auth = auth; key_dup = g_memdup(key, ER_DTLS_SRTP_MASTER_KEY_LENGTH); self->encoder_key = gst_buffer_new_wrapped(key_dup, ER_DTLS_SRTP_MASTER_KEY_LENGTH); key_str = g_base64_encode(key, ER_DTLS_SRTP_MASTER_KEY_LENGTH); GST_INFO_OBJECT(self, "received key: %s", key_str); g_free(key_str); g_signal_emit(self, signals[SIGNAL_ON_KEY_RECEIVED], 0); } static void on_send_data(ErDtlsConnection *connection, gconstpointer data, gint length, GstErDtlsEnc *self) { GstBuffer *buffer; GST_DEBUG_OBJECT(self, "sending data from %s with length %d", self->connection_id, length); buffer = gst_buffer_new_wrapped(g_memdup(data, length), length); GST_TRACE_OBJECT(self, "send data: acquiring lock"); g_mutex_lock(&self->queue_lock); GST_TRACE_OBJECT(self, "send data: acquired lock"); g_ptr_array_add(self->queue, buffer); GST_TRACE_OBJECT(self, "send data: signaling add"); g_cond_signal(&self->queue_cond_add); GST_TRACE_OBJECT(self, "send data: releasing lock"); g_mutex_unlock(&self->queue_lock); }
superdump/openwebrtc-gst-plugins
ext/erdtls/src/erdtlsagent.c
<reponame>superdump/openwebrtc-gst-plugins<filename>ext/erdtls/src/erdtlsagent.c /* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "erdtlsagent.h" #include "erdtlscommon.h" #ifdef __APPLE__ # define __AVAILABILITYMACROS__ # define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER #endif #include <openssl/err.h> #include <openssl/ssl.h> #if ER_DTLS_USE_GST_LOG GST_DEBUG_CATEGORY_STATIC(er_dtls_agent_debug); # define GST_CAT_DEFAULT er_dtls_agent_debug G_DEFINE_TYPE_WITH_CODE(ErDtlsAgent, er_dtls_agent, G_TYPE_OBJECT, GST_DEBUG_CATEGORY_INIT(er_dtls_agent_debug, "erdtlsagent", 0, "Ericsson DTLS Agent")); #else G_DEFINE_TYPE(ErDtlsAgent, er_dtls_agent, G_TYPE_OBJECT); #endif #define ER_DTLS_AGENT_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), ER_TYPE_DTLS_AGENT, ErDtlsAgentPrivate)) enum { PROP_0, PROP_CERTIFICATE, NUM_PROPERTIES }; static GParamSpec *properties[NUM_PROPERTIES]; struct _ErDtlsAgentPrivate { SSL_CTX *ssl_context; ErDtlsCertificate *certificate; }; static void er_dtls_agent_finalize(GObject *gobject); static void er_dtls_agent_set_property(GObject *, guint prop_id, const GValue *, GParamSpec *); const gchar *er_dtls_agent_peek_id(ErDtlsAgent *); void _er_dtls_init_openssl() { static gsize is_init = 0; if (g_once_init_enter(&is_init)) { if (OPENSSL_VERSION_NUMBER < 0x1000100fL) { LOG_WARNING(NULL, "Incorrect OpenSSL version, should be >= 1.0.1, is %s", OPENSSL_VERSION_TEXT); g_assert_not_reached(); } LOG_INFO(NULL, "initializing openssl %lx", OPENSSL_VERSION_NUMBER); SSL_library_init(); SSL_load_error_strings(); ERR_load_BIO_strings(); g_once_init_leave(&is_init, 1); } } static void er_dtls_agent_class_init(ErDtlsAgentClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS(klass); g_type_class_add_private(klass, sizeof(ErDtlsAgentPrivate)); gobject_class->set_property = er_dtls_agent_set_property; gobject_class->finalize = er_dtls_agent_finalize; properties[PROP_CERTIFICATE] = g_param_spec_object("certificate", "ErDtlsCertificate", "Sets the certificate of the agent", ER_TYPE_DTLS_CERTIFICATE, G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS); g_object_class_install_properties(gobject_class, NUM_PROPERTIES, properties); _er_dtls_init_openssl(); } static void er_dtls_agent_init(ErDtlsAgent *self) { ErDtlsAgentPrivate *priv = ER_DTLS_AGENT_GET_PRIVATE(self); self->priv = priv; ERR_clear_error(); priv->ssl_context = SSL_CTX_new(DTLSv1_method()); if (ERR_peek_error() || !priv->ssl_context) { char buf[512]; priv->ssl_context = NULL; LOG_WARNING(self, "Error creating SSL Context: %s", ERR_error_string(ERR_get_error(), buf)); g_return_if_reached(); } SSL_CTX_set_verify_depth(priv->ssl_context, 2); SSL_CTX_set_tlsext_use_srtp(priv->ssl_context, "SRTP_AES128_CM_SHA1_80"); SSL_CTX_set_cipher_list(priv->ssl_context, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); SSL_CTX_set_read_ahead(priv->ssl_context, 1); } static void er_dtls_agent_finalize(GObject *gobject) { ErDtlsAgentPrivate *priv = ER_DTLS_AGENT(gobject)->priv; SSL_CTX_free(priv->ssl_context); priv->ssl_context = NULL; LOG_DEBUG(gobject, "finalized"); G_OBJECT_CLASS(er_dtls_agent_parent_class)->finalize(gobject); } static void er_dtls_agent_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { ErDtlsAgent *self = ER_DTLS_AGENT(object); ErDtlsCertificate *certificate; switch (prop_id) { case PROP_CERTIFICATE: certificate = ER_DTLS_CERTIFICATE(g_value_get_object(value)); g_return_if_fail(ER_IS_DTLS_CERTIFICATE(certificate)); g_return_if_fail(self->priv->ssl_context); self->priv->certificate = certificate; g_object_ref(certificate); if (!SSL_CTX_use_certificate(self->priv->ssl_context, _er_dtls_certificate_get_internal_certificate(certificate))) { LOG_WARNING(self, "could not use certificate"); g_return_if_reached(); } if (!SSL_CTX_use_PrivateKey(self->priv->ssl_context, _er_dtls_certificate_get_internal_key(certificate))) { LOG_WARNING(self, "could not use private key"); g_return_if_reached(); } if (!SSL_CTX_check_private_key(self->priv->ssl_context)) { LOG_WARNING(self, "invalid private key"); g_return_if_reached(); } break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(self, prop_id, pspec); } } ErDtlsCertificate *er_dtls_agent_get_certificate(ErDtlsAgent *self) { g_return_val_if_fail(ER_IS_DTLS_AGENT(self), NULL); if (self->priv->certificate) { g_object_ref(self->priv->certificate); } return self->priv->certificate; } gchar *er_dtls_agent_get_certificate_pem(ErDtlsAgent *self) { gchar *pem; g_return_val_if_fail(ER_IS_DTLS_AGENT(self), NULL); g_return_val_if_fail(ER_IS_DTLS_CERTIFICATE(self->priv->certificate), NULL); g_object_get(self->priv->certificate, "pem", &pem, NULL); return pem; } const ErDtlsAgentContext _er_dtls_agent_peek_context(ErDtlsAgent *self) { g_return_val_if_fail(ER_IS_DTLS_AGENT(self), NULL); return self->priv->ssl_context; }
superdump/openwebrtc-gst-plugins
ext/erdtls/src/erdtlsconnection.h
<reponame>superdump/openwebrtc-gst-plugins<filename>ext/erdtls/src/erdtlsconnection.h /* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifndef erdtlsconnection_h #define erdtlsconnection_h #include <glib-object.h> G_BEGIN_DECLS #define ER_TYPE_DTLS_CONNECTION (er_dtls_connection_get_type()) #define ER_DTLS_CONNECTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), ER_TYPE_DTLS_CONNECTION, ErDtlsConnection)) #define ER_DTLS_CONNECTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), ER_TYPE_DTLS_CONNECTION, ErDtlsConnectionClass)) #define ER_IS_DTLS_CONNECTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), ER_TYPE_DTLS_CONNECTION)) #define ER_IS_DTLS_CONNECTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), ER_TYPE_DTLS_CONNECTION)) #define ER_DTLS_CONNECTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), ER_TYPE_DTLS_CONNECTION, ErDtlsConnectionClass)) typedef struct _ErDtlsConnection ErDtlsConnection; typedef struct _ErDtlsConnectionClass ErDtlsConnectionClass; typedef struct _ErDtlsConnectionPrivate ErDtlsConnectionPrivate; /** * ErDtlsSrtpCipher: * @ER_DTLS_SRTP_CIPHER_AES_128_ICM: aes-128-icm * * SRTP Cipher selected by the DTLS handshake, should match the enums in gstsrtp */ typedef enum { ER_DTLS_SRTP_CIPHER_AES_128_ICM = 1 } ErDtlsSrtpCipher; /** * ErDtlsSrtpAuth: * @ER_DTLS_SRTP_AUTH_HMAC_SHA1_32: hmac-sha1-32 * @ER_DTLS_SRTP_AUTH_HMAC_SHA1_80: hmac-sha1-80 * * SRTP Auth selected by the DTLS handshake, should match the enums in gstsrtp */ typedef enum { ER_DTLS_SRTP_AUTH_HMAC_SHA1_32 = 1, ER_DTLS_SRTP_AUTH_HMAC_SHA1_80 = 2 } ErDtlsSrtpAuth; #define ER_DTLS_SRTP_MASTER_KEY_LENGTH 30 /* * ErDtlsConnection: * * A class that handles a single DTLS connection. * Any connection needs to be created with the agent property set. * Once the DTLS handshake is completed, on-encoder-key and on-decoder-key will be signalled. */ struct _ErDtlsConnection { GObject parent_instance; ErDtlsConnectionPrivate *priv; }; struct _ErDtlsConnectionClass { GObjectClass parent_class; }; GType er_dtls_connection_get_type(void) G_GNUC_CONST; void er_dtls_connection_start(ErDtlsConnection *, gboolean is_client); void er_dtls_connection_start_timeout(ErDtlsConnection *); /* * Stops the connections, it is not required to call this function. */ void er_dtls_connection_stop(ErDtlsConnection *); /* * Closes the connection, the function will block until the connection has been stopped. * If stop is called some time before, close will return instantly. */ void er_dtls_connection_close(ErDtlsConnection *); /* * Sets the closure that will be called whenever data needs to be sent. * * The closure will get called with the following arguments: * void cb(ErDtlsConnection *, gpointer data, gint length, gpointer user_data) */ void er_dtls_connection_set_send_callback(ErDtlsConnection *, GClosure *); /* * Processes data that has been recevied, the transformation is done in-place. * Returns the length of the plaintext data that was decoded, if no data is available, 0<= will be returned. */ gint er_dtls_connection_process(ErDtlsConnection *, gpointer ptr, gint len); /* * If the DTLS handshake is completed this function will encode the given data. * Returns the length of the data sent, or 0 if the DTLS handshake is not completed. */ gint er_dtls_connection_send(ErDtlsConnection *, gpointer ptr, gint len); G_END_DECLS #endif /* erdtlsconnection_h */
superdump/openwebrtc-gst-plugins
ext/erdtls/src/gsterdtlsenc.h
<reponame>superdump/openwebrtc-gst-plugins<gh_stars>0 /* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifndef gsterdtlsenc_h #define gsterdtlsenc_h #include "erdtlsagent.h" #include "erdtlsconnection.h" #include <gst/gst.h> G_BEGIN_DECLS #define GST_TYPE_ER_DTLS_ENC (gst_er_dtls_enc_get_type()) #define GST_ER_DTLS_ENC(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GST_TYPE_ER_DTLS_ENC, GstErDtlsEnc)) #define GST_ER_DTLS_ENC_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), GST_TYPE_ER_DTLS_ENC, GstErDtlsEncClass)) #define GST_IS_ER_DTLS_ENC(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), GST_TYPE_ER_DTLS_ENC)) #define GST_IS_ER_DTLS_ENC_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), GST_TYPE_ER_DTLS_ENC)) typedef struct _GstErDtlsEnc GstErDtlsEnc; typedef struct _GstErDtlsEncClass GstErDtlsEncClass; struct _GstErDtlsEnc { GstElement element; GstPad *src; GPtrArray *queue; GMutex queue_lock; GCond queue_cond_add; ErDtlsConnection *connection; gchar *connection_id; gboolean is_client; GstBuffer *encoder_key; guint srtp_cipher; guint srtp_auth; gboolean send_initial_events; }; struct _GstErDtlsEncClass { GstElementClass parent_class; }; GType gst_er_dtls_enc_get_type(void); gboolean gst_er_dtls_enc_plugin_init(GstPlugin *); G_END_DECLS #endif /* gsterdtlsenc_h */
superdump/openwebrtc-gst-plugins
gst/videorepair/gstvideorepair.c
<reponame>superdump/openwebrtc-gst-plugins<gh_stars>0 /* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gstvideorepair.h" #include <gst/gst.h> #include <gst/video/video.h> GST_DEBUG_CATEGORY_STATIC(gst_videorepair_debug_category); #define GST_CAT_DEFAULT gst_videorepair_debug_category /* prototypes */ static void gst_videorepair_set_property(GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); static void gst_videorepair_get_property(GObject *object, guint property_id, GValue *value, GParamSpec *pspec); static GstStateChangeReturn gst_videorepair_change_state(GstElement *element, GstStateChange transition); static gboolean gst_videorepair_sink_event(GstPad *pad, GstObject *parent, GstEvent *event); static GstFlowReturn gst_videorepair_sink_chain(GstPad *pad, GstObject *parent, GstBuffer *buffer); /* properties */ #define DEFAULT_DROP_UNTIL_INTRA TRUE #define DEFAULT_RETRY_INTERVAL 30 enum { PROP_0, PROP_DROP_UNTIL_INTRA, PROP_RETRY_INTERVAL, NUM_PROPERTIES }; static GParamSpec *obj_properties[NUM_PROPERTIES] = {NULL, }; /* pad templates */ static GstStaticPadTemplate gst_videorepair_sink_template = GST_STATIC_PAD_TEMPLATE("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS("video/x-h264; video/x-vp8") ); static GstStaticPadTemplate gst_videorepair_src_template = GST_STATIC_PAD_TEMPLATE("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS("video/x-h264; video/x-vp8") ); /* class initialization */ #define gst_videorepair_parent_class parent_class G_DEFINE_TYPE_WITH_CODE(GstVideoRepair, gst_videorepair, GST_TYPE_ELEMENT, GST_DEBUG_CATEGORY_INIT(gst_videorepair_debug_category, "videorepair", 0, "debug category for videorepair element")); static void gst_videorepair_class_init(GstVideoRepairClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS(klass); GstElementClass *element_class = GST_ELEMENT_CLASS(klass); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&gst_videorepair_sink_template)); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get(&gst_videorepair_src_template)); gst_element_class_set_static_metadata(GST_ELEMENT_CLASS(klass), "Video repair", "Filter/Video/Network", "Requests intra pictures on GAP events and (optionally) drops buffers until they arrive", "Ericsson AB, http://www.ericsson.com"); gobject_class->set_property = gst_videorepair_set_property; gobject_class->get_property = gst_videorepair_get_property; element_class->change_state = GST_DEBUG_FUNCPTR(gst_videorepair_change_state); obj_properties[PROP_DROP_UNTIL_INTRA] = g_param_spec_boolean("drop-until-intra", "Drop until intra", "Drop buffers until an intra picture arrives when there was a GAP", DEFAULT_DROP_UNTIL_INTRA, G_PARAM_STATIC_STRINGS | G_PARAM_READWRITE); obj_properties[PROP_RETRY_INTERVAL] = g_param_spec_uint("retry-interval", "Retry interval", "Number of buffers dropped until a new key unit request is made (0=disable)", 0, G_MAXUINT, DEFAULT_RETRY_INTERVAL, G_PARAM_STATIC_STRINGS | G_PARAM_READWRITE); g_object_class_install_properties(gobject_class, NUM_PROPERTIES, obj_properties); } static void gst_videorepair_reset(GstVideoRepair *videorepair) { videorepair->needs_intra = TRUE; videorepair->drop_count = 0; } static void gst_videorepair_init(GstVideoRepair *videorepair) { videorepair->sinkpad = gst_pad_new_from_static_template( &gst_videorepair_sink_template, "sink"); gst_pad_set_chain_function(videorepair->sinkpad, GST_DEBUG_FUNCPTR(gst_videorepair_sink_chain)); gst_pad_set_event_function(videorepair->sinkpad, GST_DEBUG_FUNCPTR(gst_videorepair_sink_event)); GST_PAD_SET_PROXY_CAPS(videorepair->sinkpad); gst_element_add_pad(GST_ELEMENT(videorepair), videorepair->sinkpad); videorepair->srcpad = gst_pad_new_from_static_template( &gst_videorepair_src_template, "src"); GST_PAD_SET_PROXY_CAPS(videorepair->srcpad); gst_element_add_pad(GST_ELEMENT(videorepair), videorepair->srcpad); videorepair->drop_until_intra = DEFAULT_DROP_UNTIL_INTRA; videorepair->retry_interval = DEFAULT_RETRY_INTERVAL; gst_videorepair_reset(videorepair); } void gst_videorepair_set_property(GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { GstVideoRepair *videorepair = GST_VIDEOREPAIR(object); switch (property_id) { case PROP_DROP_UNTIL_INTRA: videorepair->drop_until_intra = g_value_get_boolean(value); break; case PROP_RETRY_INTERVAL: videorepair->retry_interval = g_value_get_uint(value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec); break; } } void gst_videorepair_get_property(GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { GstVideoRepair *videorepair = GST_VIDEOREPAIR(object); switch (property_id) { case PROP_DROP_UNTIL_INTRA: g_value_set_boolean(value, videorepair->drop_until_intra); break; case PROP_RETRY_INTERVAL: g_value_set_uint(value, videorepair->retry_interval); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec); break; } } static GstStateChangeReturn gst_videorepair_change_state(GstElement *element, GstStateChange transition) { GstVideoRepair *videorepair = GST_VIDEOREPAIR(element); GstStateChangeReturn ret; /* We don't need to do anything for upward transitions */ ret = GST_ELEMENT_CLASS(parent_class)->change_state(element, transition); if (ret != GST_STATE_CHANGE_SUCCESS) return ret; switch (transition) { case GST_STATE_CHANGE_PAUSED_TO_READY: gst_videorepair_reset(videorepair); break; default: break; } return GST_STATE_CHANGE_SUCCESS; } static gboolean gst_videorepair_sink_event(GstPad *pad, GstObject *parent, GstEvent *event) { GstVideoRepair *videorepair = GST_VIDEOREPAIR(parent); gboolean ret; switch (GST_EVENT_TYPE(event)) { case GST_EVENT_GAP: GST_INFO_OBJECT(videorepair, "got GAP event"); gst_pad_push_event(videorepair->sinkpad, gst_video_event_new_upstream_force_key_unit(GST_CLOCK_TIME_NONE, FALSE, 0)); videorepair->needs_intra = TRUE; ret = TRUE; break; default: ret = gst_pad_event_default(pad, parent, event); } return ret; } static GstFlowReturn gst_videorepair_sink_chain(GstPad *pad, GstObject *parent, GstBuffer *buffer) { GstVideoRepair *videorepair = GST_VIDEOREPAIR(parent); (void)pad; if (!GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DELTA_UNIT)) { GST_DEBUG_OBJECT(videorepair, "got keyframe"); videorepair->needs_intra = FALSE; videorepair->drop_count = 0; } if (videorepair->needs_intra && videorepair->drop_until_intra) { GST_DEBUG_OBJECT(videorepair, "dropping buffer waiting for intra"); videorepair->drop_count++; if (videorepair->retry_interval && (videorepair->drop_count >= videorepair->retry_interval)) { GST_INFO_OBJECT(videorepair, "still no intra picture, requesting a key unit again"); gst_pad_push_event(videorepair->sinkpad, gst_video_event_new_upstream_force_key_unit(GST_CLOCK_TIME_NONE, FALSE, 0)); videorepair->drop_count = 0; } gst_buffer_unref(buffer); return GST_FLOW_OK; } return gst_pad_push(videorepair->srcpad, buffer); } static gboolean plugin_init(GstPlugin *plugin) { return gst_element_register(plugin, "videorepair", GST_RANK_NONE, GST_TYPE_VIDEOREPAIR); } GST_PLUGIN_DEFINE( GST_VERSION_MAJOR, GST_VERSION_MINOR, videorepair, "Requests intra pictures on GAP events and (optionally) drops buffers until they arrive", plugin_init, "0.0.1", "BSD", "OpenWebRTC GStreamer plugins", "http://www.ericsson.com")
superdump/openwebrtc-gst-plugins
ext/erdtls/src/gsterdtlsdec.h
/* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifndef gsterdtlsdec_h #define gsterdtlsdec_h #include "erdtlsagent.h" #include "erdtlsconnection.h" #include <gst/gst.h> G_BEGIN_DECLS #define GST_TYPE_ER_DTLS_DEC \ (gst_er_dtls_dec_get_type()) #define GST_ER_DTLS_DEC(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj), GST_TYPE_ER_DTLS_DEC, GstErDtlsDec)) #define GST_ER_DTLS_DEC_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST((klass), GST_TYPE_ER_DTLS_DEC, GstErDtlsDecClass)) #define GST_IS_ER_DTLS_DEC(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE((obj), GST_TYPE_ER_DTLS_DEC)) #define GST_IS_ER_DTLS_DEC_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE((klass), GST_TYPE_ER_DTLS_DEC)) typedef struct _GstErDtlsDec GstErDtlsDec; typedef struct _GstErDtlsDecClass GstErDtlsDecClass; struct _GstErDtlsDec { GstElement element; GstPad *src; GMutex src_mutex; ErDtlsAgent *agent; ErDtlsConnection *connection; GMutex connection_mutex; gchar *connection_id; gchar *peer_pem; GstBuffer *decoder_key; guint srtp_cipher; guint srtp_auth; }; struct _GstErDtlsDecClass { GstElementClass parent_class; }; GType gst_er_dtls_dec_get_type(void); gboolean gst_er_dtls_dec_plugin_init(GstPlugin *); ErDtlsConnection *gst_er_dtls_dec_fetch_connection(gchar *id); G_END_DECLS #endif /* gsterdtlsdec_h */
superdump/openwebrtc-gst-plugins
ext/erdtls/src/erdtlsagent.h
<reponame>superdump/openwebrtc-gst-plugins /* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifndef erdtlsagent_h #define erdtlsagent_h #include "erdtlscertificate.h" #include <glib-object.h> G_BEGIN_DECLS #define ER_TYPE_DTLS_AGENT (er_dtls_agent_get_type()) #define ER_DTLS_AGENT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), ER_TYPE_DTLS_AGENT, ErDtlsAgent)) #define ER_DTLS_AGENT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), ER_TYPE_DTLS_AGENT, ErDtlsAgentClass)) #define ER_IS_DTLS_AGENT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), ER_TYPE_DTLS_AGENT)) #define ER_IS_DTLS_AGENT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), ER_TYPE_DTLS_AGENT)) #define ER_DTLS_AGENT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), ER_TYPE_DTLS_AGENT, ErDtlsAgentClass)) typedef gpointer ErDtlsAgentContext; typedef struct _ErDtlsAgent ErDtlsAgent; typedef struct _ErDtlsAgentClass ErDtlsAgentClass; typedef struct _ErDtlsAgentPrivate ErDtlsAgentPrivate; /* * ErDtlsAgent: * * A context for creating ErDtlsConnections with a ErDtlsCertificate. * ErDtlsAgent needs to be constructed with the "certificate" property set. */ struct _ErDtlsAgent { GObject parent_instance; ErDtlsAgentPrivate *priv; }; struct _ErDtlsAgentClass { GObjectClass parent_class; }; GType er_dtls_agent_get_type(void) G_GNUC_CONST; /* * Returns the certificate used by the agent. */ ErDtlsCertificate *er_dtls_agent_get_certificate(ErDtlsAgent *); /* * Returns the certificate used by the agent, in PEM format. */ gchar *er_dtls_agent_get_certificate_pem(ErDtlsAgent *self); /* internal */ void _er_dtls_init_openssl(); const ErDtlsAgentContext _er_dtls_agent_peek_context(ErDtlsAgent *); G_END_DECLS #endif /* erdtlsagent_h */
superdump/openwebrtc-gst-plugins
ext/erdtls/src/gsterdtlsdec.c
<filename>ext/erdtls/src/gsterdtlsdec.c /* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gsterdtlsdec.h" #include "erdtlscertificate.h" static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS("application/x-dtls") ); static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE("src", GST_PAD_SRC, GST_PAD_REQUEST, GST_STATIC_CAPS_ANY ); GST_DEBUG_CATEGORY_STATIC(er_dtls_dec_debug); #define GST_CAT_DEFAULT er_dtls_dec_debug #define gst_er_dtls_dec_parent_class parent_class G_DEFINE_TYPE_WITH_CODE(GstErDtlsDec, gst_er_dtls_dec, GST_TYPE_ELEMENT, GST_DEBUG_CATEGORY_INIT(er_dtls_dec_debug, "erdtlsdec", 0, "Ericsson DTLS Decoder")); #define UNUSED(param) while (0) { (void)(param); } enum { SIGNAL_ON_KEY_RECEIVED, NUM_SIGNALS }; static guint signals[NUM_SIGNALS]; enum { PROP_0, PROP_CONNECTION_ID, PROP_PEM, PROP_PEER_PEM, PROP_DECODER_KEY, PROP_SRTP_CIPHER, PROP_SRTP_AUTH, NUM_PROPERTIES }; static GParamSpec *properties[NUM_PROPERTIES]; #define DEFAULT_CONNECTION_ID NULL #define DEFAULT_PEM NULL #define DEFAULT_PEER_PEM NULL #define DEFAULT_DECODER_KEY NULL #define DEFAULT_SRTP_CIPHER 0 #define DEFAULT_SRTP_AUTH 0 static void gst_er_dtls_dec_finalize(GObject *); static void gst_er_dtls_dec_dispose(GObject *); static void gst_er_dtls_dec_set_property(GObject *, guint prop_id, const GValue *, GParamSpec *); static void gst_er_dtls_dec_get_property(GObject *, guint prop_id, GValue *, GParamSpec *); static GstStateChangeReturn gst_er_dtls_dec_change_state(GstElement *, GstStateChange); static GstPad *gst_er_dtls_dec_request_new_pad(GstElement *, GstPadTemplate *, const gchar *name, const GstCaps *); static void gst_er_dtls_dec_release_pad(GstElement *, GstPad *); static void on_key_received(ErDtlsConnection *, gpointer key, guint cipher, guint auth, GstErDtlsDec *); static gboolean on_peer_certificate_received(ErDtlsConnection *, gchar *pem, GstErDtlsDec *); static GstFlowReturn sink_chain(GstPad *, GstObject *parent, GstBuffer *); static ErDtlsAgent *get_agent_by_pem(const gchar *pem); static void agent_weak_ref_notify(gchar *pem, ErDtlsAgent *); static void create_connection(GstErDtlsDec *, gchar *id); static void connection_weak_ref_notify(gchar *id, ErDtlsConnection *); static void gst_er_dtls_dec_class_init(GstErDtlsDecClass *klass) { GObjectClass *gobject_class; GstElementClass *element_class; gobject_class = (GObjectClass *) klass; element_class = (GstElementClass *) klass; gobject_class->finalize = GST_DEBUG_FUNCPTR(gst_er_dtls_dec_finalize); gobject_class->dispose = GST_DEBUG_FUNCPTR(gst_er_dtls_dec_dispose); gobject_class->set_property = GST_DEBUG_FUNCPTR(gst_er_dtls_dec_set_property); gobject_class->get_property = GST_DEBUG_FUNCPTR(gst_er_dtls_dec_get_property); element_class->change_state = GST_DEBUG_FUNCPTR(gst_er_dtls_dec_change_state); element_class->request_new_pad = GST_DEBUG_FUNCPTR(gst_er_dtls_dec_request_new_pad); element_class->release_pad = GST_DEBUG_FUNCPTR(gst_er_dtls_dec_release_pad); signals[SIGNAL_ON_KEY_RECEIVED] = g_signal_new("on-key-received", G_TYPE_FROM_CLASS(klass), G_SIGNAL_RUN_LAST, 0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 0); properties[PROP_CONNECTION_ID] = g_param_spec_string("connection-id", "Connection id", "Every encoder/decoder pair should have the same, unique, connection-id", DEFAULT_CONNECTION_ID, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); properties[PROP_PEM] = g_param_spec_string("pem", "PEM string", "A string containing a X509 certificate and RSA private key in PEM format", DEFAULT_PEM, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); properties[PROP_PEER_PEM] = g_param_spec_string("peer-pem", "Peer PEM string", "The X509 certificate received in the DTLS handshake, in PEM format", DEFAULT_PEER_PEM, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); properties[PROP_DECODER_KEY] = g_param_spec_boxed("decoder-key", "Decoder key", "SRTP key that should be used by the decider", GST_TYPE_CAPS, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); properties[PROP_SRTP_CIPHER] = g_param_spec_uint("srtp-cipher", "SRTP cipher", "The SRTP cipher selected in the DTLS handshake. " "The value will be set to an ErDtlsSrtpCipher.", 0, ER_DTLS_SRTP_CIPHER_AES_128_ICM, DEFAULT_SRTP_CIPHER, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); properties[PROP_SRTP_AUTH] = g_param_spec_uint("srtp-auth", "SRTP authentication", "The SRTP authentication selected in the DTLS handshake. " "The value will be set to an ErDtlsSrtpAuth.", 0, ER_DTLS_SRTP_AUTH_HMAC_SHA1_80, DEFAULT_SRTP_AUTH, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); g_object_class_install_properties(gobject_class, NUM_PROPERTIES, properties); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&src_template)); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&sink_template)); gst_element_class_set_static_metadata(element_class, "DTLS Decoder", "Decoder/Network/DTLS", "Decodes DTLS packets", "<NAME> <EMAIL>"); } static void gst_er_dtls_dec_init(GstErDtlsDec *self) { GstPad *sink; self->agent = get_agent_by_pem(NULL); self->connection_id = NULL; self->connection = NULL; self->peer_pem = NULL; self->decoder_key = NULL; self->srtp_cipher = DEFAULT_SRTP_CIPHER; self->srtp_auth = DEFAULT_SRTP_AUTH; g_mutex_init(&self->src_mutex); self->src = NULL; sink = gst_pad_new_from_static_template(&sink_template, "sink"); g_return_if_fail(sink); gst_pad_set_chain_function(sink, GST_DEBUG_FUNCPTR(sink_chain)); gst_element_add_pad(GST_ELEMENT(self), sink); } static void gst_er_dtls_dec_finalize(GObject *object) { GstErDtlsDec *self = GST_ER_DTLS_DEC(object); if (self->decoder_key) { gst_buffer_unref(self->decoder_key); self->decoder_key = NULL; } g_free(self->connection_id); self->connection_id = NULL; g_free(self->peer_pem); self->peer_pem = NULL; g_mutex_clear(&self->src_mutex); GST_LOG_OBJECT(self, "finalized"); G_OBJECT_CLASS(parent_class)->finalize(object); } static void gst_er_dtls_dec_dispose(GObject *object) { GstErDtlsDec *self = GST_ER_DTLS_DEC(object); if (self->agent) { g_object_unref(self->agent); self->agent = NULL; } if (self->connection) { g_object_unref(self->connection); self->connection = NULL; } } static void gst_er_dtls_dec_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { GstErDtlsDec *self = GST_ER_DTLS_DEC(object); switch (prop_id) { case PROP_CONNECTION_ID: g_free(self->connection_id); self->connection_id = g_value_dup_string(value); g_return_if_fail(self->agent); create_connection(self, self->connection_id); break; case PROP_PEM: if (self->agent) { g_object_unref(self->agent); } self->agent = get_agent_by_pem(g_value_get_string(value)); if (self->connection_id) { create_connection(self, self->connection_id); } break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(self, prop_id, pspec); } } static void gst_er_dtls_dec_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { GstErDtlsDec *self = GST_ER_DTLS_DEC(object); switch (prop_id) { case PROP_CONNECTION_ID: g_value_set_string(value, self->connection_id); break; case PROP_PEM: g_value_take_string(value, er_dtls_agent_get_certificate_pem(self->agent)); break; case PROP_PEER_PEM: g_value_set_string(value, self->peer_pem); break; case PROP_DECODER_KEY: g_value_set_boxed(value, self->decoder_key); break; case PROP_SRTP_CIPHER: g_value_set_uint(value, self->srtp_cipher); break; case PROP_SRTP_AUTH: g_value_set_uint(value, self->srtp_auth); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(self, prop_id, pspec); } } static GstStateChangeReturn gst_er_dtls_dec_change_state(GstElement *element, GstStateChange transition) { GstErDtlsDec *self = GST_ER_DTLS_DEC(element); GstStateChangeReturn ret; switch (transition) { case GST_STATE_CHANGE_NULL_TO_READY: if (self->connection) { g_signal_connect_object(self->connection, "on-decoder-key", G_CALLBACK(on_key_received), self, 0); g_signal_connect_object(self->connection, "on-peer-certificate", G_CALLBACK(on_peer_certificate_received), self, 0); } else { GST_WARNING_OBJECT(self, "trying to change state to ready without connection id and pem"); return GST_STATE_CHANGE_FAILURE; } break; default: break; } ret = GST_ELEMENT_CLASS(parent_class)->change_state(element, transition); return ret; } static GstPad *gst_er_dtls_dec_request_new_pad(GstElement *element, GstPadTemplate *tmpl, const gchar *name, const GstCaps *caps) { GstErDtlsDec *self = GST_ER_DTLS_DEC(element); GST_DEBUG_OBJECT(element, "requesting pad"); g_return_val_if_fail(!self->src, NULL); g_return_val_if_fail(tmpl->direction == GST_PAD_SRC, NULL); g_mutex_lock(&self->src_mutex); self->src = gst_pad_new_from_template(tmpl, name); g_return_val_if_fail(self->src, NULL); if (caps) { g_object_set(self->src, "caps", caps, NULL); } gst_pad_set_active(self->src, TRUE); gst_element_add_pad(element, self->src); g_mutex_unlock(&self->src_mutex); return self->src; } static void gst_er_dtls_dec_release_pad(GstElement *element, GstPad *pad) { GstErDtlsDec *self = GST_ER_DTLS_DEC(element); g_mutex_lock(&self->src_mutex); g_return_if_fail(self->src == pad); gst_element_remove_pad(element, self->src); self->src = NULL; GST_DEBUG_OBJECT(self, "releasing src pad"); g_mutex_unlock(&self->src_mutex); GST_ELEMENT_GET_CLASS(element)->release_pad(element, pad); } static void on_key_received(ErDtlsConnection *connection, gpointer key, guint cipher, guint auth, GstErDtlsDec *self) { gpointer key_dup; gchar *key_str; UNUSED(connection); g_return_if_fail(GST_IS_ER_DTLS_DEC(self)); self->srtp_cipher = cipher; self->srtp_auth = auth; key_dup = g_memdup(key, ER_DTLS_SRTP_MASTER_KEY_LENGTH); self->decoder_key = gst_buffer_new_wrapped(key_dup, ER_DTLS_SRTP_MASTER_KEY_LENGTH); key_str = g_base64_encode(key, ER_DTLS_SRTP_MASTER_KEY_LENGTH); GST_INFO_OBJECT(self, "received key: %s", key_str); g_free(key_str); g_signal_emit(self, signals[SIGNAL_ON_KEY_RECEIVED], 0); } static gboolean signal_peer_certificate_received(GWeakRef *ref) { GstErDtlsDec *self; self = g_weak_ref_get(ref); g_weak_ref_clear(ref); g_free(ref); ref = NULL; if (self) { g_object_notify_by_pspec(G_OBJECT(self), properties[PROP_PEER_PEM]); g_object_unref(self); self = NULL; } return FALSE; } static gboolean on_peer_certificate_received(ErDtlsConnection *connection, gchar *pem, GstErDtlsDec *self) { GWeakRef *ref; UNUSED(connection); g_return_val_if_fail(GST_IS_ER_DTLS_DEC(self), TRUE); GST_DEBUG_OBJECT(self, "Received peer certificate PEM: \n%s", pem); self->peer_pem = g_strdup(pem); ref = g_new(GWeakRef, 1); g_weak_ref_init(ref, self); g_idle_add((GSourceFunc) signal_peer_certificate_received, ref); return TRUE; } static GstFlowReturn sink_chain(GstPad *pad, GstObject *parent, GstBuffer *buffer) { GstErDtlsDec *self = GST_ER_DTLS_DEC(parent); GstFlowReturn ret = GST_FLOW_OK; GstMapInfo map_info = GST_MAP_INFO_INIT; gint size; if (!self->agent) { gst_buffer_unref(buffer); return GST_FLOW_OK; } GST_DEBUG_OBJECT(self, "received buffer from %s with length %zd", self->connection_id, gst_buffer_get_size(buffer)); gst_buffer_map(buffer, &map_info, GST_MAP_READWRITE); if (!map_info.size) { gst_buffer_unmap(buffer, &map_info); return GST_FLOW_OK; } size = er_dtls_connection_process(self->connection, map_info.data, map_info.size); gst_buffer_unmap(buffer, &map_info); if (size <= 0) { gst_buffer_unref(buffer); return GST_FLOW_OK; } g_mutex_lock(&self->src_mutex); if (self->src) { gst_buffer_set_size(buffer, size); GST_LOG_OBJECT(self, "decoded buffer with length %d, pushing", size); ret = gst_pad_push(self->src, buffer); } else { GST_LOG_OBJECT(self, "dropped buffer with length %d, not linked", size); gst_buffer_unref(buffer); } g_mutex_unlock(&self->src_mutex); return ret; } static GHashTable *agent_table = NULL; G_LOCK_DEFINE_STATIC(agent_table); static ErDtlsAgent *generated_cert_agent = NULL; static ErDtlsAgent *get_agent_by_pem(const gchar *pem) { ErDtlsAgent *agent; if (!pem) { if (g_once_init_enter (&generated_cert_agent)) { ErDtlsAgent *new_agent; new_agent = g_object_new(ER_TYPE_DTLS_AGENT, "certificate", g_object_new(ER_TYPE_DTLS_CERTIFICATE, NULL), NULL); GST_DEBUG_OBJECT(generated_cert_agent, "no agent with generated cert found, creating new"); g_once_init_leave (&generated_cert_agent, new_agent); } else { GST_DEBUG_OBJECT(generated_cert_agent, "using agent with generated cert"); } agent = generated_cert_agent; g_object_ref(agent); } else { G_LOCK(agent_table); if (!agent_table) { agent_table = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL); } agent = ER_DTLS_AGENT(g_hash_table_lookup(agent_table, pem)); if (!agent) { agent = g_object_new(ER_TYPE_DTLS_AGENT, "certificate", g_object_new(ER_TYPE_DTLS_CERTIFICATE, "pem", pem, NULL), NULL); g_object_weak_ref(G_OBJECT(agent), (GWeakNotify) agent_weak_ref_notify, (gpointer) g_strdup(pem)); g_hash_table_insert(agent_table, g_strdup(pem), agent); GST_DEBUG_OBJECT(agent, "no agent found, created new"); } else { g_object_ref(agent); GST_DEBUG_OBJECT(agent, "agent found"); } G_UNLOCK(agent_table); } return agent; } static void agent_weak_ref_notify(gchar *pem, ErDtlsAgent *agent) { UNUSED(agent); G_LOCK(agent_table); g_hash_table_remove(agent_table, pem); G_UNLOCK(agent_table); g_free(pem); pem = NULL; } static GHashTable *connection_table = NULL; G_LOCK_DEFINE_STATIC(connection_table); ErDtlsConnection *gst_er_dtls_dec_fetch_connection(gchar *id) { ErDtlsConnection *connection; g_return_val_if_fail(id, NULL); GST_DEBUG("fetching '%s' from connection table, size is %d", id, g_hash_table_size(connection_table)); G_LOCK(connection_table); connection = g_hash_table_lookup(connection_table, id); if (connection) { g_object_ref(connection); g_hash_table_remove(connection_table, id); } else { GST_WARNING("no connection with id '%s' found", id); } G_UNLOCK(connection_table); return connection; } static void create_connection(GstErDtlsDec *self, gchar *id) { g_return_if_fail(GST_IS_ER_DTLS_DEC(self)); g_return_if_fail(ER_IS_DTLS_AGENT(self->agent)); if (self->connection) { g_object_unref(self->connection); self->connection = NULL; } G_LOCK(connection_table); if (!connection_table) { connection_table = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL); } if (g_hash_table_contains(connection_table, id)) { G_UNLOCK(connection_table); g_return_if_reached(); } self->connection = g_object_new(ER_TYPE_DTLS_CONNECTION, "agent", self->agent, NULL); g_object_weak_ref(G_OBJECT(self->connection), (GWeakNotify) connection_weak_ref_notify, g_strdup(id)); g_hash_table_insert(connection_table, g_strdup(id), self->connection); G_UNLOCK(connection_table); } static void connection_weak_ref_notify(gchar *id, ErDtlsConnection *connection) { UNUSED(connection); G_LOCK(connection_table); g_hash_table_remove(connection_table, id); G_UNLOCK(connection_table); g_free(id); id = NULL; }
superdump/openwebrtc-gst-plugins
ext/erdtls/src/gsterdtlssrtpbin.c
/* * Copyright (c) 2014, Ericsson AB. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gsterdtlssrtpbin.h" #define gst_er_dtls_srtp_bin_parent_class parent_class G_DEFINE_ABSTRACT_TYPE(GstErDtlsSrtpBin, gst_er_dtls_srtp_bin, GST_TYPE_BIN); enum { PROP_0, PROP_CONNECTION_ID, PROP_KEY, PROP_SRTP_AUTH, PROP_SRTP_CIPHER, PROP_SRTCP_AUTH, PROP_SRTCP_CIPHER, NUM_PROPERTIES }; static GParamSpec *properties[NUM_PROPERTIES]; #define DEFAULT_CONNECTION_ID NULL #define DEFAULT_KEY NULL #define DEFAULT_SRTP_AUTH NULL #define DEFAULT_SRTP_CIPHER NULL #define DEFAULT_SRTCP_AUTH NULL #define DEFAULT_SRTCP_CIPHER NULL static void gst_er_dtls_srtp_bin_finalize(GObject *); static void gst_er_dtls_srtp_bin_set_property(GObject *, guint prop_id, const GValue *, GParamSpec *); static void gst_er_dtls_srtp_bin_get_property(GObject *, guint prop_id, GValue *, GParamSpec *); static void gst_er_dtls_srtp_bin_class_init(GstErDtlsSrtpBinClass *klass) { GObjectClass *gobject_class; gobject_class = (GObjectClass *) klass; gobject_class->finalize = GST_DEBUG_FUNCPTR(gst_er_dtls_srtp_bin_finalize); gobject_class->set_property = GST_DEBUG_FUNCPTR(gst_er_dtls_srtp_bin_set_property); gobject_class->get_property = GST_DEBUG_FUNCPTR(gst_er_dtls_srtp_bin_get_property); klass->remove_dtls_element = NULL; properties[PROP_CONNECTION_ID] = g_param_spec_string("connection-id", "Connection id", "Every encoder/decoder pair should have the same, unique, connection-id", DEFAULT_CONNECTION_ID, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); properties[PROP_KEY] = g_param_spec_boxed("key", "Key", "SRTP master key, if this property is set, DTLS will be disabled", GST_TYPE_BUFFER, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING | G_PARAM_STATIC_STRINGS); properties[PROP_SRTP_CIPHER] = g_param_spec_string("srtp-cipher", "SRTP Cipher", "SRTP cipher name, should be 'null' or 'aes-128-icm', " "if this property is set, DTLS will be disabled", DEFAULT_SRTP_CIPHER, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING | G_PARAM_STATIC_STRINGS); properties[PROP_SRTCP_CIPHER] = g_param_spec_string("srtcp-cipher", "SRTCP Cipher", "SRTCP cipher name, should be 'null' or 'aes-128-icm', " "if this property is set, DTLS will be disabled", DEFAULT_SRTCP_CIPHER, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING | G_PARAM_STATIC_STRINGS); properties[PROP_SRTP_AUTH] = g_param_spec_string("srtp-auth", "SRTP Auth", "SRTP auth name, should be 'null', 'hmac-sha1-32' or 'hmac-sha1-80', " "if this property is set, DTLS will be disabled", DEFAULT_SRTP_AUTH, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING | G_PARAM_STATIC_STRINGS); properties[PROP_SRTCP_AUTH] = g_param_spec_string("srtcp-auth", "SRTCP Auth", "SRTCP auth name, should be 'null', 'hmac-sha1-32' or 'hmac-sha1-80', " "if this property is set, DTLS will be disabled", DEFAULT_SRTCP_AUTH, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING | G_PARAM_STATIC_STRINGS); g_object_class_install_properties(gobject_class, NUM_PROPERTIES, properties); } static void gst_er_dtls_srtp_bin_init(GstErDtlsSrtpBin *self) { self->key = NULL; self->key_is_set = FALSE; self->srtp_auth = NULL; self->srtp_cipher = NULL; self->srtcp_auth = NULL; self->srtcp_cipher = NULL; } static void gst_er_dtls_srtp_bin_finalize(GObject *object) { GstErDtlsSrtpBin *self = GST_ER_DTLS_SRTP_BIN(object); if (self->key) { gst_buffer_unref(self->key); self->key = NULL; } g_free(self->srtp_auth); self->srtp_auth = NULL; g_free(self->srtp_cipher); self->srtp_cipher = NULL; g_free(self->srtcp_auth); self->srtcp_auth = NULL; g_free(self->srtcp_cipher); self->srtcp_cipher = NULL; G_OBJECT_CLASS(parent_class)->finalize(object); } static void gst_er_dtls_srtp_bin_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { GstErDtlsSrtpBin *self = GST_ER_DTLS_SRTP_BIN(object); GstErDtlsSrtpBinClass *klass = GST_ER_DTLS_SRTP_BIN_GET_CLASS(self); switch (prop_id) { case PROP_CONNECTION_ID: if (self->dtls_element) { g_object_set_property(G_OBJECT(self->dtls_element), "connection-id", value); } else { g_warning("tried to set connection-id after disabling DTLS"); } break; case PROP_KEY: if (self->key) { gst_buffer_unref(self->key); } self->key = g_value_dup_boxed(value); self->key_is_set = TRUE; klass->remove_dtls_element(self); break; case PROP_SRTP_AUTH: g_free(self->srtp_auth); self->srtp_auth = g_value_dup_string(value); klass->remove_dtls_element(self); break; case PROP_SRTP_CIPHER: g_free(self->srtp_cipher); self->srtp_cipher = g_value_dup_string(value); klass->remove_dtls_element(self); break; case PROP_SRTCP_AUTH: g_free(self->srtcp_auth); self->srtcp_auth = g_value_dup_string(value); klass->remove_dtls_element(self); break; case PROP_SRTCP_CIPHER: g_free(self->srtcp_cipher); self->srtcp_cipher = g_value_dup_string(value); klass->remove_dtls_element(self); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(self, prop_id, pspec); } } static void gst_er_dtls_srtp_bin_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { GstErDtlsSrtpBin *self = GST_ER_DTLS_SRTP_BIN(object); switch (prop_id) { case PROP_CONNECTION_ID: if (self->dtls_element) { g_object_get_property(G_OBJECT(self->dtls_element), "connection-id", value); } else { g_warning("tried to get connection-id after disabling DTLS"); } break; case PROP_KEY: if (self->key) { g_value_set_boxed(value, self->key); } break; case PROP_SRTP_AUTH: g_value_set_string(value, self->srtp_auth); break; case PROP_SRTP_CIPHER: g_value_set_string(value, self->srtp_cipher); break; case PROP_SRTCP_AUTH: g_value_set_string(value, self->srtcp_auth); break; case PROP_SRTCP_CIPHER: g_value_set_string(value, self->srtcp_cipher); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(self, prop_id, pspec); } }
superdump/openwebrtc-gst-plugins
ext/erdtls/src/gsterdtlssrtpdec.c
/* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gsterdtlssrtpdec.h" #include "erdtlsconnection.h" static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS_ANY ); static GstStaticPadTemplate rtp_src_template = GST_STATIC_PAD_TEMPLATE("rtp_src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS("application/x-rtp;application/x-rtcp") ); static GstStaticPadTemplate data_src_template = GST_STATIC_PAD_TEMPLATE("data_src", GST_PAD_SRC, GST_PAD_REQUEST, GST_STATIC_CAPS_ANY ); GST_DEBUG_CATEGORY_STATIC(er_dtls_srtp_dec_debug); #define GST_CAT_DEFAULT er_dtls_srtp_dec_debug #define gst_er_dtls_srtp_dec_parent_class parent_class G_DEFINE_TYPE_WITH_CODE(GstErDtlsSrtpDec, gst_er_dtls_srtp_dec, GST_TYPE_ER_DTLS_SRTP_BIN, GST_DEBUG_CATEGORY_INIT(er_dtls_srtp_dec_debug, "erdtlssrtpdec", 0, "Ericsson DTLS Decoder")); #define UNUSED(param) while (0) { (void)(param); } enum { PROP_0, PROP_PEM, PROP_PEER_PEM, NUM_PROPERTIES }; static GParamSpec *properties[NUM_PROPERTIES]; #define DEFAULT_PEM NULL #define DEFAULT_PEER_PEM NULL static void gst_er_dtls_srtp_dec_set_property(GObject *, guint prop_id, const GValue *, GParamSpec *); static void gst_er_dtls_srtp_dec_get_property(GObject *, guint prop_id, GValue *, GParamSpec *); static GstPad *gst_er_dtls_srtp_dec_request_new_pad(GstElement *, GstPadTemplate *, const gchar *name, const GstCaps *); static GstCaps *on_decoder_request_key(GstElement *srtp_decoder, guint ssrc, GstErDtlsSrtpBin *); static void on_peer_pem(GstElement *srtp_decoder, GParamSpec *pspec, GstErDtlsSrtpDec *self); static void gst_er_dtls_srtp_dec_remove_dtls_element(GstErDtlsSrtpBin *); static GstPadProbeReturn remove_dtls_decoder_probe_callback(GstPad *, GstPadProbeInfo *, GstElement *); static GstPadProbeReturn drop_funnel_rtcp_caps(GstPad *, GstPadProbeInfo *, gpointer); static void gst_er_dtls_srtp_dec_class_init(GstErDtlsSrtpDecClass *klass) { GObjectClass *gobject_class; GstElementClass *element_class; GstErDtlsSrtpBinClass *dtls_srtp_bin_class; gobject_class = (GObjectClass *) klass; element_class = (GstElementClass *) klass; dtls_srtp_bin_class = (GstErDtlsSrtpBinClass *) klass; gobject_class->set_property = GST_DEBUG_FUNCPTR(gst_er_dtls_srtp_dec_set_property); gobject_class->get_property = GST_DEBUG_FUNCPTR(gst_er_dtls_srtp_dec_get_property); element_class->request_new_pad = GST_DEBUG_FUNCPTR(gst_er_dtls_srtp_dec_request_new_pad); dtls_srtp_bin_class->remove_dtls_element = GST_DEBUG_FUNCPTR(gst_er_dtls_srtp_dec_remove_dtls_element); properties[PROP_PEM] = g_param_spec_string("pem", "PEM string", "A string containing a X509 certificate and RSA private key in PEM format", DEFAULT_PEM, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); properties[PROP_PEER_PEM] = g_param_spec_string("peer-pem", "Peer PEM string", "The X509 certificate received in the DTLS handshake, in PEM format", DEFAULT_PEER_PEM, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); g_object_class_install_properties(gobject_class, NUM_PROPERTIES, properties); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&sink_template)); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&rtp_src_template)); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&data_src_template)); gst_element_class_set_static_metadata(element_class, "DTLS-SRTP Decoder", "Decoder/Network/DTLS/SRTP", "Decodes SRTP packets with a key received from DTLS", "<NAME> <EMAIL>"); } static void gst_er_dtls_srtp_dec_init(GstErDtlsSrtpDec *self) { GstElementClass *klass = GST_ELEMENT_GET_CLASS(GST_ELEMENT(self)); GstPadTemplate *templ; GstPad *target_pad, *ghost_pad, *pad; gboolean ret; /* +--------------------+ +--------------+ .-o| erdtlsdec |o-R----------data | dtls|o-' +--------------------+ sink---o| dtlsdemux | | srt(c)p|o-. +-----------+ +-----------+ +--------------+ '-o|srtp rtp|o---o|rtp | | srtpdec | | funnel |o---rt(c)p o|srtcp rtcp|o---o|rtcp | +-----------+ +-----------+ */ self->srtp_dec = gst_element_factory_make("srtpdec", "srtp-decoder"); if (!self->srtp_dec) { GST_ERROR_OBJECT(self, "failed to create srtp_dec, is the srtp plugin registered?"); return; } self->dtls_srtp_demux = gst_element_factory_make("erdtlssrtpdemux", "dtls-srtp-demux"); if (!self->dtls_srtp_demux) { GST_ERROR_OBJECT(self, "failed to create dtls_srtp_demux"); return; } self->bin.dtls_element = gst_element_factory_make("erdtlsdec", "dtls-decoder"); if (!self->bin.dtls_element) { GST_ERROR_OBJECT(self, "failed to create dtls_dec"); return; } self->funnel = gst_element_factory_make("funnel", "funnel"); if (!self->funnel) { GST_ERROR_OBJECT(self, "failed to create funnel"); return; } gst_bin_add_many(GST_BIN(self), self->dtls_srtp_demux, self->bin.dtls_element, self->srtp_dec, self->funnel, NULL); ret = gst_element_link_pads(self->dtls_srtp_demux, "dtls_src", self->bin.dtls_element, NULL); g_return_if_fail(ret); ret = gst_element_link_pads(self->dtls_srtp_demux, "rtp_src", self->srtp_dec, "rtp_sink"); g_return_if_fail(ret); ret = gst_element_link_pads(self->srtp_dec, "rtp_src", self->funnel, "sink_0"); g_return_if_fail(ret); ret = gst_element_link_pads(self->srtp_dec, "rtcp_src", self->funnel, "sink_1"); g_return_if_fail(ret); pad = gst_element_get_static_pad(self->funnel, "sink_1"); gst_pad_add_probe(pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, drop_funnel_rtcp_caps, NULL, NULL); gst_object_unref(pad); templ = gst_element_class_get_pad_template(klass, "rtp_src"); target_pad = gst_element_get_static_pad(self->funnel, "src"); ghost_pad = gst_ghost_pad_new_from_template("rtp_src", target_pad, templ); gst_object_unref(target_pad); g_return_if_fail(ghost_pad); ret = gst_element_add_pad(GST_ELEMENT(self), ghost_pad); g_return_if_fail(ret); templ = gst_element_class_get_pad_template(klass, "sink"); target_pad = gst_element_get_static_pad(self->dtls_srtp_demux, "sink"); ghost_pad = gst_ghost_pad_new_from_template("sink", target_pad, templ); gst_object_unref(target_pad); g_return_if_fail(ghost_pad); ret = gst_element_add_pad(GST_ELEMENT(self), ghost_pad); g_return_if_fail(ret); g_signal_connect(self->srtp_dec, "request-key", G_CALLBACK(on_decoder_request_key), self); g_signal_connect(self->bin.dtls_element, "notify::peer-pem", G_CALLBACK(on_peer_pem), self); } static void gst_er_dtls_srtp_dec_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { GstErDtlsSrtpDec *self = GST_ER_DTLS_SRTP_DEC(object); switch (prop_id) { case PROP_PEM: if (self->bin.dtls_element) { g_object_set_property(G_OBJECT(self->bin.dtls_element), "pem", value); } else { GST_WARNING_OBJECT(self, "tried to set pem after disabling DTLS"); } break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(self, prop_id, pspec); } } static void gst_er_dtls_srtp_dec_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { GstErDtlsSrtpDec *self = GST_ER_DTLS_SRTP_DEC(object); switch (prop_id) { case PROP_PEM: if (self->bin.dtls_element) { g_object_get_property(G_OBJECT(self->bin.dtls_element), "pem", value); } else { GST_WARNING_OBJECT(self, "tried to get pem after disabling DTLS"); } break; case PROP_PEER_PEM: if (self->bin.dtls_element) { g_object_get_property(G_OBJECT(self->bin.dtls_element), "peer-pem", value); } else { GST_WARNING_OBJECT(self, "tried to get peer-pem after disabling DTLS"); } break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(self, prop_id, pspec); } } static GstPad *gst_er_dtls_srtp_dec_request_new_pad(GstElement *element, GstPadTemplate *templ, const gchar *name, const GstCaps *caps) { GstErDtlsSrtpDec *self = GST_ER_DTLS_SRTP_DEC(element); GstElementClass *klass = GST_ELEMENT_GET_CLASS(element); GstPad *ghost_pad = NULL; gboolean ret; GST_DEBUG_OBJECT(element, "pad requested"); g_return_val_if_fail(self->bin.dtls_element, NULL); g_return_val_if_fail(!self->bin.key_is_set, NULL); if (templ == gst_element_class_get_pad_template(klass, "data_src")) { GstPad *target_pad; target_pad = gst_element_get_request_pad(self->bin.dtls_element, "src"); ghost_pad = gst_ghost_pad_new_from_template(name, target_pad, templ); gst_object_unref(target_pad); g_return_val_if_fail(ghost_pad, NULL); ret = gst_pad_set_active(ghost_pad, TRUE); g_return_val_if_fail(ret, NULL); ret = gst_element_add_pad(element, ghost_pad); g_return_val_if_fail(ret, NULL); GST_LOG_OBJECT(self, "added data src pad"); if (caps) { g_object_set(ghost_pad, "caps", caps, NULL); } return ghost_pad; } g_return_val_if_reached(NULL); } static GstCaps *on_decoder_request_key(GstElement *srtp_decoder, guint ssrc, GstErDtlsSrtpBin *bin) { GstCaps *key_caps; GstBuffer *key_buffer = NULL; guint cipher; guint auth; if (bin->key_is_set) { if (bin->key) { if (bin->srtp_cipher && bin->srtp_auth && bin->srtcp_cipher && bin->srtcp_auth) { GST_DEBUG_OBJECT(bin, "setting srtp key"); return gst_caps_new_simple("application/x-srtp", "srtp-key", GST_TYPE_BUFFER, gst_buffer_copy(bin->key), "srtp-auth", G_TYPE_STRING, bin->srtp_auth, "srtcp-auth", G_TYPE_STRING, bin->srtcp_auth, "srtp-cipher", G_TYPE_STRING, bin->srtp_cipher, "srtcp-cipher", G_TYPE_STRING, bin->srtcp_cipher, NULL); } else { GST_WARNING_OBJECT(bin, "srtp key is set but not all ciphers and auths"); return NULL; } } GST_DEBUG_OBJECT(bin, "setting srtp key to null"); return gst_caps_new_simple("application/x-srtp", "srtp-key", GST_TYPE_BUFFER, NULL, "srtp-auth", G_TYPE_STRING, "null", "srtcp-auth", G_TYPE_STRING, "null", "srtp-cipher", G_TYPE_STRING, "null", "srtcp-cipher", G_TYPE_STRING, "null", NULL); } if (bin->dtls_element) { g_object_get(bin->dtls_element, "decoder-key", &key_buffer, NULL); } if (key_buffer) { g_object_get(bin->dtls_element, "srtp-cipher", &cipher, "srtp-auth", &auth, NULL); g_return_val_if_fail(cipher == ER_DTLS_SRTP_CIPHER_AES_128_ICM, NULL); key_caps = gst_caps_new_simple("application/x-srtp", "srtp-key", GST_TYPE_BUFFER, key_buffer, "srtp-cipher", G_TYPE_STRING, "aes-128-icm", "srtcp-cipher", G_TYPE_STRING, "aes-128-icm", NULL); switch (auth) { case ER_DTLS_SRTP_AUTH_HMAC_SHA1_32: gst_caps_set_simple(key_caps, "srtp-auth", G_TYPE_STRING, "hmac-sha1-32", "srtcp-auth", G_TYPE_STRING, "hmac-sha1-32", NULL); break; case ER_DTLS_SRTP_AUTH_HMAC_SHA1_80: gst_caps_set_simple(key_caps, "srtp-auth", G_TYPE_STRING, "hmac-sha1-80", "srtcp-auth", G_TYPE_STRING, "hmac-sha1-80", NULL); break; default: g_return_val_if_reached(NULL); break; } return key_caps; } return NULL; } static void on_peer_pem(GstElement *srtp_decoder, GParamSpec *pspec, GstErDtlsSrtpDec *self) { UNUSED(srtp_decoder); UNUSED(pspec); g_return_if_fail(self); g_object_notify_by_pspec(G_OBJECT(self), properties[PROP_PEER_PEM]); } static void gst_er_dtls_srtp_dec_remove_dtls_element(GstErDtlsSrtpBin *bin) { GstErDtlsSrtpDec *self = GST_ER_DTLS_SRTP_DEC(bin); GstPad *demux_pad; gulong id; if (!bin->dtls_element) { return; } demux_pad = gst_element_get_static_pad(self->dtls_srtp_demux, "dtls_src"); id = gst_pad_add_probe(demux_pad, GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM, (GstPadProbeCallback) remove_dtls_decoder_probe_callback, bin->dtls_element, NULL); g_return_if_fail(id); bin->dtls_element = NULL; gst_pad_push_event(demux_pad, gst_event_new_custom(GST_EVENT_CUSTOM_DOWNSTREAM, gst_structure_new_empty("dummy"))); gst_object_unref(demux_pad); } static GstPadProbeReturn remove_dtls_decoder_probe_callback(GstPad *pad, GstPadProbeInfo *info, GstElement *element) { gst_pad_remove_probe(pad, GST_PAD_PROBE_INFO_ID(info)); gst_element_set_state(GST_ELEMENT(element), GST_STATE_NULL); gst_bin_remove(GST_BIN(GST_ELEMENT_PARENT(element)), element); return GST_PAD_PROBE_OK; } static GstPadProbeReturn drop_funnel_rtcp_caps(GstPad *pad, GstPadProbeInfo *info, gpointer data) { return (GST_EVENT_TYPE(gst_pad_probe_info_get_event(info)) == GST_EVENT_CAPS) ? GST_PAD_PROBE_DROP : GST_PAD_PROBE_OK; }
superdump/openwebrtc-gst-plugins
ext/erdtls/src/erdtlscertificate.h
/* * Copyright (c) 2014, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #ifndef erdtlscertificate_h #define erdtlscertificate_h #include <glib-object.h> G_BEGIN_DECLS #define ER_TYPE_DTLS_CERTIFICATE (er_dtls_certificate_get_type()) #define ER_DTLS_CERTIFICATE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), ER_TYPE_DTLS_CERTIFICATE, ErDtlsCertificate)) #define ER_DTLS_CERTIFICATE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), ER_TYPE_DTLS_CERTIFICATE, ErDtlsCertificateClass)) #define ER_IS_DTLS_CERTIFICATE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), ER_TYPE_DTLS_CERTIFICATE)) #define ER_IS_DTLS_CERTIFICATE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), ER_TYPE_DTLS_CERTIFICATE)) #define ER_DTLS_CERTIFICATE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), ER_TYPE_DTLS_CERTIFICATE, ErDtlsCertificateClass)) typedef gpointer ErDtlsCertificateInternalCertificate; typedef gpointer ErDtlsCertificateInternalKey; typedef struct _ErDtlsCertificate ErDtlsCertificate; typedef struct _ErDtlsCertificateClass ErDtlsCertificateClass; typedef struct _ErDtlsCertificatePrivate ErDtlsCertificatePrivate; /* * ErDtlsCertificate: * * Handles a X509 certificate and a private key. * If a certificate is created without the "pem" property, a self-signed certificate is generated. */ struct _ErDtlsCertificate { GObject parent_instance; ErDtlsCertificatePrivate *priv; }; struct _ErDtlsCertificateClass { GObjectClass parent_class; }; GType er_dtls_certificate_get_type(void) G_GNUC_CONST; /* internal */ ErDtlsCertificateInternalCertificate _er_dtls_certificate_get_internal_certificate(ErDtlsCertificate *); ErDtlsCertificateInternalKey _er_dtls_certificate_get_internal_key(ErDtlsCertificate *); gchar *_er_dtls_x509_to_pem(gpointer x509); G_END_DECLS #endif /* erdtlscertificate_h */
jjyangjian/-
projectOC/projectContent/allControllers/tongzhi/JJRootTongzhiController.h
// // JJRootTongzhiController.h // shebeijiance // // Created by 杨剑 on 2019/3/26. // Copyright © 2019 jjyangjian. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface JJRootTongzhiController : UITableViewController @end NS_ASSUME_NONNULL_END
jjyangjian/-
projectOC/projectContent/tool/JJDownload.h
<filename>projectOC/projectContent/tool/JJDownload.h // // JJDownload.h // jjxinfadi // // Created by CMP on 2018/7/14. // Copyright © 2018年 ChiefCadet. All rights reserved. // #define CODE_KEY @"code"//返回数据时,code的key,一般为,code,state 等 #define CODEMESSAGE_KEY @"message"//返回消息的key值 #define CODE_VALUE_SUCCESS @"0"//成功的code值 #define CODE_VALUE_OTHERLOGIN @"500"//其他设备登录的code值 #define CODE_VALUE_NOLOGIN @"499"//未登录的code值 #define CODEMESSAGE_VALUE_NOLOGIN @"未登录,请登录"//未登录的message //设定后台返回空的时候 #define CODE_VALUE_NULL @"-10" #define CODEMESSAGE_VALUE_NULL @"返回值为空" //设定请求成功但code值有问题的时候 #define CODEMESSAGE_VALUE_SUCCESSERROR @"正确回调,code错误" //设定走错误回调时 #define CODE_VALUE_ERROR @"-11" #define CODEMESSAGE_VALUE_ERROR @"错误" #import <Foundation/Foundation.h> #import <AFNetworking.h> @interface JJDownload : NSObject typedef void (^JJUpdateDataSuccessBlock)(NSDictionary * _Nonnull responseObject); typedef void (^JJUpdateDataFailBlock)(NSError * _Nullable error,NSString *message,NSString *code); typedef void (^JJUpdateDataProgressBlock)(NSProgress *progress); typedef void (^JJURLSessionManagerSuccessBlock)(NSString * _Nonnull message,NSDictionary * _Nullable responseObject); typedef void (^JJURLSessionManagerFailureBlock)(NSError * _Nonnull error); //普通下载数据 + (void)downloadDataWithIsPost:(BOOL)isPost andURLString:(NSString *)urlString andParameter:(NSDictionary *)parameter andSuccessBlock:(JJUpdateDataSuccessBlock)successBlock andFailBlock:(JJUpdateDataFailBlock)failBlock; //测试使用 + (void)ceshidownloadDataWithIsPost:(BOOL)isPost andURLString:(NSString *)urlString andParameter:(NSDictionary *)parameter andSuccessBlock:(JJUpdateDataSuccessBlock)successBlock andFailBlock:(JJUpdateDataFailBlock)failBlock; //post上传图片,传入data + (void)uploadOneImageDataWithURLString:(NSString *)urlString andParameter:(NSDictionary *)parameter andImageInfo:(NSDictionary *)imageInfo andUpdateDataProgressBlock:(JJUpdateDataProgressBlock)progressBlock andSuccessBlock:(JJUpdateDataSuccessBlock)successBlock andFailBlock:(JJUpdateDataFailBlock)failBlock; //post上传多张图片 <图片规则,data,name 两个字典参数> + (void)uploadMoreImageDataWithURLString:(NSString *)urlString andParameter:(NSDictionary *)parameter andImageInfoArray:(NSArray *)imageInfoArray andUpdateDataProgressBlock:(JJUpdateDataProgressBlock)progressBlock andSuccessBlock:(JJUpdateDataSuccessBlock)successBlock andFailBlock:(JJUpdateDataFailBlock)failBlock; /* 可传空 urlSessionConfiguration $$$ 传空即可 method $$$ @"GET"或@"POST",也可传空,默认为 @"GET" content_Type $$$ 传入的格式,可传空,默认为 @"application/json" accept $$$ 接收的格式,可传空,默认为 @"application/json" urlString $$$ 请求地址 needToken $$$ 是否需要token (token $$$ 自动在全局中获取了,如果需要另外设置,则改内部) bodyDictionary $$$ 请求体,传入个字典进去即可 uploadProgressBlock $$$ 上传的回调 (这个回调好像被调用一次) downloadProgressBlock $$$ 下载的回调 (这个回调好像还没被调用过) successBlock $$$ 改进的回调,成功回调 failureBlock $$$ 改进的回调,失败回调 completionHandlerBlock $$$ 这是原汁原味的任务结束回调,需要根据error来判断成功与否 */ //是否需要原汁原味 #define YUANZHIYUANWEI 0 + (void)urlSessionWithURLSessionConfiguration:(NSURLSessionConfiguration *_Nullable)urlSessionConfiguration andContent_Type:(NSString * _Nullable )content_Type andAccept:(NSString * _Nullable )accept andMethod:(NSString * _Nonnull )method andURLString:(NSString *_Nonnull)urlString andBodyDictionary:(NSDictionary * _Nullable )bodyDictionary andNeedToken:(BOOL)needToken // andToken:(NSString *)token andUploadProgressBlock:(nullable void (^)(NSProgress * _Nullable uploadProgress)) uploadProgressBlock andDownloadProgressBlock:(nullable void (^)(NSProgress * _Nullable downloadProgress)) downloadProgressBlock #if YUANZHIYUANWEI andCompletionHandlerBlock:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandlerBlock #else andSuccessBlock:(JJURLSessionManagerSuccessBlock _Nonnull )successBlock andFailureBlock:(JJURLSessionManagerFailureBlock _Nonnull )failureBlock #endif ; + (void)login_Method:(NSString * _Nonnull )method andURLString:(NSString * _Nonnull )urlString andBodyDictionary:(NSDictionary * _Nullable )bodyDictionary andSuccessBlock:(JJURLSessionManagerSuccessBlock _Nonnull )successBlock andFailureBlock:(JJURLSessionManagerFailureBlock _Nonnull )failureBlock; //是否需要token获取数据(body) + (void)getData_Method:(NSString * _Nonnull )method andURLString:(NSString *_Nonnull)urlString andBody:(NSDictionary * _Nullable )bodyDictionary andNeedToken:(BOOL)needToken andSuccessBlock:(JJURLSessionManagerSuccessBlock _Nonnull )successBlock andFailureBlock:(JJURLSessionManagerFailureBlock _Nonnull )failureBlock; //是否需要token获取数据(parameter) + (void)getData_Method:(NSString * _Nonnull )method andURLString:(NSString *_Nonnull)urlString andParameter:(NSDictionary * _Nullable )parameter andNeedToken:(BOOL)needToken andSuccessBlock:(JJURLSessionManagerSuccessBlock _Nonnull )successBlock andFailureBlock:(JJURLSessionManagerFailureBlock _Nonnull )failureBlock; @end
jjyangjian/-
projectOC/projectContent/allControllers/tabbar/JJTabbarController.h
// // JJTabbarController.h // xiaoyulvtu // // Created by 杨剑 on 2018/10/19. // Copyright © 2018年 贱贱. All rights reserved. // #import <UIKit/UIKit.h> #import <AudioToolbox/AudioToolbox.h> //#import "JJRootShebeiController.h" //#import "JJRootTongzhiController.h" //#import "JJRootWoController.h" #import "JJJianceController.h" #import "JJDitushebeiController.h" #import "JJTongjiController.h" #import "JJShebeiliebiaoController.h" #import "JJWodeController.h" @interface JJTabbarController : UITabBarController - (void)qiehuanShebei; @end
jjyangjian/-
projectOC/projectContent/tool/JJURLHeader.h
// // JJURLHeader.h // jjxinfadi // // Created by CMP on 2018/7/14. // Copyright © 2018年 ChiefCadet. All rights reserved. //http://www.lolhelper.cn/analyse_word.php? #ifndef JJURLHeader_h #define JJURLHeader_h //前面固定部分 #define JJBASEURLSTRING @"http://172.16.31.10:8084" //#define JJBASEURLSTRING @"http://192.168.1.150:8084" /* 接口登录获取token 请求类型 POST 接口地址 /api/login 参数类型 json 返回类型 json 请求参数示例 { "username":"zyf3","password":"<PASSWORD>" } */ #define JJURLSTRING_api_login [NSString stringWithFormat:@"%@/api/login",JJBASEURLSTRING] /* 接口名称 设备列表 请求类型 POST 接口地址 /api/eq/list/my 参数类型 PathVariable 返回类型 JSON 请求参数示例 /api/eq/list/my */ #define JJURLSTRING_api_eq_list_my [NSString stringWithFormat:@"%@/api/eq/list/my",JJBASEURLSTRING] /* 接口名称 设备信息 请求类型 GET 接口地址 /api/eq/info/{eqid} 参数类型 PathVariable 返回类型 json 请求参数示例 /api/eq/info/300000 */ #define JJURLSTRING_api_eq_info_(deviceID) [NSString stringWithFormat:@"%@/api/eq/info/%@",JJBASEURLSTRING,deviceID] /* 接口名称 历史列表 请求类型 GET 接口地址 /api/history/data/list/title 参数类型 RequestParam historyDataType:列表类型1(数据)、2(报警)、3(报表);eqId:设备id 返回类型 json 请求参数示例 /api/history/data/list/title?historyDataType=1&eqId=300000 */ #define JJURLSTRING_api_history_data_list_title [NSString stringWithFormat:@"%@/api/history/data/list/title",JJBASEURLSTRING] /* 接口名称 历史列表 请求类型 POST 接口地址 /api/history/data/list 参数类型 json eqId:设备id ; historyDataType: 列表类型1(数据)、2(报警)、3(报表); beginTime:开始时间; endTime:结束时间; pageSize:每页显示条数; pageNum:页码; orderByColumn:排序字段; isAsc:排序方式; 返回类型 json 请求参数示例 {"eqId":"300000","historyDataType":"1","beginTime":"2019-04-17","endTime":"2019-04-17","pageSize":15,"pageNum":1,"orderByColumn":"addTime","isAsc":"desc"} */ #define JJURLSTRING_api_history_data_list [NSString stringWithFormat:@"%@/api/history/data/list",JJBASEURLSTRING] /* 6.报警-日列表 接口名称 历史列表 备注 请求类型 POST 接口地址 /api/alarm/list/day 参数类型 json 返回类型 json 请求参数示例 {"eqId":"300000","beginTime":"2019-04-01","endTime":"2019-04-01","historyDataType":"2","pageSize":15,"pageNum":1,"orderByColumn":"addTime","isAsc":"desc"} */ #define JJURLSTRING_api_alarm_list_day [NSString stringWithFormat:@"%@/api/alarm/list/day",JJBASEURLSTRING] /* 8.报警数量-月统计 接口名称 报警数量 按月统计每日报警数量 请求类型 GET 接口地址 /api/alarm/report/month/{eqId}/{dateMonth} eqId (设备id) dateMonth(某月) 2019-04 参数类型 PathVariable 返回类型 json 请求参数示例 /api/alarm/report/month/300000/2019-04 */ #define JJURLSTRING_api_alarm_report_month_(deviceID,YearMonth) [NSString stringWithFormat:@"%@/api/alarm/report/month/%@/%@",JJBASEURLSTRING,deviceID,YearMonth] /* 11.峰值统计 接口名称 平均值-最大值-最小值 备注 请求类型 POST 日期相同为一天内时报,否则日报 接口地址 /api/report/peak/{eqId}/{daterange} eqid 设备id daterange 时间段 参数类型 pathvalue 返回类型 json 请求参数示例 /api/report/peak/300000/2019-04-15_2019-04-19 */ #define JJURLSTRING_api_report_peak_(deviceID,startTime,endTime) [NSString stringWithFormat:@"%@/api/report/peak/%@/%@_%@",JJBASEURLSTRING,deviceID,startTime,endTime] /* 5.历史数据-指定数量 接口名称 历史数据 返回指定数量的历史数据 请求类型 GET 接口地址 /api/history/data/top/{num}/{eqId} 参数类型 PathVariable num(数量) eqId(设备id) 返回类型 json 请求参数示例 /api/history/data/top/1/300000 */ #define JJURLSTRING_api_history_data_top_(count,deviceID) [NSString stringWithFormat:@"%@/api/history/data/top/%@/%@",JJBASEURLSTRING,count,deviceID] #endif
jjyangjian/-
projectOC/projectContent/tool/JJExtern.h
// // JJExtern.h // jjxinfadi // // Created by CMP on 2018/7/13. // Copyright © 2018年 ChiefCadet. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "JJXuanzeshebeiView.h" @interface JJExtern : NSObject //+(instancetype) alloc __attribute__((unavailable("call sharedInstance instead"))); //+(instancetype) new __attribute__((unavailable("call sharedInstance instead"))); //-(instancetype) copy __attribute__((unavailable("call sharedInstance instead"))); //-(instancetype) mutableCopy __attribute__((unavailable("call sharedInstance instead"))); typedef void (^JJExternBlock)(NSDictionary *dic ,NSString *msg,int code); @property (nonatomic,strong)NSString *username; @property (nonatomic,strong)NSString *password; @property (nonatomic,strong)NSString *token; /* 设备的参数 categoryId = 110; categoryName = "<null>"; deptId = 104; eqId = 300000; eqName = "ph\U4f20\U611f\U5668"; mapXy = "114.434634,38.035341"; orderNum = 2; remark = "<null>"; status = 0; userId = "<null>"; */ @property (nonatomic,strong)NSArray <NSDictionary *>*devices;//多台设备 @property (nonatomic,strong)NSString *currentDeviceID;//当前设备的id @property (nonatomic,strong)NSDictionary *currentDevice;//当前设备的id @property (nonatomic,strong)NSString *userid; @property (nonatomic,strong)NSString *phone; @property (nonatomic,strong)NSString *headimageurlstring;//头像地址 @property (nonatomic,strong)NSString *name;//姓名 //@property (nonatomic,strong)NSString *nickname;//姓名 @property (nonatomic,strong)NSString *sex;//性别 + (void)showXuanzeshebeiViewForViewController:(UIViewController *)viewController andSelectedDevice:(JJXuanzeshebeiViewSelectedDeviceBlock)selectedDeviceBlock andHideBlock:(JJXuanzeshebeiViewHideBlock)hideBlock; + (instancetype)sharedJJ; + (void)gotoDengluController; @end //other类,比较杂的东西 @interface JJOther : NSObject typedef void (^JJButtonBlock)(long buttonTag); //判断是否异形屏 + (BOOL)is_iPhoneX; + (UIColor*)colorWithHexString:(NSString*)stringToConvert; + (NSString *)getDifferentString; + (NSData *)compressImage:(UIImage *)image MaxLength:(NSUInteger)maxLength; @end @interface JJDate : NSObject /* 获取当前 时间戳 */ + (NSTimeInterval)getTimeNowTimestamp; /* 获取当前 时间 @"yyyy-MM-dd" @"yyyy-MM-dd HH:mm" @"yyyy-MM-dd HH:mm:ss" */ + (NSString *)getTimeNowTimeStringWithFormatString:(NSString *)formatString; /* 根据 时间 获取 时间戳 2000-01-01 12:00:00 @"yyyy-MM-dd" @"yyyy-MM-dd HH:mm" @"yyyy-MM-dd HH:mm:ss" */ + (NSTimeInterval)getTimestampStringWithTimeString:(NSString *)timeString andFormatString:(NSString *)formatString; /* 根据时间戳获取时间 @"yyyy-MM-dd" @"yyyy-MM-dd HH:mm" @"yyyy-MM-dd HH:mm:ss" */ + (NSString *)getTimeTimeStringWithTimestampString:(NSString *)timestampString andFormatString:(NSString *)formatString; //根据date获取年 + (NSInteger)calendar_yearFromDate:(NSDate *)date ; //根据date获取月 + (NSInteger)calendar_monthFromDate:(NSDate *)date ; //根据date获取日 + (NSInteger)calendar_dayFromDate:(NSDate *)date ; //根据date 获取 当日 周几 (美国时间周日-周六为 1-7,改为0-6方便计算) + (NSInteger)calendar_weekdayFromDate:(NSDate *)date ; //根据date获取 当月第一天 周几 + (NSInteger)calendar_weekdayOfMonthFromDate:(NSDate *)date ; //根据date获取当月总天数 + (NSInteger)calendar_totalDaysOfMonthFromDate:(NSDate *)date ; @end #import <QuartzCore/QuartzCore.h> @interface CALayer (Extension) /* 1.layer.cornerRadius ,注意该 key 对应 Value 的 type 应该设置为 String/Number 两种类型均可 2.layer.masksToBounds ,注意该 key 对应 Value 的 type 应该设置为 Boolean 3.layer.borderWidth ,注意该 key 对应 Value 的 type 应该设置为 String/Number 两种类型均可 4.layer.borderColorFromUIColor 注意该 key 对应 Value 的 type 应该设置为color 并且需要加CALayer的分类、 layer.borderColorFromUIColor */ - (void)setBorderColorFromUIColor:(UIColor *)color; @end /* */
jjyangjian/-
projectOC/projectContent/jjmqtt/JJMQTTManager.h
<reponame>jjyangjian/-<filename>projectOC/projectContent/jjmqtt/JJMQTTManager.h // // JJMQTTManager.h // shebeijiance // // Created by 杨剑 on 2019/3/30. // Copyright © 2019 jjyangjian. All rights reserved. // #import <Foundation/Foundation.h> #import <MQTTClient.h> NS_ASSUME_NONNULL_BEGIN //host: 服务器地址 #define JJMQTT_HOST @"192.168.3.11" //part: 服务器端口 #define JJMQTT_PORT 9090 //#define JJMQTT_PORT 9091 //tls:是否使用tls协议,mosca是支持tls的,如果使用了要设置成true #define JJMQTT_TLS 1 //keepalive: 心跳时间,单位秒,每隔固定时间发送心跳包, 心跳间隔不得大于120s #define JJMQTT_KEEPALIVE 20 //clean: session是否清除,这个需要注意,如果是false,代表保持登录,如果客户端离线了再次登录就可以接收到离线消息 #define JJMQTT_CLEAN 1 //auth: 是否使用登录验证 #define JJMQTT_AUTH true //user: 用户名 #define JJMQTT_USER @"zrkj01" //pass: 密码 #define JJMQTT_PASS @"<PASSWORD>" //willTopic: 订阅主题 #define JJMQTT_WILL_TOPIC @"/cio/01/data/300000/+" //willMsg: 自定义的离线消息 #define JJMQTT_WILL_MSG @"mqtt" //willQos: 接收离线消息的级别 #define JJMQTT_WILL_QOS 1 //clientId: 客户端id,需要特别指出的是这个id需要全局唯一,因为服务端是根据这个来区分不同的客户端的,默认情况下一个id登录后,假如有另外的连接以这个id登录,上一个连接会被踢下线, 我使用的设备UUID #define JJMQTT_CLIENT_ID @"txm_1554341296" @class JJMQTTManager; @protocol JJMQTTManagerDelegate <NSObject> //接收.好像握手时候用到了 - (void)mqttManager:(JJMQTTManager *)manager received:(MQTTSession *)session type:(MQTTCommandType)type qos:(MQTTQosLevel)qos retained:(BOOL)retained duped:(BOOL)duped mid:(UInt16)mid data:(NSData *)data; //连接成功 - (void)mqttManager:(JJMQTTManager *)manager connected:(MQTTSession *)session; //返回内容 - (void)mqttManager:(JJMQTTManager *)manager newMessage:(MQTTSession *)session data:(NSData*)data onTopic:(NSString*)topic qos:(MQTTQosLevel)qos retained:(BOOL)retained mid:(unsigned int)mid; //关闭 - (void)mqttManager:(JJMQTTManager *)manager connectionClosed:(MQTTSession *)session; //错误 - (void)mqttManager:(JJMQTTManager *)manager connectionError:(MQTTSession *)session error:(NSError *)error; //拒绝 - (void)mqttManager:(JJMQTTManager *)manager connectionRefused:(MQTTSession *)session error:(NSError *)error; //向后兼容,暂时无用 - (void)mqttManager:(JJMQTTManager *)manager session:(MQTTSession*)session newMessage:(NSData*)data onTopic:(NSString*)topic; //处理事件 - (void)mqttManager:(JJMQTTManager *)manager handleEvent:(MQTTSession *)session event:(MQTTSessionEvent)eventCode error:(NSError *)error; @end @interface JJMQTTManager : NSObject @property (nonatomic,weak)id <JJMQTTManagerDelegate> delegate; @property (nonatomic,strong)NSString *topic; - (instancetype)initWithDelegate:(id)delegate; - (void)mqttConnect; @end NS_ASSUME_NONNULL_END
jjyangjian/-
projectOC/projectContent/jjwifi/JJWiFiController.h
// // JJWiFiController.h // shebeijiance // // Created by 杨剑 on 2019/4/4. // Copyright © 2019 jjyangjian. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface JJWiFiController : UIViewController @end NS_ASSUME_NONNULL_END
jjyangjian/-
projectOC/projectContent/allControllers/tongzhi/JJRootTongzhiCell.h
<reponame>jjyangjian/- // // JJRootTongzhiCell.h // shebeijiance // // Created by 杨剑 on 2019/3/26. // Copyright © 2019 jjyangjian. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface JJRootTongzhiCell : UITableViewCell @end NS_ASSUME_NONNULL_END
jjyangjian/-
projectOC/projectContent/allControllers/shebeixiangqing/JJShebeixiangqing2Cell.h
<gh_stars>0 // // JJShebeixiangqing2Cell.h // shebeijiance // // Created by 杨剑 on 2019/3/28. // Copyright © 2019 jjyangjian. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface JJShebeixiangqing2Cell : UITableViewCell @end NS_ASSUME_NONNULL_END
livesxu/LXAOPTask
LXAopTaskDemo/LXAopTask/LXAOPTask+TaskTest.h
<reponame>livesxu/LXAOPTask // // LXAOPTask+TaskTest.h // LXAopTask // // Created by livesxu on 2018/9/10. // Copyright © 2018年 Livesxu. All rights reserved. // #import "LXAOPTask.h" @interface LXAOPTask (TaskTest) + (NSDictionary *)taskTestConfig; @end
livesxu/LXAOPTask
LXAopTaskDemo/LXAopTask/NextViewController.h
<filename>LXAopTaskDemo/LXAopTask/NextViewController.h // // NextViewController.h // LXAopTask // // Created by livesxu on 2018/9/10. // Copyright © 2018年 Livesxu. All rights reserved. // #import <UIKit/UIKit.h> @interface NextViewController : UIViewController @end
livesxu/LXAOPTask
LXAopTaskDemo/LXAopTask/LXAOPTask.h
// // AOPTask.h // Shuzan // // Created by Xu小波 on 2018/2/7. // Copyright © 2018年 Shujin. All rights reserved. //注意点:1.hook最好在控制器留下痕迹,否则很容易造坑 - 我一般使用taskHold // 2.aspects 类hook 都会被保存到NSObject应用上,AspectTracker为防止同一方法被多次hook,导致 类hook 方法都不能一样,可以像截图处理,但 需手动保证类方法不被多次hook //hook格式: /* taskConfig: @{ @"className1":@{@"HookSEL":HandlerBlock, @"HookSEL1":HandlerBlock1, }, @"className2":@{@"HookSEL":HandlerBlock, @"HookSEL1":HandlerBlock1, }, } */ #import <UIKit/UIKit.h> #import <Aspects/Aspects.h> //#define AOPTaskEventSELName @"AOPTaskEventHookSEL" //#define AOPTaskEventHandlerBlock @"AOPTaskEventHandlerBlock" typedef void (^AspectHandlerBlock)(id<AspectInfo> aspectInfo); @interface LXAOPTask : NSObject + (void)performTask:(NSDictionary *)taskConfig; @end
yangxiangwei/YXWFirst
View/UIColor+XJ.h
// // UIColor+XJ.h // WhiteDragon // // Created by rxj on 16/1/17. // Copyright © 2016年 YongLibao. All rights reserved. // #import <UIKit/UIKit.h> @interface UIColor (XJ) + (UIColor *)colorWithstartColor:(UIColor *)startColor endColor:(UIColor *)endColor fraction:(CGFloat)fraction; /** * 获取UIColor(已经除了255.0) * * @param red 255 红 * @param green 255 绿 * @param blue 255 蓝 * * @return UIColor */ + (UIColor *)colorWithR:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue; /** * 获取UIColor(已经除了255.0) * * @param red 255 红 * @param green 255 绿 * @param blue 255 蓝 * @param alpha 1.0 透明度 * * @return UIColor */ + (UIColor *)colorWithR:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha; /** * 通过16进制获取颜色 * * @param colorString (0x123443 ,#232322 ,232322) * * @return UIColor */ + (UIColor *)colorWithHexString:(NSString *)colorString; @end
yangxiangwei/YXWFirst
View/YLBVerificationCodeButton.h
// // YLBValidcodeButton.h // RRHua // // Created by liyang on 16/9/28. // Copyright © 2016年 yangxiangwei. All rights reserved. // #import <UIKit/UIKit.h> @interface YLBVerificationCodeButton : UIButton /** 开始倒计时 @param second 开始倒计时的秒数 比如:200 */ - (void)efStartTimingWithSecond:(int)second; /** 设置默认标题 默认为 获取验证码 @param buttonTitle 标题 */ -(void)efSetOriginButtonTitle:(NSString *)buttonTitle; @end
pavankumarbn/VTKExamples
src/Cxx/Developers/vtkTestGraphAlgorithmSource.h
<gh_stars>1-10 #ifndef __vtkTestGraphAlgorithmSource_h #define __vtkTestGraphAlgorithmSource_h #include <vtkGraphAlgorithm.h> class vtkTestGraphAlgorithmSource : public vtkGraphAlgorithm { public: static vtkTestGraphAlgorithmSource *New(); vtkTypeMacro(vtkTestGraphAlgorithmSource,vtkGraphAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); protected: vtkTestGraphAlgorithmSource(); ~vtkTestGraphAlgorithmSource(); int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); int RequestDataObject(vtkInformation *, vtkInformationVector **, vtkInformationVector *); private: vtkTestGraphAlgorithmSource(const vtkTestGraphAlgorithmSource&); // Not implemented. void operator=(const vtkTestGraphAlgorithmSource&); // Not implemented. }; #endif