code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
# Copyright (C) 2012 The Libphonenumber 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. # Author: Fredrik Roubert # It used to be common to provide pre-compiled Google Test libraries, but this # practice is not recommended and is increasingly rare today: # # http://code.google.com/p/googletest/wiki/FAQ#Why_is_it_not_recommended_to_install_a_pre-compiled_copy_of_Goog # # This helper function will either find a pre-compiled library or else find the # source code and add a library target to build the library from source. function (find_or_build_gtest) # Find header files. find_path (GTEST_INCLUDE_DIR gtest/gtest.h) if (${GTEST_INCLUDE_DIR} STREQUAL "GTEST_INCLUDE_DIR-NOTFOUND") message (FATAL_ERROR "Can't find Google C++ Testing Framework: can't locate gtest/gtest.h. " "Please read the README and also take a look at tools/cpp/gtest.cmake.") endif () include_directories (${GTEST_INCLUDE_DIR}) # Check for a pre-compiled library. find_library (GTEST_LIB gtest) if (${GTEST_LIB} STREQUAL "GTEST_LIB-NOTFOUND") # No pre-compiled library found, attempt building it from source. find_path (GTEST_SOURCE_DIR src/gtest-all.cc HINTS /usr/src/gtest /usr/local/src/gtest) add_library (gtest STATIC ${GTEST_SOURCE_DIR}/src/gtest-all.cc) include_directories (${GTEST_SOURCE_DIR}) set (GTEST_LIB gtest PARENT_SCOPE) endif () endfunction ()
2301_81045437/third_party_libphonenumber
tools/cpp/gtest.cmake
CMake
unknown
1,913
// Copyright (c) 2010 The Chromium 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 BASE_BASICTYPES_H_ #define BASE_BASICTYPES_H_ #pragma once #include <limits.h> // So we can set the bounds of our types #include <stddef.h> // For size_t #include <string.h> // for memcpy #ifndef COMPILER_MSVC // stdint.h is part of C99 but MSVC doesn't have it. #include <stdint.h> // For intptr_t. #endif #ifdef INT64_MAX // INT64_MAX is defined if C99 stdint.h is included; use the // native types if available. typedef int8_t int8; typedef int16_t int16; typedef int32_t int32; typedef int64_t int64; typedef uint8_t uint8; typedef uint16_t uint16; typedef uint32_t uint32; typedef uint64_t uint64; const uint8 kuint8max = UINT8_MAX; const uint16 kuint16max = UINT16_MAX; const uint32 kuint32max = UINT32_MAX; const uint64 kuint64max = UINT64_MAX; const int8 kint8min = INT8_MIN; const int8 kint8max = INT8_MAX; const int16 kint16min = INT16_MIN; const int16 kint16max = INT16_MAX; const int32 kint32min = INT32_MIN; const int32 kint32max = INT32_MAX; const int64 kint64min = INT64_MIN; const int64 kint64max = INT64_MAX; #else // !INT64_MAX typedef signed char int8; typedef short int16; // TODO: Remove these type guards. These are to avoid conflicts with // obsolete/protypes.h in the Gecko SDK. #ifndef _INT32 #define _INT32 typedef int int32; #endif // The NSPR system headers define 64-bit as |long| when possible. In order to // not have typedef mismatches, we do the same on LP64. #if __LP64__ typedef long int64; #else typedef long long int64; #endif // NOTE: unsigned types are DANGEROUS in loops and other arithmetical // places. Use the signed types unless your variable represents a bit // pattern (eg a hash value) or you really need the extra bit. Do NOT // use 'unsigned' to express "this value should always be positive"; // use assertions for this. typedef unsigned char uint8; typedef unsigned short uint16; // TODO: Remove these type guards. These are to avoid conflicts with // obsolete/protypes.h in the Gecko SDK. #ifndef _UINT32 #define _UINT32 typedef unsigned int uint32; #endif // See the comment above about NSPR and 64-bit. #if __LP64__ typedef unsigned long uint64; #else typedef unsigned long long uint64; #endif #endif // !INT64_MAX typedef signed char schar; // A type to represent a Unicode code-point value. As of Unicode 4.0, // such values require up to 21 bits. // (For type-checking on pointers, make this explicitly signed, // and it should always be the signed version of whatever int32 is.) typedef signed int char32; // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for a class #if !defined(DISALLOW_COPY_AND_ASSIGN) #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) #endif // An older, deprecated, politically incorrect name for the above. // NOTE: The usage of this macro was baned from our code base, but some // third_party libraries are yet using it. // TODO(tfarina): Figure out how to fix the usage of this macro in the // third_party libraries and get rid of it. #if !defined(DISALLOW_EVIL_CONSTRUCTORS) #define DISALLOW_EVIL_CONSTRUCTORS(TypeName) DISALLOW_COPY_AND_ASSIGN(TypeName) #endif // A macro to disallow all the implicit constructors, namely the // default constructor, copy constructor and operator= functions. // // This should be used in the private: declarations for a class // that wants to prevent anyone from instantiating it. This is // especially useful for classes containing only static methods. #if !defined(DISALLOW_IMPLICIT_CONSTRUCTORS) #define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ TypeName(); \ DISALLOW_COPY_AND_ASSIGN(TypeName) #endif // The arraysize(arr) macro returns the # of elements in an array arr. // The expression is a compile-time constant, and therefore can be // used in defining new arrays, for example. If you use arraysize on // a pointer by mistake, you will get a compile-time error. // // One caveat is that arraysize() doesn't accept any array of an // anonymous type or a type defined inside a function. In these rare // cases, you have to use the unsafe ARRAYSIZE_UNSAFE() macro below. This is // due to a limitation in C++'s template system. The limitation might // eventually be removed, but it hasn't happened yet. // This template function declaration is used in defining arraysize. // Note that the function doesn't need an implementation, as we only // use its type. template <typename T, size_t N> char (&ArraySizeHelper(T (&array)[N]))[N]; // That gcc wants both of these prototypes seems mysterious. VC, for // its part, can't decide which to use (another mystery). Matching of // template overloads: the final frontier. #ifndef _MSC_VER template <typename T, size_t N> char (&ArraySizeHelper(const T (&array)[N]))[N]; #endif #if !defined(arraysize) #define arraysize(array) (sizeof(ArraySizeHelper(array))) #endif // ARRAYSIZE_UNSAFE performs essentially the same calculation as arraysize, // but can be used on anonymous types or types defined inside // functions. It's less safe than arraysize as it accepts some // (although not all) pointers. Therefore, you should use arraysize // whenever possible. // // The expression ARRAYSIZE_UNSAFE(a) is a compile-time constant of type // size_t. // // ARRAYSIZE_UNSAFE catches a few type errors. If you see a compiler error // // "warning: division by zero in ..." // // when using ARRAYSIZE_UNSAFE, you are (wrongfully) giving it a pointer. // You should only use ARRAYSIZE_UNSAFE on statically allocated arrays. // // The following comments are on the implementation details, and can // be ignored by the users. // // ARRAYSIZE_UNSAFE(arr) works by inspecting sizeof(arr) (the # of bytes in // the array) and sizeof(*(arr)) (the # of bytes in one array // element). If the former is divisible by the latter, perhaps arr is // indeed an array, in which case the division result is the # of // elements in the array. Otherwise, arr cannot possibly be an array, // and we generate a compiler error to prevent the code from // compiling. // // Since the size of bool is implementation-defined, we need to cast // !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final // result has type size_t. // // This macro is not perfect as it wrongfully accepts certain // pointers, namely where the pointer size is divisible by the pointee // size. Since all our code has to go through a 32-bit compiler, // where a pointer is 4 bytes, this means all pointers to a type whose // size is 3 or greater than 4 will be (righteously) rejected. #if !defined(ARRAYSIZE_UNSAFE) #define ARRAYSIZE_UNSAFE(a) \ ((sizeof(a) / sizeof(*(a))) / \ static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) #endif // Use implicit_cast as a safe version of static_cast or const_cast // for upcasting in the type hierarchy (i.e. casting a pointer to Foo // to a pointer to SuperclassOfFoo or casting a pointer to Foo to // a const pointer to Foo). // When you use implicit_cast, the compiler checks that the cast is safe. // Such explicit implicit_casts are necessary in surprisingly many // situations where C++ demands an exact type match instead of an // argument type convertable to a target type. // // The From type can be inferred, so the preferred syntax for using // implicit_cast is the same as for static_cast etc.: // // implicit_cast<ToType>(expr) // // implicit_cast would have been part of the C++ standard library, // but the proposal was submitted too late. It will probably make // its way into the language in the future. template<typename To, typename From> inline To implicit_cast(From const &f) { return f; } // The COMPILE_ASSERT macro can be used to verify that a compile time // expression is true. For example, you could use it to verify the // size of a static array: // // COMPILE_ASSERT(ARRAYSIZE_UNSAFE(content_type_names) == CONTENT_NUM_TYPES, // content_type_names_incorrect_size); // // or to make sure a struct is smaller than a certain size: // // COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large); // // The second argument to the macro is the name of the variable. If // the expression is false, most compilers will issue a warning/error // containing the name of the variable. #if __cplusplus >= 201103L // Under C++11, just use static_assert. #define COMPILE_ASSERT(expr, msg) static_assert(expr, #msg) #else template <bool> struct CompileAssert { }; // Annotate a variable indicating it's ok if the variable is not used. // (Typically used to silence a compiler warning when the assignment // is important for some other reason.) // Use like: // int x ALLOW_UNUSED = ...; #if defined(__GNUC__) #define ALLOW_UNUSED __attribute__((unused)) #else #define ALLOW_UNUSED #endif #define COMPILE_ASSERT(expr, msg) \ typedef CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1] ALLOW_UNUSED // Implementation details of COMPILE_ASSERT: // // - COMPILE_ASSERT works by defining an array type that has -1 // elements (and thus is invalid) when the expression is false. // // - The simpler definition // // #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1] // // does not work, as gcc supports variable-length arrays whose sizes // are determined at run-time (this is gcc's extension and not part // of the C++ standard). As a result, gcc fails to reject the // following code with the simple definition: // // int foo; // COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is // // not a compile-time constant. // // - By using the type CompileAssert<(bool(expr))>, we ensures that // expr is a compile-time constant. (Template arguments must be // determined at compile-time.) // // - The outer parentheses in CompileAssert<(bool(expr))> are necessary // to work around a bug in gcc 3.4.4 and 4.0.1. If we had written // // CompileAssert<bool(expr)> // // instead, these compilers will refuse to compile // // COMPILE_ASSERT(5 > 0, some_message); // // (They seem to think the ">" in "5 > 0" marks the end of the // template argument list.) // // - The array size is (bool(expr) ? 1 : -1), instead of simply // // ((expr) ? 1 : -1). // // This is to avoid running into a bug in MS VC 7.1, which // causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. #endif // Used to explicitly mark the return value of a function as unused. If you are // really sure you don't want to do anything with the return value of a function // that has been marked WARN_UNUSED_RESULT, wrap it with this. Example: // // scoped_ptr<MyType> my_var = ...; // if (TakeOwnership(my_var.get()) == SUCCESS) // ignore_result(my_var.release()); // template<typename T> inline void ignore_result(const T&) { } // The following enum should be used only as a constructor argument to indicate // that the variable has static storage class, and that the constructor should // do nothing to its state. It indicates to the reader that it is legal to // declare a static instance of the class, provided the constructor is given // the base::LINKER_INITIALIZED argument. Normally, it is unsafe to declare a // static variable that has a constructor or a destructor because invocation // order is undefined. However, IF the type can be initialized by filling with // zeroes (which the loader does for static variables), AND the destructor also // does nothing to the storage, AND there are no virtual methods, then a // constructor declared as // explicit MyClass(base::LinkerInitialized x) {} // and invoked as // static MyClass my_variable_name(base::LINKER_INITIALIZED); namespace base { enum LinkerInitialized { LINKER_INITIALIZED }; } // base #endif // BASE_BASICTYPES_H_
2301_81045437/third_party_libphonenumber
tools/cpp/src/base/basictypes.h
C++
unknown
12,140
/* * Copyright (C) 2009 The Libphonenumber 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. */ package com.google.i18n.phonenumbers; import com.google.i18n.phonenumbers.Phonemetadata.NumberFormat; import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata; import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadataCollection; import com.google.i18n.phonenumbers.Phonemetadata.PhoneNumberDesc; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * Library to build phone number metadata from the XML format. * * @author Shaopeng Jia */ public class BuildMetadataFromXml { private static final Logger logger = Logger.getLogger(BuildMetadataFromXml.class.getName()); // String constants used to fetch the XML nodes and attributes. private static final String CARRIER_CODE_FORMATTING_RULE = "carrierCodeFormattingRule"; private static final String CARRIER_SPECIFIC = "carrierSpecific"; private static final String COUNTRY_CODE = "countryCode"; private static final String EMERGENCY = "emergency"; private static final String EXAMPLE_NUMBER = "exampleNumber"; private static final String FIXED_LINE = "fixedLine"; private static final String FORMAT = "format"; private static final String GENERAL_DESC = "generalDesc"; private static final String INTERNATIONAL_PREFIX = "internationalPrefix"; private static final String INTL_FORMAT = "intlFormat"; private static final String LEADING_DIGITS = "leadingDigits"; private static final String MAIN_COUNTRY_FOR_CODE = "mainCountryForCode"; private static final String MOBILE = "mobile"; private static final String MOBILE_NUMBER_PORTABLE_REGION = "mobileNumberPortableRegion"; private static final String NATIONAL_NUMBER_PATTERN = "nationalNumberPattern"; private static final String NATIONAL_PREFIX = "nationalPrefix"; private static final String NATIONAL_PREFIX_FORMATTING_RULE = "nationalPrefixFormattingRule"; private static final String NATIONAL_PREFIX_OPTIONAL_WHEN_FORMATTING = "nationalPrefixOptionalWhenFormatting"; private static final String NATIONAL_PREFIX_FOR_PARSING = "nationalPrefixForParsing"; private static final String NATIONAL_PREFIX_TRANSFORM_RULE = "nationalPrefixTransformRule"; private static final String NO_INTERNATIONAL_DIALLING = "noInternationalDialling"; private static final String NUMBER_FORMAT = "numberFormat"; private static final String PAGER = "pager"; private static final String PATTERN = "pattern"; private static final String PERSONAL_NUMBER = "personalNumber"; private static final String POSSIBLE_LENGTHS = "possibleLengths"; private static final String NATIONAL = "national"; private static final String LOCAL_ONLY = "localOnly"; private static final String PREFERRED_EXTN_PREFIX = "preferredExtnPrefix"; private static final String PREFERRED_INTERNATIONAL_PREFIX = "preferredInternationalPrefix"; private static final String PREMIUM_RATE = "premiumRate"; private static final String SHARED_COST = "sharedCost"; private static final String SHORT_CODE = "shortCode"; private static final String SMS_SERVICES = "smsServices"; private static final String STANDARD_RATE = "standardRate"; private static final String TOLL_FREE = "tollFree"; private static final String UAN = "uan"; private static final String VOICEMAIL = "voicemail"; private static final String VOIP = "voip"; private static final Set<String> PHONE_NUMBER_DESCS_WITHOUT_MATCHING_TYPES = new HashSet<String>(Arrays.asList(new String[]{NO_INTERNATIONAL_DIALLING})); // Build the PhoneMetadataCollection from the input XML file. public static PhoneMetadataCollection buildPhoneMetadataCollection(String inputXmlFile, boolean liteBuild, boolean specialBuild) throws Exception { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); File xmlFile = new File(inputXmlFile); Document document = builder.parse(xmlFile); // TODO: Look for other uses of these constants and possibly pull them out into a separate // constants file. boolean isShortNumberMetadata = inputXmlFile.contains("ShortNumberMetadata"); boolean isAlternateFormatsMetadata = inputXmlFile.contains("PhoneNumberAlternateFormats"); return buildPhoneMetadataCollection(document, liteBuild, specialBuild, isShortNumberMetadata, isAlternateFormatsMetadata); } // @VisibleForTesting static PhoneMetadataCollection buildPhoneMetadataCollection(Document document, boolean liteBuild, boolean specialBuild, boolean isShortNumberMetadata, boolean isAlternateFormatsMetadata) throws Exception { document.getDocumentElement().normalize(); Element rootElement = document.getDocumentElement(); NodeList territory = rootElement.getElementsByTagName("territory"); PhoneMetadataCollection.Builder metadataCollection = PhoneMetadataCollection.newBuilder(); int numOfTerritories = territory.getLength(); // TODO: Infer filter from a single flag. MetadataFilter metadataFilter = getMetadataFilter(liteBuild, specialBuild); for (int i = 0; i < numOfTerritories; i++) { Element territoryElement = (Element) territory.item(i); String regionCode = ""; // For the main metadata file this should always be set, but for other supplementary data // files the country calling code may be all that is needed. if (territoryElement.hasAttribute("id")) { regionCode = territoryElement.getAttribute("id"); } PhoneMetadata.Builder metadata = loadCountryMetadata(regionCode, territoryElement, isShortNumberMetadata, isAlternateFormatsMetadata); metadataFilter.filterMetadata(metadata); metadataCollection.addMetadata(metadata); } return metadataCollection.build(); } // Build a mapping from a country calling code to the region codes which denote the country/region // represented by that country code. In the case of multiple countries sharing a calling code, // such as the NANPA countries, the one indicated with "isMainCountryForCode" in the metadata // should be first. public static Map<Integer, List<String>> buildCountryCodeToRegionCodeMap( PhoneMetadataCollection metadataCollection) { Map<Integer, List<String>> countryCodeToRegionCodeMap = new TreeMap<Integer, List<String>>(); for (PhoneMetadata metadata : metadataCollection.getMetadataList()) { String regionCode = metadata.getId(); int countryCode = metadata.getCountryCode(); if (countryCodeToRegionCodeMap.containsKey(countryCode)) { if (metadata.getMainCountryForCode()) { countryCodeToRegionCodeMap.get(countryCode).add(0, regionCode); } else { countryCodeToRegionCodeMap.get(countryCode).add(regionCode); } } else { // For most countries, there will be only one region code for the country calling code. List<String> listWithRegionCode = new ArrayList<String>(1); if (!regionCode.equals("")) { // For alternate formats, there are no region codes at all. listWithRegionCode.add(regionCode); } countryCodeToRegionCodeMap.put(countryCode, listWithRegionCode); } } return countryCodeToRegionCodeMap; } private static String validateRE(String regex) { return validateRE(regex, false); } // @VisibleForTesting static String validateRE(String regex, boolean removeWhitespace) { // Removes all the whitespace and newline from the regexp. Not using pattern compile options to // make it work across programming languages. String compressedRegex = removeWhitespace ? regex.replaceAll("\\s", "") : regex; Pattern.compile(compressedRegex); // We don't ever expect to see | followed by a ) in our metadata - this would be an indication // of a bug. If one wants to make something optional, we prefer ? to using an empty group. int errorIndex = compressedRegex.indexOf("|)"); if (errorIndex >= 0) { logger.log(Level.SEVERE, "Error with original regex: " + regex + "\n| should not be followed directly by ) in phone number regular expressions."); throw new PatternSyntaxException("| followed by )", compressedRegex, errorIndex); } // return the regex if it is of correct syntax, i.e. compile did not fail with a // PatternSyntaxException. return compressedRegex; } /** * Returns the national prefix of the provided country element. */ // @VisibleForTesting static String getNationalPrefix(Element element) { return element.hasAttribute(NATIONAL_PREFIX) ? element.getAttribute(NATIONAL_PREFIX) : ""; } // @VisibleForTesting static PhoneMetadata.Builder loadTerritoryTagMetadata(String regionCode, Element element, String nationalPrefix) { PhoneMetadata.Builder metadata = PhoneMetadata.newBuilder(); metadata.setId(regionCode); if (element.hasAttribute(COUNTRY_CODE)) { metadata.setCountryCode(Integer.parseInt(element.getAttribute(COUNTRY_CODE))); } if (element.hasAttribute(LEADING_DIGITS)) { metadata.setLeadingDigits(validateRE(element.getAttribute(LEADING_DIGITS))); } if (element.hasAttribute(INTERNATIONAL_PREFIX)) { metadata.setInternationalPrefix(validateRE(element.getAttribute(INTERNATIONAL_PREFIX))); } if (element.hasAttribute(PREFERRED_INTERNATIONAL_PREFIX)) { metadata.setPreferredInternationalPrefix( element.getAttribute(PREFERRED_INTERNATIONAL_PREFIX)); } if (element.hasAttribute(NATIONAL_PREFIX_FOR_PARSING)) { metadata.setNationalPrefixForParsing( validateRE(element.getAttribute(NATIONAL_PREFIX_FOR_PARSING), true)); if (element.hasAttribute(NATIONAL_PREFIX_TRANSFORM_RULE)) { metadata.setNationalPrefixTransformRule( validateRE(element.getAttribute(NATIONAL_PREFIX_TRANSFORM_RULE))); } } if (!nationalPrefix.isEmpty()) { metadata.setNationalPrefix(nationalPrefix); if (!metadata.hasNationalPrefixForParsing()) { metadata.setNationalPrefixForParsing(nationalPrefix); } } if (element.hasAttribute(PREFERRED_EXTN_PREFIX)) { metadata.setPreferredExtnPrefix(element.getAttribute(PREFERRED_EXTN_PREFIX)); } if (element.hasAttribute(MAIN_COUNTRY_FOR_CODE)) { metadata.setMainCountryForCode(true); } if (element.hasAttribute(MOBILE_NUMBER_PORTABLE_REGION)) { metadata.setMobileNumberPortableRegion(true); } return metadata; } /** * Extracts the pattern for international format. If there is no intlFormat, default to using the * national format. If the intlFormat is set to "NA" the intlFormat should be ignored. * * @throws RuntimeException if multiple intlFormats have been encountered. * @return whether an international number format is defined. */ // @VisibleForTesting static boolean loadInternationalFormat(PhoneMetadata.Builder metadata, Element numberFormatElement, NumberFormat nationalFormat) { NumberFormat.Builder intlFormat = NumberFormat.newBuilder(); NodeList intlFormatPattern = numberFormatElement.getElementsByTagName(INTL_FORMAT); boolean hasExplicitIntlFormatDefined = false; if (intlFormatPattern.getLength() > 1) { logger.log(Level.SEVERE, "A maximum of one intlFormat pattern for a numberFormat element should be defined."); String countryId = metadata.getId().length() > 0 ? metadata.getId() : Integer.toString(metadata.getCountryCode()); throw new RuntimeException("Invalid number of intlFormat patterns for country: " + countryId); } else if (intlFormatPattern.getLength() == 0) { // Default to use the same as the national pattern if none is defined. intlFormat.mergeFrom(nationalFormat); } else { intlFormat.setPattern(numberFormatElement.getAttribute(PATTERN)); setLeadingDigitsPatterns(numberFormatElement, intlFormat); String intlFormatPatternValue = intlFormatPattern.item(0).getFirstChild().getNodeValue(); if (!intlFormatPatternValue.equals("NA")) { intlFormat.setFormat(intlFormatPatternValue); } hasExplicitIntlFormatDefined = true; } if (intlFormat.hasFormat()) { metadata.addIntlNumberFormat(intlFormat); } return hasExplicitIntlFormatDefined; } /** * Extracts the pattern for the national format. * * @throws RuntimeException if multiple or no formats have been encountered. */ // @VisibleForTesting static void loadNationalFormat(PhoneMetadata.Builder metadata, Element numberFormatElement, NumberFormat.Builder format) { setLeadingDigitsPatterns(numberFormatElement, format); format.setPattern(validateRE(numberFormatElement.getAttribute(PATTERN))); NodeList formatPattern = numberFormatElement.getElementsByTagName(FORMAT); int numFormatPatterns = formatPattern.getLength(); if (numFormatPatterns != 1) { logger.log(Level.SEVERE, "One format pattern for a numberFormat element should be defined."); String countryId = metadata.getId().length() > 0 ? metadata.getId() : Integer.toString(metadata.getCountryCode()); throw new RuntimeException("Invalid number of format patterns (" + numFormatPatterns + ") for country: " + countryId); } format.setFormat(formatPattern.item(0).getFirstChild().getNodeValue()); } /** * Extracts the available formats from the provided DOM element. If it does not contain any * nationalPrefixFormattingRule, the one passed-in is retained; similarly for * nationalPrefixOptionalWhenFormatting. The nationalPrefix, nationalPrefixFormattingRule and * nationalPrefixOptionalWhenFormatting values are provided from the parent (territory) element. */ // @VisibleForTesting static void loadAvailableFormats(PhoneMetadata.Builder metadata, Element element, String nationalPrefix, String nationalPrefixFormattingRule, boolean nationalPrefixOptionalWhenFormatting) { String carrierCodeFormattingRule = ""; if (element.hasAttribute(CARRIER_CODE_FORMATTING_RULE)) { carrierCodeFormattingRule = validateRE( getDomesticCarrierCodeFormattingRuleFromElement(element, nationalPrefix)); } NodeList numberFormatElements = element.getElementsByTagName(NUMBER_FORMAT); boolean hasExplicitIntlFormatDefined = false; int numOfFormatElements = numberFormatElements.getLength(); if (numOfFormatElements > 0) { for (int i = 0; i < numOfFormatElements; i++) { Element numberFormatElement = (Element) numberFormatElements.item(i); NumberFormat.Builder format = NumberFormat.newBuilder(); if (numberFormatElement.hasAttribute(NATIONAL_PREFIX_FORMATTING_RULE)) { format.setNationalPrefixFormattingRule( getNationalPrefixFormattingRuleFromElement(numberFormatElement, nationalPrefix)); } else if (!nationalPrefixFormattingRule.equals("")) { format.setNationalPrefixFormattingRule(nationalPrefixFormattingRule); } if (numberFormatElement.hasAttribute(NATIONAL_PREFIX_OPTIONAL_WHEN_FORMATTING)) { format.setNationalPrefixOptionalWhenFormatting( Boolean.valueOf(numberFormatElement.getAttribute( NATIONAL_PREFIX_OPTIONAL_WHEN_FORMATTING))); } else if (format.getNationalPrefixOptionalWhenFormatting() != nationalPrefixOptionalWhenFormatting) { // Inherit from the parent field if it is not already the same as the default. format.setNationalPrefixOptionalWhenFormatting(nationalPrefixOptionalWhenFormatting); } if (numberFormatElement.hasAttribute(CARRIER_CODE_FORMATTING_RULE)) { format.setDomesticCarrierCodeFormattingRule(validateRE( getDomesticCarrierCodeFormattingRuleFromElement(numberFormatElement, nationalPrefix))); } else if (!carrierCodeFormattingRule.equals("")) { format.setDomesticCarrierCodeFormattingRule(carrierCodeFormattingRule); } loadNationalFormat(metadata, numberFormatElement, format); metadata.addNumberFormat(format); if (loadInternationalFormat(metadata, numberFormatElement, format.build())) { hasExplicitIntlFormatDefined = true; } } // Only a small number of regions need to specify the intlFormats in the xml. For the majority // of countries the intlNumberFormat metadata is an exact copy of the national NumberFormat // metadata. To minimize the size of the metadata file, we only keep intlNumberFormats that // actually differ in some way to the national formats. if (!hasExplicitIntlFormatDefined) { metadata.clearIntlNumberFormat(); } } } // @VisibleForTesting static void setLeadingDigitsPatterns(Element numberFormatElement, NumberFormat.Builder format) { NodeList leadingDigitsPatternNodes = numberFormatElement.getElementsByTagName(LEADING_DIGITS); int numOfLeadingDigitsPatterns = leadingDigitsPatternNodes.getLength(); if (numOfLeadingDigitsPatterns > 0) { for (int i = 0; i < numOfLeadingDigitsPatterns; i++) { format.addLeadingDigitsPattern( validateRE((leadingDigitsPatternNodes.item(i)).getFirstChild().getNodeValue(), true)); } } } // @VisibleForTesting static String getNationalPrefixFormattingRuleFromElement(Element element, String nationalPrefix) { String nationalPrefixFormattingRule = element.getAttribute(NATIONAL_PREFIX_FORMATTING_RULE); // Replace $NP with national prefix and $FG with the first group ($1). nationalPrefixFormattingRule = nationalPrefixFormattingRule.replaceFirst("\\$NP", nationalPrefix) .replaceFirst("\\$FG", "\\$1"); return nationalPrefixFormattingRule; } // @VisibleForTesting static String getDomesticCarrierCodeFormattingRuleFromElement(Element element, String nationalPrefix) { String carrierCodeFormattingRule = element.getAttribute(CARRIER_CODE_FORMATTING_RULE); // Replace $FG with the first group ($1) and $NP with the national prefix. carrierCodeFormattingRule = carrierCodeFormattingRule.replaceFirst("\\$FG", "\\$1") .replaceFirst("\\$NP", nationalPrefix); return carrierCodeFormattingRule; } /** * Checks if the possible lengths provided as a sorted set are equal to the possible lengths * stored already in the description pattern. Note that possibleLengths may be empty but must not * be null, and the PhoneNumberDesc passed in should also not be null. */ private static boolean arePossibleLengthsEqual(TreeSet<Integer> possibleLengths, PhoneNumberDesc desc) { if (possibleLengths.size() != desc.getPossibleLengthCount()) { return false; } // Note that both should be sorted already, and we know they are the same length. int i = 0; for (Integer length : possibleLengths) { if (length != desc.getPossibleLength(i)) { return false; } i++; } return true; } /** * Processes a phone number description element from the XML file and returns it as a * PhoneNumberDesc. If the description element is a fixed line or mobile number, the parent * description will be used to fill in the whole element if necessary, or any components that are * missing. For all other types, the parent description will only be used to fill in missing * components if the type has a partial definition. For example, if no "tollFree" element exists, * we assume there are no toll free numbers for that locale, and return a phone number description * with no national number data and [-1] for the possible lengths. Note that the parent * description must therefore already be processed before this method is called on any child * elements. * * @param parentDesc a generic phone number description that will be used to fill in missing * parts of the description, or null if this is the root node. This must be processed before * this is run on any child elements. * @param countryElement the XML element representing all the country information * @param numberType the name of the number type, corresponding to the appropriate tag in the XML * file with information about that type * @return complete description of that phone number type */ // @VisibleForTesting static PhoneNumberDesc.Builder processPhoneNumberDescElement(PhoneNumberDesc parentDesc, Element countryElement, String numberType) { NodeList phoneNumberDescList = countryElement.getElementsByTagName(numberType); PhoneNumberDesc.Builder numberDesc = PhoneNumberDesc.newBuilder(); if (phoneNumberDescList.getLength() == 0) { // -1 will never match a possible phone number length, so is safe to use to ensure this never // matches. We don't leave it empty, since for compression reasons, we use the empty list to // mean that the generalDesc possible lengths apply. numberDesc.addPossibleLength(-1); return numberDesc; } if (phoneNumberDescList.getLength() > 0) { if (phoneNumberDescList.getLength() > 1) { throw new RuntimeException( String.format("Multiple elements with type %s found.", numberType)); } Element element = (Element) phoneNumberDescList.item(0); if (parentDesc != null) { // New way of handling possible number lengths. We don't do this for the general // description, since these tags won't be present; instead we will calculate its values // based on the values for all the other number type descriptions (see // setPossibleLengthsGeneralDesc). TreeSet<Integer> lengths = new TreeSet<Integer>(); TreeSet<Integer> localOnlyLengths = new TreeSet<Integer>(); populatePossibleLengthSets(element, lengths, localOnlyLengths); setPossibleLengths(lengths, localOnlyLengths, parentDesc, numberDesc); } NodeList validPattern = element.getElementsByTagName(NATIONAL_NUMBER_PATTERN); if (validPattern.getLength() > 0) { numberDesc.setNationalNumberPattern( validateRE(validPattern.item(0).getFirstChild().getNodeValue(), true)); } NodeList exampleNumber = element.getElementsByTagName(EXAMPLE_NUMBER); if (exampleNumber.getLength() > 0) { numberDesc.setExampleNumber(exampleNumber.item(0).getFirstChild().getNodeValue()); } } return numberDesc; } // @VisibleForTesting static void setRelevantDescPatterns(PhoneMetadata.Builder metadata, Element element, boolean isShortNumberMetadata) { PhoneNumberDesc.Builder generalDescBuilder = processPhoneNumberDescElement(null, element, GENERAL_DESC); // Calculate the possible lengths for the general description. This will be based on the // possible lengths of the child elements. setPossibleLengthsGeneralDesc( generalDescBuilder, metadata.getId(), element, isShortNumberMetadata); metadata.setGeneralDesc(generalDescBuilder); PhoneNumberDesc generalDesc = metadata.getGeneralDesc(); if (!isShortNumberMetadata) { // Set fields used by regular length phone numbers. metadata.setFixedLine(processPhoneNumberDescElement(generalDesc, element, FIXED_LINE)); metadata.setMobile(processPhoneNumberDescElement(generalDesc, element, MOBILE)); metadata.setSharedCost(processPhoneNumberDescElement(generalDesc, element, SHARED_COST)); metadata.setVoip(processPhoneNumberDescElement(generalDesc, element, VOIP)); metadata.setPersonalNumber(processPhoneNumberDescElement(generalDesc, element, PERSONAL_NUMBER)); metadata.setPager(processPhoneNumberDescElement(generalDesc, element, PAGER)); metadata.setUan(processPhoneNumberDescElement(generalDesc, element, UAN)); metadata.setVoicemail(processPhoneNumberDescElement(generalDesc, element, VOICEMAIL)); metadata.setNoInternationalDialling(processPhoneNumberDescElement(generalDesc, element, NO_INTERNATIONAL_DIALLING)); boolean mobileAndFixedAreSame = metadata.getMobile().getNationalNumberPattern() .equals(metadata.getFixedLine().getNationalNumberPattern()); if (metadata.getSameMobileAndFixedLinePattern() != mobileAndFixedAreSame) { // Set this if it is not the same as the default. metadata.setSameMobileAndFixedLinePattern(mobileAndFixedAreSame); } metadata.setTollFree(processPhoneNumberDescElement(generalDesc, element, TOLL_FREE)); metadata.setPremiumRate(processPhoneNumberDescElement(generalDesc, element, PREMIUM_RATE)); } else { // Set fields used by short numbers. metadata.setStandardRate(processPhoneNumberDescElement(generalDesc, element, STANDARD_RATE)); metadata.setShortCode(processPhoneNumberDescElement(generalDesc, element, SHORT_CODE)); metadata.setCarrierSpecific(processPhoneNumberDescElement(generalDesc, element, CARRIER_SPECIFIC)); metadata.setEmergency(processPhoneNumberDescElement(generalDesc, element, EMERGENCY)); metadata.setTollFree(processPhoneNumberDescElement(generalDesc, element, TOLL_FREE)); metadata.setPremiumRate(processPhoneNumberDescElement(generalDesc, element, PREMIUM_RATE)); metadata.setSmsServices(processPhoneNumberDescElement(generalDesc, element, SMS_SERVICES)); } } /** * Parses a possible length string into a set of the integers that are covered. * * @param possibleLengthString a string specifying the possible lengths of phone numbers. Follows * this syntax: ranges or elements are separated by commas, and ranges are specified in * [min-max] notation, inclusive. For example, [3-5],7,9,[11-14] should be parsed to * 3,4,5,7,9,11,12,13,14. */ private static Set<Integer> parsePossibleLengthStringToSet(String possibleLengthString) { if (possibleLengthString.length() == 0) { throw new RuntimeException("Empty possibleLength string found."); } String[] lengths = possibleLengthString.split(","); Set<Integer> lengthSet = new TreeSet<Integer>(); for (int i = 0; i < lengths.length; i++) { String lengthSubstring = lengths[i]; if (lengthSubstring.length() == 0) { throw new RuntimeException(String.format("Leading, trailing or adjacent commas in possible " + "length string %s, these should only separate numbers or ranges.", possibleLengthString)); } else if (lengthSubstring.charAt(0) == '[') { if (lengthSubstring.charAt(lengthSubstring.length() - 1) != ']') { throw new RuntimeException(String.format("Missing end of range character in possible " + "length string %s.", possibleLengthString)); } // Strip the leading and trailing [], and split on the -. String[] minMax = lengthSubstring.substring(1, lengthSubstring.length() - 1).split("-"); if (minMax.length != 2) { throw new RuntimeException(String.format("Ranges must have exactly one - character: " + "missing for %s.", possibleLengthString)); } int min = Integer.parseInt(minMax[0]); int max = Integer.parseInt(minMax[1]); // We don't even accept [6-7] since we prefer the shorter 6,7 variant; for a range to be in // use the hyphen needs to replace at least one digit. if (max - min < 2) { throw new RuntimeException(String.format("The first number in a range should be two or " + "more digits lower than the second. Culprit possibleLength string: %s", possibleLengthString)); } for (int j = min; j <= max; j++) { if (!lengthSet.add(j)) { throw new RuntimeException(String.format("Duplicate length element found (%d) in " + "possibleLength string %s", j, possibleLengthString)); } } } else { int length = Integer.parseInt(lengthSubstring); if (!lengthSet.add(length)) { throw new RuntimeException(String.format("Duplicate length element found (%d) in " + "possibleLength string %s", length, possibleLengthString)); } } } return lengthSet; } /** * Reads the possible lengths present in the metadata and splits them into two sets: one for * full-length numbers, one for local numbers. * * @param data one or more phone number descriptions, represented as XML nodes * @param lengths a set to which to add possible lengths of full phone numbers * @param localOnlyLengths a set to which to add possible lengths of phone numbers only diallable * locally (e.g. within a province) */ private static void populatePossibleLengthSets(Element data, TreeSet<Integer> lengths, TreeSet<Integer> localOnlyLengths) { NodeList possibleLengths = data.getElementsByTagName(POSSIBLE_LENGTHS); for (int i = 0; i < possibleLengths.getLength(); i++) { Element element = (Element) possibleLengths.item(i); String nationalLengths = element.getAttribute(NATIONAL); // We don't add to the phone metadata yet, since we want to sort length elements found under // different nodes first, make sure there are no duplicates between them and that the // localOnly lengths don't overlap with the others. Set<Integer> thisElementLengths = parsePossibleLengthStringToSet(nationalLengths); if (element.hasAttribute(LOCAL_ONLY)) { String localLengths = element.getAttribute(LOCAL_ONLY); Set<Integer> thisElementLocalOnlyLengths = parsePossibleLengthStringToSet(localLengths); Set<Integer> intersection = new HashSet<Integer>(thisElementLengths); intersection.retainAll(thisElementLocalOnlyLengths); if (!intersection.isEmpty()) { throw new RuntimeException(String.format( "Possible length(s) found specified as a normal and local-only length: %s", intersection)); } // We check again when we set these lengths on the metadata itself in setPossibleLengths // that the elements in localOnly are not also in lengths. For e.g. the generalDesc, it // might have a local-only length for one type that is a normal length for another type. We // don't consider this an error, but we do want to remove the local-only lengths. localOnlyLengths.addAll(thisElementLocalOnlyLengths); } // It is okay if at this time we have duplicates, because the same length might be possible // for e.g. fixed-line and for mobile numbers, and this method operates potentially on // multiple phoneNumberDesc XML elements. lengths.addAll(thisElementLengths); } } /** * Sets possible lengths in the general description, derived from certain child elements. */ // @VisibleForTesting static void setPossibleLengthsGeneralDesc(PhoneNumberDesc.Builder generalDesc, String metadataId, Element data, boolean isShortNumberMetadata) { TreeSet<Integer> lengths = new TreeSet<Integer>(); TreeSet<Integer> localOnlyLengths = new TreeSet<Integer>(); // The general description node should *always* be present if metadata for other types is // present, aside from in some unit tests. // (However, for e.g. formatting metadata in PhoneNumberAlternateFormats, no PhoneNumberDesc // elements are present). NodeList generalDescNodes = data.getElementsByTagName(GENERAL_DESC); if (generalDescNodes.getLength() > 0) { Element generalDescNode = (Element) generalDescNodes.item(0); populatePossibleLengthSets(generalDescNode, lengths, localOnlyLengths); if (!lengths.isEmpty() || !localOnlyLengths.isEmpty()) { // We shouldn't have anything specified at the "general desc" level: we are going to // calculate this ourselves from child elements. throw new RuntimeException(String.format("Found possible lengths specified at general " + "desc: this should be derived from child elements. Affected country: %s", metadataId)); } } if (!isShortNumberMetadata) { // Make a copy here since we want to remove some nodes, but we don't want to do that on our // actual data. Element allDescData = (Element) data.cloneNode(true /* deep copy */); for (String tag : PHONE_NUMBER_DESCS_WITHOUT_MATCHING_TYPES) { NodeList nodesToRemove = allDescData.getElementsByTagName(tag); if (nodesToRemove.getLength() > 0) { // We check when we process phone number descriptions that there are only one of each // type, so this is safe to do. allDescData.removeChild(nodesToRemove.item(0)); } } populatePossibleLengthSets(allDescData, lengths, localOnlyLengths); } else { // For short number metadata, we want to copy the lengths from the "short code" section only. // This is because it's the more detailed validation pattern, it's not a sub-type of short // codes. The other lengths will be checked later to see that they are a sub-set of these // possible lengths. NodeList shortCodeDescList = data.getElementsByTagName(SHORT_CODE); if (shortCodeDescList.getLength() > 0) { Element shortCodeDesc = (Element) shortCodeDescList.item(0); populatePossibleLengthSets(shortCodeDesc, lengths, localOnlyLengths); } if (localOnlyLengths.size() > 0) { throw new RuntimeException("Found local-only lengths in short-number metadata"); } } setPossibleLengths(lengths, localOnlyLengths, null, generalDesc); } /** * Sets the possible length fields in the metadata from the sets of data passed in. Checks that * the length is covered by the "parent" phone number description element if one is present, and * if the lengths are exactly the same as this, they are not filled in for efficiency reasons. * * @param parentDesc the "general description" element or null if desc is the generalDesc itself * @param desc the PhoneNumberDesc object that we are going to set lengths for */ private static void setPossibleLengths(TreeSet<Integer> lengths, TreeSet<Integer> localOnlyLengths, PhoneNumberDesc parentDesc, PhoneNumberDesc.Builder desc) { // We clear these fields since the metadata tends to inherit from the parent element for other // fields (via a mergeFrom). desc.clearPossibleLength(); desc.clearPossibleLengthLocalOnly(); // Only add the lengths to this sub-type if they aren't exactly the same as the possible // lengths in the general desc (for metadata size reasons). if (parentDesc == null || !arePossibleLengthsEqual(lengths, parentDesc)) { for (Integer length : lengths) { if (parentDesc == null || parentDesc.getPossibleLengthList().contains(length)) { desc.addPossibleLength(length); } else { // We shouldn't have possible lengths defined in a child element that are not covered by // the general description. We check this here even though the general description is // derived from child elements because it is only derived from a subset, and we need to // ensure *all* child elements have a valid possible length. throw new RuntimeException(String.format( "Out-of-range possible length found (%d), parent lengths %s.", length, parentDesc.getPossibleLengthList())); } } } // We check that the local-only length isn't also a normal possible length (only relevant for // the general-desc, since within elements such as fixed-line we would throw an exception if we // saw this) before adding it to the collection of possible local-only lengths. for (Integer length : localOnlyLengths) { if (!lengths.contains(length)) { // We check it is covered by either of the possible length sets of the parent // PhoneNumberDesc, because for example 7 might be a valid localOnly length for mobile, but // a valid national length for fixedLine, so the generalDesc would have the 7 removed from // localOnly. if (parentDesc == null || parentDesc.getPossibleLengthLocalOnlyList().contains(length) || parentDesc.getPossibleLengthList().contains(length)) { desc.addPossibleLengthLocalOnly(length); } else { throw new RuntimeException(String.format( "Out-of-range local-only possible length found (%d), parent length %s.", length, parentDesc.getPossibleLengthLocalOnlyList())); } } } } // @VisibleForTesting static PhoneMetadata.Builder loadCountryMetadata(String regionCode, Element element, boolean isShortNumberMetadata, boolean isAlternateFormatsMetadata) { String nationalPrefix = getNationalPrefix(element); PhoneMetadata.Builder metadata = loadTerritoryTagMetadata(regionCode, element, nationalPrefix); String nationalPrefixFormattingRule = getNationalPrefixFormattingRuleFromElement(element, nationalPrefix); loadAvailableFormats(metadata, element, nationalPrefix, nationalPrefixFormattingRule, element.hasAttribute(NATIONAL_PREFIX_OPTIONAL_WHEN_FORMATTING)); if (!isAlternateFormatsMetadata) { // The alternate formats metadata does not need most of the patterns to be set. setRelevantDescPatterns(metadata, element, isShortNumberMetadata); } return metadata; } /** * Processes the custom build flags and gets a {@code MetadataFilter} which may be used to * filter {@code PhoneMetadata} objects. Incompatible flag combinations throw RuntimeException. * * @param liteBuild The liteBuild flag value as given by the command-line * @param specialBuild The specialBuild flag value as given by the command-line */ // @VisibleForTesting static MetadataFilter getMetadataFilter(boolean liteBuild, boolean specialBuild) { if (specialBuild) { if (liteBuild) { throw new RuntimeException("liteBuild and specialBuild may not both be set"); } return MetadataFilter.forSpecialBuild(); } if (liteBuild) { return MetadataFilter.forLiteBuild(); } return MetadataFilter.emptyFilter(); } }
2301_81045437/third_party_libphonenumber
tools/java/common/src/com/google/i18n/phonenumbers/BuildMetadataFromXml.java
Java
unknown
40,022
/* * Copyright (C) 2011 The Libphonenumber 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. */ package com.google.i18n.phonenumbers; /** * Abstract class defining a common interface for commands provided by build tools (e.g: commands to * generate code or to download source files). * * <p> Subclass it to create a new command (e.g: code generation step). * * @author Philippe Liard */ public abstract class Command { // The arguments provided to this command. The first one is the name of the command. private String[] args; /** * Entry point of the command called by the CommandDispatcher when requested. This method must be * implemented by subclasses. */ public abstract boolean start(); /** * The name of the command is used by the CommandDispatcher to execute the requested command. The * Dispatcher will pass along all command-line arguments to this command, so args[0] will be * always the command name. */ public abstract String getCommandName(); public String[] getArgs() { return args; } public void setArgs(String[] args) { this.args = args; } }
2301_81045437/third_party_libphonenumber
tools/java/common/src/com/google/i18n/phonenumbers/Command.java
Java
unknown
1,645
/* * Copyright (C) 2011 The Libphonenumber 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. */ package com.google.i18n.phonenumbers; /** * This class is designed to execute a requested command among a set of provided commands. * The dispatching is performed according to the requested command name, which is provided as the * first string of the 'args' array. The 'args' array also contains the command arguments available * from position 1 to end. The verification of the arguments' consistency is under the * responsibility of the command since the dispatcher can't be aware of its underlying goals. * * @see Command * @author Philippe Liard */ public class CommandDispatcher { // Command line arguments passed to the command which will be executed. Note that the first one is // the name of the command. private final String[] args; // Supported commands by this dispatcher. private final Command[] commands; public CommandDispatcher(String[] args, Command[] commands) { this.args = args; this.commands = commands; } /** * Executes the command named `args[0]` if any. If the requested command (in args[0]) is not * supported, display a help message. * * <p> Note that the command name comparison is case sensitive. */ public boolean start() { if (args.length != 0) { String requestedCommand = args[0]; for (Command command : commands) { if (command.getCommandName().equals(requestedCommand)) { command.setArgs(args); return command.start(); } } } displayUsage(); return false; } /** * Displays a message containing the list of the supported commands by this dispatcher. */ private void displayUsage() { StringBuilder msg = new StringBuilder("Usage: java -jar /path/to/jar [ "); int i = 0; for (Command command : commands) { msg.append(command.getCommandName()); if (i++ != commands.length - 1) { msg.append(" | "); } } msg.append(" ] args"); System.err.println(msg.toString()); } }
2301_81045437/third_party_libphonenumber
tools/java/common/src/com/google/i18n/phonenumbers/CommandDispatcher.java
Java
unknown
2,601
/* * Copyright (C) 2011 The Libphonenumber 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. */ package com.google.i18n.phonenumbers; import java.io.IOException; import java.io.Writer; import java.util.Formatter; /** * Class containing the Apache copyright notice used by code generators. * * @author Philippe Liard */ public class CopyrightNotice { private static final String TEXT_OPENING = "/*\n"; private static final String TEXT_OPENING_FOR_JAVASCRIPT = "/**\n" + " * @license\n"; private static final String TEXT = " * Copyright (C) %d The Libphonenumber Authors\n" + " *\n" + " * Licensed under the Apache License, Version 2.0 (the \"License\");\n" + " * you may not use this file except in compliance with the License.\n" + " * You may obtain a copy of the License at\n" + " *\n" + " * http://www.apache.org/licenses/LICENSE-2.0\n" + " *\n" + " * Unless required by applicable law or agreed to in writing, software\n" + " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + " * See the License for the specific language governing permissions and\n" + " * limitations under the License.\n" + " */\n\n"; static final void writeTo(Writer writer, int year) throws IOException { writeTo(writer, year, false); } static final void writeTo(Writer writer, int year, boolean isJavascript) throws IOException { if (isJavascript) { writer.write(TEXT_OPENING_FOR_JAVASCRIPT); } else { writer.write(TEXT_OPENING); } Formatter formatter = new Formatter(writer); formatter.format(TEXT, year); } }
2301_81045437/third_party_libphonenumber
tools/java/common/src/com/google/i18n/phonenumbers/CopyrightNotice.java
Java
unknown
2,248
/* * Copyright (C) 2011 The Libphonenumber 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. * under the License. */ package com.google.i18n.phonenumbers; import java.io.Closeable; import java.io.IOException; /** * Helper class containing methods designed to ease file manipulation and generation. * * @author Philippe Liard */ public class FileUtils { /** * Silently closes a resource (i.e: don't throw any exception). */ private static void close(Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (IOException e) { System.err.println(e.getMessage()); } } /** * Silently closes multiple resources. This method doesn't throw any exception when an error * occurs when a resource is being closed. */ public static void closeFiles(Closeable ... closeables) { for (Closeable closeable : closeables) { close(closeable); } } }
2301_81045437/third_party_libphonenumber
tools/java/common/src/com/google/i18n/phonenumbers/FileUtils.java
Java
unknown
1,480
/* * Copyright (C) 2016 The Libphonenumber 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. */ package com.google.i18n.phonenumbers; import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata; import com.google.i18n.phonenumbers.Phonemetadata.PhoneNumberDesc; import java.util.Arrays; import java.util.TreeMap; import java.util.TreeSet; /** * Class to encapsulate the metadata filtering logic and restrict visibility into raw data * structures. * * <p> * WARNING: This is an internal API which is under development and subject to backwards-incompatible * changes without notice. Any changes are not guaranteed to be reflected in the versioning scheme * of the public API, nor in release notes. */ final class MetadataFilter { // The following 3 sets comprise all the PhoneMetadata fields as defined at phonemetadata.proto // which may be excluded from customized serializations of the binary metadata. Fields that are // core to the library functionality may not be listed here. // excludableParentFields are PhoneMetadata fields of type PhoneNumberDesc. // excludableChildFields are PhoneNumberDesc fields of primitive type. // excludableChildlessFields are PhoneMetadata fields of primitive type. // Currently we support only one non-primitive type and the depth of the "family tree" is 2, // meaning a field may have only direct descendants, who may not have descendants of their own. If // this changes, the blacklist handling in this class should also change. // @VisibleForTesting static final TreeSet<String> excludableParentFields = new TreeSet<String>(Arrays.asList( "fixedLine", "mobile", "tollFree", "premiumRate", "sharedCost", "personalNumber", "voip", "pager", "uan", "emergency", "voicemail", "shortCode", "standardRate", "carrierSpecific", "smsServices", "noInternationalDialling")); // Note: If this set changes, the descHasData implementation must change in PhoneNumberUtil. // The current implementation assumes that all PhoneNumberDesc fields are present here, since it // "clears" a PhoneNumberDesc field by simply clearing all of the fields under it. See the comment // above, about all 3 sets, for more about these fields. // @VisibleForTesting static final TreeSet<String> excludableChildFields = new TreeSet<String>(Arrays.asList( "nationalNumberPattern", "possibleLength", "possibleLengthLocalOnly", "exampleNumber")); // @VisibleForTesting static final TreeSet<String> excludableChildlessFields = new TreeSet<String>(Arrays.asList( "preferredInternationalPrefix", "nationalPrefix", "preferredExtnPrefix", "nationalPrefixTransformRule", "sameMobileAndFixedLinePattern", "mainCountryForCode", "leadingZeroPossible", "mobileNumberPortableRegion")); private final TreeMap<String, TreeSet<String>> blacklist; // Note: If changing the blacklist here or the name of the method, update documentation about // affected methods at the same time: // https://github.com/google/libphonenumber/blob/master/FAQ.md#what-is-the-metadatalitejsmetadata_lite-option static MetadataFilter forLiteBuild() { // "exampleNumber" is a blacklist. return new MetadataFilter(parseFieldMapFromString("exampleNumber")); } static MetadataFilter forSpecialBuild() { // "mobile" is a whitelist. return new MetadataFilter(computeComplement(parseFieldMapFromString("mobile"))); } static MetadataFilter emptyFilter() { // Empty blacklist, meaning we filter nothing. return new MetadataFilter(new TreeMap<String, TreeSet<String>>()); } // @VisibleForTesting MetadataFilter(TreeMap<String, TreeSet<String>> blacklist) { this.blacklist = blacklist; } @Override public boolean equals(Object obj) { return blacklist.equals(((MetadataFilter) obj).blacklist); } @Override public int hashCode() { return blacklist.hashCode(); } /** * Clears certain fields in {@code metadata} as defined by the {@code MetadataFilter} instance. * Note that this changes the mutable {@code metadata} object, and is not thread-safe. If this * method does not return successfully, do not assume {@code metadata} has not changed. * * @param metadata The {@code PhoneMetadata} object to be filtered */ void filterMetadata(PhoneMetadata.Builder metadata) { // TODO: Consider clearing if the filtered PhoneNumberDesc is empty. if (metadata.hasFixedLine()) { metadata.setFixedLine(getFiltered("fixedLine", metadata.getFixedLine())); } if (metadata.hasMobile()) { metadata.setMobile(getFiltered("mobile", metadata.getMobile())); } if (metadata.hasTollFree()) { metadata.setTollFree(getFiltered("tollFree", metadata.getTollFree())); } if (metadata.hasPremiumRate()) { metadata.setPremiumRate(getFiltered("premiumRate", metadata.getPremiumRate())); } if (metadata.hasSharedCost()) { metadata.setSharedCost(getFiltered("sharedCost", metadata.getSharedCost())); } if (metadata.hasPersonalNumber()) { metadata.setPersonalNumber(getFiltered("personalNumber", metadata.getPersonalNumber())); } if (metadata.hasVoip()) { metadata.setVoip(getFiltered("voip", metadata.getVoip())); } if (metadata.hasPager()) { metadata.setPager(getFiltered("pager", metadata.getPager())); } if (metadata.hasUan()) { metadata.setUan(getFiltered("uan", metadata.getUan())); } if (metadata.hasEmergency()) { metadata.setEmergency(getFiltered("emergency", metadata.getEmergency())); } if (metadata.hasVoicemail()) { metadata.setVoicemail(getFiltered("voicemail", metadata.getVoicemail())); } if (metadata.hasShortCode()) { metadata.setShortCode(getFiltered("shortCode", metadata.getShortCode())); } if (metadata.hasStandardRate()) { metadata.setStandardRate(getFiltered("standardRate", metadata.getStandardRate())); } if (metadata.hasCarrierSpecific()) { metadata.setCarrierSpecific(getFiltered("carrierSpecific", metadata.getCarrierSpecific())); } if (metadata.hasSmsServices()) { metadata.setSmsServices(getFiltered("smsServices", metadata.getSmsServices())); } if (metadata.hasNoInternationalDialling()) { metadata.setNoInternationalDialling(getFiltered("noInternationalDialling", metadata.getNoInternationalDialling())); } if (shouldDrop("preferredInternationalPrefix")) { metadata.clearPreferredInternationalPrefix(); } if (shouldDrop("nationalPrefix")) { metadata.clearNationalPrefix(); } if (shouldDrop("preferredExtnPrefix")) { metadata.clearPreferredExtnPrefix(); } if (shouldDrop("nationalPrefixTransformRule")) { metadata.clearNationalPrefixTransformRule(); } if (shouldDrop("sameMobileAndFixedLinePattern")) { metadata.clearSameMobileAndFixedLinePattern(); } if (shouldDrop("mainCountryForCode")) { metadata.clearMainCountryForCode(); } if (shouldDrop("leadingZeroPossible")) { metadata.clearLeadingZeroPossible(); } if (shouldDrop("mobileNumberPortableRegion")) { metadata.clearMobileNumberPortableRegion(); } } /** * The input blacklist or whitelist string is expected to be of the form "a(b,c):d(e):f", where * b and c are children of a, e is a child of d, and f is either a parent field, a child field, or * a childless field. Order and whitespace don't matter. We throw RuntimeException for any * duplicates, malformed strings, or strings where field tokens do not correspond to strings in * the sets of excludable fields. We also throw RuntimeException for empty strings since such * strings should be treated as a special case by the flag checking code and not passed here. */ // @VisibleForTesting static TreeMap<String, TreeSet<String>> parseFieldMapFromString(String string) { if (string == null) { throw new RuntimeException("Null string should not be passed to parseFieldMapFromString"); } // Remove whitespace. string = string.replaceAll("\\s", ""); if (string.isEmpty()) { throw new RuntimeException("Empty string should not be passed to parseFieldMapFromString"); } TreeMap<String, TreeSet<String>> fieldMap = new TreeMap<String, TreeSet<String>>(); TreeSet<String> wildcardChildren = new TreeSet<String>(); for (String group : string.split(":", -1)) { int leftParenIndex = group.indexOf('('); int rightParenIndex = group.indexOf(')'); if (leftParenIndex < 0 && rightParenIndex < 0) { if (excludableParentFields.contains(group)) { if (fieldMap.containsKey(group)) { throw new RuntimeException(group + " given more than once in " + string); } fieldMap.put(group, new TreeSet<String>(excludableChildFields)); } else if (excludableChildlessFields.contains(group)) { if (fieldMap.containsKey(group)) { throw new RuntimeException(group + " given more than once in " + string); } fieldMap.put(group, new TreeSet<String>()); } else if (excludableChildFields.contains(group)) { if (wildcardChildren.contains(group)) { throw new RuntimeException(group + " given more than once in " + string); } wildcardChildren.add(group); } else { throw new RuntimeException(group + " is not a valid token"); } } else if (leftParenIndex > 0 && rightParenIndex == group.length() - 1) { // We don't check for duplicate parentheses or illegal characters since these will be caught // as not being part of valid field tokens. String parent = group.substring(0, leftParenIndex); if (!excludableParentFields.contains(parent)) { throw new RuntimeException(parent + " is not a valid parent token"); } if (fieldMap.containsKey(parent)) { throw new RuntimeException(parent + " given more than once in " + string); } TreeSet<String> children = new TreeSet<String>(); for (String child : group.substring(leftParenIndex + 1, rightParenIndex).split(",", -1)) { if (!excludableChildFields.contains(child)) { throw new RuntimeException(child + " is not a valid child token"); } if (!children.add(child)) { throw new RuntimeException(child + " given more than once in " + group); } } fieldMap.put(parent, children); } else { throw new RuntimeException("Incorrect location of parantheses in " + group); } } for (String wildcardChild : wildcardChildren) { for (String parent : excludableParentFields) { TreeSet<String> children = fieldMap.get(parent); if (children == null) { children = new TreeSet<String>(); fieldMap.put(parent, children); } if (!children.add(wildcardChild) && fieldMap.get(parent).size() != excludableChildFields.size()) { // The map already contains parent -> wildcardChild but not all possible children. // So wildcardChild was given explicitly as a child of parent, which is a duplication // since it's also given as a wildcard child. throw new RuntimeException( wildcardChild + " is present by itself so remove it from " + parent + "'s group"); } } } return fieldMap; } // Does not check that legal tokens are used, assuming that fieldMap is constructed using // parseFieldMapFromString(String) which does check. If fieldMap contains illegal tokens or parent // fields with no children or other unexpected state, the behavior of this function is undefined. // @VisibleForTesting static TreeMap<String, TreeSet<String>> computeComplement( TreeMap<String, TreeSet<String>> fieldMap) { TreeMap<String, TreeSet<String>> complement = new TreeMap<String, TreeSet<String>>(); for (String parent : excludableParentFields) { if (!fieldMap.containsKey(parent)) { complement.put(parent, new TreeSet<String>(excludableChildFields)); } else { TreeSet<String> otherChildren = fieldMap.get(parent); // If the other map has all the children for this parent then we don't want to include the // parent as a key. if (otherChildren.size() != excludableChildFields.size()) { TreeSet<String> children = new TreeSet<String>(); for (String child : excludableChildFields) { if (!otherChildren.contains(child)) { children.add(child); } } complement.put(parent, children); } } } for (String childlessField : excludableChildlessFields) { if (!fieldMap.containsKey(childlessField)) { complement.put(childlessField, new TreeSet<String>()); } } return complement; } // @VisibleForTesting boolean shouldDrop(String parent, String child) { if (!excludableParentFields.contains(parent)) { throw new RuntimeException(parent + " is not an excludable parent field"); } if (!excludableChildFields.contains(child)) { throw new RuntimeException(child + " is not an excludable child field"); } return blacklist.containsKey(parent) && blacklist.get(parent).contains(child); } // @VisibleForTesting boolean shouldDrop(String childlessField) { if (!excludableChildlessFields.contains(childlessField)) { throw new RuntimeException(childlessField + " is not an excludable childless field"); } return blacklist.containsKey(childlessField); } private PhoneNumberDesc getFiltered(String type, PhoneNumberDesc desc) { PhoneNumberDesc.Builder builder = PhoneNumberDesc.newBuilder().mergeFrom(desc); if (shouldDrop(type, "nationalNumberPattern")) { builder.clearNationalNumberPattern(); } if (shouldDrop(type, "possibleLength")) { builder.clearPossibleLength(); } if (shouldDrop(type, "possibleLengthLocalOnly")) { builder.clearPossibleLengthLocalOnly(); } if (shouldDrop(type, "exampleNumber")) { builder.clearExampleNumber(); } return builder.build(); } }
2301_81045437/third_party_libphonenumber
tools/java/common/src/com/google/i18n/phonenumbers/MetadataFilter.java
Java
unknown
14,906
/* * Copyright (C) 2011 The Libphonenumber 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. */ package com.google.i18n.phonenumbers; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Logger; /** * Utility class that makes the geocoding data as small as possible. This class assumes the * geocoding data provided as input doesn't contain any gaps thus should not be used with incomplete * data (missing prefixes). * <pre> * Example: Can be combined as: * 33131|Paris 331|Paris * 33132|Paris 334|Marseille * 3341|Marseille * </pre> * * @author Philippe Liard */ public class CombineGeoData { private final InputStream inputStream; private final OutputStream outputStream; private final String outputLineSeparator; private static final Logger LOGGER = Logger.getLogger(CombineGeoData.class.getName()); public CombineGeoData(InputStream inputStream, OutputStream outputStream, String lineSeparator) { this.inputStream = inputStream; this.outputStream = outputStream; this.outputLineSeparator = lineSeparator; } public CombineGeoData(InputStream inputStream, OutputStream outputStream) { this(inputStream, outputStream, System.getProperty("line.separator")); } /** * Utility class that contains two indexes (start and end). */ static class Range { public final int start; public final int end; public Range(int start, int end) { this.start = start; this.end = end; } } /** * Parses the input text file expected to contain lines written as 'prefix|description'. Note that * description can be empty. * * @return the map of phone prefix data parsed. * @throws IOException */ private SortedMap<String, String> parseInput() throws IOException { SortedMap<String, String> outputMap = new TreeMap<String, String>(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); for (String line; (line = bufferedReader.readLine()) != null; ) { int indexOfPipe = line.indexOf('|'); if (indexOfPipe == -1) { continue; } outputMap.put(line.substring(0, indexOfPipe), line.substring(indexOfPipe + 1)); } return outputMap; } /** * Creates a sorted array of phone number prefixes as strings from the provided phone number * prefix map. * * @return the array of phone number prefixes sorted by string. */ static String[] createSortedPrefixArray(SortedMap<String, String> phonePrefixMap) { String[] sortedPrefixes = new String[phonePrefixMap.size()]; phonePrefixMap.keySet().toArray(sortedPrefixes); return sortedPrefixes; } /** * Finds the end index of the range of phone number prefixes starting at the provided index. * A range ends when a different description or prefix divided by 10 is encountered. * * @param prefixes the array of phone number prefixes sorted by string * @param phonePrefixMap the map associating phone number prefixes and descriptions * @param start the start index of the prefixes array * @return the index of the end of the range starting at the provided index */ static int findRangeEnd(String[] prefixes, Map<String, String> phonePrefixMap, int start) { String previousPrefix = prefixes[start]; int previousPrefixAsInt = Integer.parseInt(previousPrefix); String previousLocation = phonePrefixMap.get(previousPrefix); for (int i = start; i < prefixes.length; i++) { String currentPrefix = prefixes[i]; String currentLocation = phonePrefixMap.get(currentPrefix); if (!currentLocation.equals(previousLocation) || (Integer.parseInt(currentPrefix) / 10 != previousPrefixAsInt / 10)) { return i - 1; } } return prefixes.length - 1; } /** * Splits the provided array of prefixes into an array of ranges. A range contains the start and * end indexes of a set of mappings that share the same description and have the same prefix minus * the last digit. * * @param prefixes the array of phone number prefixes sorted by string * @param phonePrefixMap the map associating phone number prefixes and descriptions * @return the list of ranges */ static List<Range> createRanges(String[] prefixes, Map<String, String> phonePrefixMap) { List<Range> ranges = new ArrayList<Range>(); int index = 0; int phonePrefixMapSize = phonePrefixMap.size(); while (index < phonePrefixMapSize) { int rangeEnd = findRangeEnd(prefixes, phonePrefixMap, index); ranges.add(new Range(index, rangeEnd)); index = rangeEnd + 1; } return ranges; } /** * Checks whether the provided candidate prefix conflicts with the prefixes contained in the * provided range. A conflict occurs if the provided prefix covers (is a prefix of) one of the * prefixes contained in the range. * * @param prefixes the array of phone number prefixes sorted by string * @param candidate the candidate phone number prefix * @param start the start of the range * @param end the end of the range * @return whether the candidate prefix conflicts with the prefixes contained in the range */ static boolean findConflict(String[] prefixes, int candidate, int start, int end) { String candidateAsString = String.valueOf(candidate); for (int i = start; i <= end; i++) { String prefix = prefixes[i]; if (prefix.startsWith(candidateAsString)) { return true; } } return false; } /** * Checks whether the provided candidate prefix conflicts with the prefixes contained in the * ranges adjacent (before and after the provided range) of the provided range. * * @param ranges the list of ranges * @param rangeIndex the index of the range in which the conflict search occurs * @param prefixes the array of phone number prefixes sorted by string * @param candidate the candidate phone number prefix * @return whether a conflict was found in the provided range */ static boolean hasConflict(List<Range> ranges, int rangeIndex, String[] prefixes, int candidate) { if (rangeIndex > 0) { Range previousRange = ranges.get(rangeIndex - 1); if (findConflict(prefixes, candidate, previousRange.start, previousRange.end)) { return true; } } if (rangeIndex < ranges.size() - 1) { Range nextRange = ranges.get(rangeIndex + 1); if (findConflict(prefixes, candidate, nextRange.start, nextRange.end)) { return true; } } return false; } /** * Combines the mappings contained in the provided map. A new combined map is returned as a result * in case any combination occurred. Otherwise (if no combination occurred) the same map (same * identity) is returned. Note that this method performs a 'single step' (i.e performs only one * combination iteration). */ static SortedMap<String, String> combine(SortedMap<String, String> phonePrefixMap) { String[] prefixes = createSortedPrefixArray(phonePrefixMap); List<Range> ranges = createRanges(prefixes, phonePrefixMap); Map<Integer /* range index */, Integer> combinedPrefixes = new HashMap<Integer, Integer>(); int rangeIndex = 0; for (Range range : ranges) { int prefixCandidate = Integer.parseInt(prefixes[range.start]) / 10; if (prefixCandidate != 0 && !hasConflict(ranges, rangeIndex, prefixes, prefixCandidate)) { combinedPrefixes.put(rangeIndex, prefixCandidate); } ++rangeIndex; } if (combinedPrefixes.size() == 0) { return phonePrefixMap; } SortedMap<String, String> combinedMap = new TreeMap<String, String>(); rangeIndex = 0; for (Range range : ranges) { Integer combinedRange = combinedPrefixes.get(rangeIndex++); if (combinedRange != null) { String firstPrefixOfRange = prefixes[range.start]; combinedMap.put(String.valueOf(combinedRange), phonePrefixMap.get(firstPrefixOfRange)); } else { for (int i = range.start; i <= range.end; i++) { String prefix = prefixes[i]; combinedMap.put(prefix, phonePrefixMap.get(prefix)); } } } return combinedMap; } /** * Combines the provided map associating phone number prefixes and descriptions. * * @return the combined map */ static SortedMap<String, String> combineMultipleTimes(SortedMap<String, String> phonePrefixMap) { SortedMap<String, String> previousMap = null; while (phonePrefixMap != previousMap) { previousMap = phonePrefixMap; phonePrefixMap = combine(phonePrefixMap); } return phonePrefixMap; } /** * Combines the geocoding data read from the provided input stream and writes it as a result to * the provided output stream. Uses the provided string as the line separator. */ public void run() throws IOException { SortedMap<String, String> phonePrefixMap = parseInput(); phonePrefixMap = combineMultipleTimes(phonePrefixMap); PrintWriter printWriter = new PrintWriter(new BufferedOutputStream(outputStream)); for (Map.Entry<String, String> mapping : phonePrefixMap.entrySet()) { printWriter.printf("%s|%s%s", mapping.getKey(), mapping.getValue(), outputLineSeparator); } printWriter.flush(); } public static void main(String[] args) { if (args.length != 2) { LOGGER.severe("usage: java -jar combine-geodata.jar /path/to/input /path/to/output"); System.exit(1); } try { CombineGeoData combineGeoData = new CombineGeoData(new FileInputStream(args[0]), new FileOutputStream(args[1])); combineGeoData.run(); } catch (Exception e) { LOGGER.severe(e.getMessage()); System.exit(1); } } }
2301_81045437/third_party_libphonenumber
tools/java/data/src/com/google/i18n/phonenumbers/CombineGeoData.java
Java
unknown
10,706
/* * Copyright (C) 2011 The Libphonenumber 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. * * @author Philippe Liard */ package com.google.i18n.phonenumbers; import java.io.ByteArrayInputStream; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * A servlet that invokes the geocoding data combination tool. */ public class CombineGeoDataServlet extends HttpServlet { @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html;charset=UTF-8"); String input = req.getParameter("geodata"); resp.getOutputStream().print("<html><head>"); resp.getOutputStream().print( "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"></head>"); resp.getOutputStream().print("<body>"); CombineGeoData combineGeoData = new CombineGeoData( new ByteArrayInputStream(input.getBytes()), resp.getOutputStream(), "<br>"); combineGeoData.run(); resp.getOutputStream().print("</body></html>"); resp.getOutputStream().flush(); } }
2301_81045437/third_party_libphonenumber
tools/java/data/src/com/google/i18n/phonenumbers/CombineGeoDataServlet.java
Java
unknown
1,690
<html> <head><meta http-equiv="content-type" content="text/html; charset=UTF-8"></head> <body> <form action="/combine" method="post" accept-charset="UTF-8"> <h2>Geocoding Prefix Reducer</h2> <p>Please paste your geocoding data below. Each line should be in the format "prefix|description". Lines without a "|" symbol will be ignored.</p> <u>Input example:</u><br> 331|Paris<br> 334|Marseilles<br> <br> <textarea name="geodata" rows="20" cols="80"></textarea> <input type="submit" value="Submit"><br> <a href="https://github.com/google/libphonenumber/">Back to libphonenumber</a> </form> </body> </html>
2301_81045437/third_party_libphonenumber
tools/java/data/webapp/index.html
HTML
unknown
682
#! /bin/sh # Copyright (C) 2011 The Libphonenumber 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. # Author: Philippe Liard # Countinuous integration script that tests the different versions and # configurations of libphonenumber. # Check geocoding resource files encoding. (find resources/geocoding -type f | xargs file | egrep -v 'UTF-8|ASCII') && exit 1 # Test the C++ version with the provided CMake parameter. CXX=g++ INSTALL_PREFIX=/tmp/libphonenumber test_cpp_version() { CC_TEST_FILE=`mktemp`.cc CC_TEST_BINARY=`mktemp` CMAKE_FLAGS="$1" LD_FLAGS="-L${INSTALL_PREFIX}/lib -lphonenumber -lboost_thread $2" # Write the program that tests the installation of the library to a temporary # source file. > $CC_TEST_FILE echo ' #include <cassert> #include <base/memory/scoped_ptr.h> // Include all the public headers. #include <phonenumbers/asyoutypeformatter.h> #include <phonenumbers/phonenumber.pb.h> #include <phonenumbers/phonenumbermatch.h> #include <phonenumbers/phonenumbermatcher.h> #include <phonenumbers/phonenumberutil.h> using i18n::phonenumbers::AsYouTypeFormatter; using i18n::phonenumbers::PhoneNumberUtil; int main() { PhoneNumberUtil* const phone_util = PhoneNumberUtil::GetInstance(); const scoped_ptr<AsYouTypeFormatter> asytf( phone_util->GetAsYouTypeFormatter("US")); assert(phone_util != NULL); assert(asytf != NULL); }' # Run the build and tests. ( set +e rm -rf cpp/build /tmp/libphonenumber mkdir cpp/build /tmp/libphonenumber cd cpp/build cmake "${CMAKE_FLAGS}" -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX .. make test make install $CXX -o $CC_TEST_BINARY $CC_TEST_FILE -I${INSTALL_PREFIX}/include $LD_FLAGS LD_LIBRARY_PATH="${INSTALL_PREFIX}/lib" $CC_TEST_BINARY ) STATUS=$? # Remove the temporary files. rm -f $CC_TEST_FILE rm -f $CC_TEST_BINARY [ $STATUS -ne 0 ] && exit $STATUS } BASE_LIBS='-licuuc -lprotobuf' test_cpp_version '' "$BASE_LIBS" test_cpp_version '-DUSE_ICU_REGEXP=ON' "$BASE_LIBS" test_cpp_version '-DUSE_LITE_METADATA=ON' '-licuuc -lprotobuf-lite' test_cpp_version '-DUSE_RE2=ON' "$BASE_LIBS -lre2" test_cpp_version '-DUSE_STD_MAP=ON' "$BASE_LIBS" # Test Java version using Ant. (cd java && ant clean jar && ant junit) || exit $? # Test Java version using Maven. (cd java && mvn clean package) || exit $? # Test build tools. (cd tools/java && mvn clean package) || exit $?
2301_81045437/third_party_libphonenumber
tools/script/continuous-integration.sh
Shell
unknown
2,984
cmake_minimum_required (VERSION 3.5) project (webrtc-streamer) set (WEBRTCROOT "${CMAKE_CURRENT_SOURCE_DIR}/../webrtc" CACHE STRING "WEBRTC root directory") set (WEBRTCDESKTOPCAPTURE "ON" CACHE STRING "WEBRTC Desktop capture") set (WEBRTCCHROMEBRANDED "ON" CACHE STRING "WEBRTC Chrome branded") if(NOT CMAKE_BUILD_TYPE) set (CMAKE_BUILD_TYPE "Release") endif() MESSAGE("CMAKE_BUILD_TYPE = ${CMAKE_BUILD_TYPE}\nWEBRTCROOT = ${WEBRTCROOT}\nWEBRTCDESKTOPCAPTURE= ${WEBRTCDESKTOPCAPTURE}\nCMAKE_CXX_COMPILER_ID=${CMAKE_CXX_COMPILER_ID}") set (CMAKE_POSITION_INDEPENDENT_CODE ON) set (CMAKE_CXX_STANDARD 20) set (CMAKE_CXX_EXTENSIONS OFF) # build version identifier find_package(Git) if(GIT_FOUND) EXECUTE_PROCESS(COMMAND ${GIT_EXECUTABLE} submodule update --init) EXECUTE_PROCESS(COMMAND ${GIT_EXECUTABLE} describe --tags --always --dirty OUTPUT_VARIABLE PROJECTVERSION OUTPUT_STRIP_TRAILING_WHITESPACE) set (VERSION "${PROJECTVERSION}/${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}") EXECUTE_PROCESS(COMMAND ${GIT_EXECUTABLE} -C civetweb describe --tags --always --dirty OUTPUT_VARIABLE CIVETVERSION OUTPUT_STRIP_TRAILING_WHITESPACE) set (VERSION "${VERSION} civetweb@${CIVETVERSION}") EXECUTE_PROCESS(COMMAND ${GIT_EXECUTABLE} -C ${WEBRTCROOT}/src describe --tags --always --dirty OUTPUT_VARIABLE WEBRTCVERSION OUTPUT_STRIP_TRAILING_WHITESPACE) set (VERSION "${VERSION} webrtc@${WEBRTCVERSION}") EXECUTE_PROCESS(COMMAND ${GIT_EXECUTABLE} -C live555helper describe --tags --always --dirty OUTPUT_VARIABLE LIVEVERSION OUTPUT_STRIP_TRAILING_WHITESPACE) set (VERSION "${VERSION} live555helper@${LIVEVERSION}") endif() add_definitions(-DVERSION=\"${VERSION}\") # set CMAKE_FIND_ROOT_PATH to search package in WebRTC sysroot if(CMAKE_SYSTEM_PROCESSOR MATCHES "armv.*") set (CMAKE_FIND_ROOT_PATH ${WEBRTCROOT}/src/build/linux/debian_bullseye_arm-sysroot) elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "arm64") set (CMAKE_FIND_ROOT_PATH ${WEBRTCROOT}/src/build/linux/debian_bullseye_arm64-sysroot) add_compile_options(--sysroot=${CMAKE_FIND_ROOT_PATH}) endif() MESSAGE("CMAKE_FIND_ROOT_PATH = ${CMAKE_FIND_ROOT_PATH}") # alsa ? find_package(ALSA QUIET) MESSAGE("ALSA_FOUND = ${ALSA_FOUND}") # pulse ? find_package(PulseAudio QUIET) MESSAGE("PulseAudio_FOUND = ${PulseAudio_FOUND}") # webrtc build set (WEBRTCOBJS ${WEBRTCROOT}/src/out/${CMAKE_BUILD_TYPE}/obj) if (NOT EXISTS ${WEBRTCOBJS}/${CMAKE_STATIC_LIBRARY_PREFIX}webrtc${CMAKE_STATIC_LIBRARY_SUFFIX}) set (WEBRTCARGS rtc_include_tests=false\nrtc_enable_protobuf=false\nrtc_build_examples=false\nrtc_build_tools=false\ntreat_warnings_as_errors=false\nrtc_enable_libevent=false\nrtc_build_libevent=false\nuse_glib=false\nuse_lld=false\n) set (WEBRTCARGS use_custom_libcxx=false\n${WEBRTCARGS}) # debug/release if(CMAKE_BUILD_TYPE STREQUAL "Release") set (WEBRTCARGS is_debug=false\n${WEBRTCARGS}) else() set (WEBRTCARGS is_debug=true\n${WEBRTCARGS}) endif() # enable H264 support if (WEBRTCCHROMEBRANDED STREQUAL "ON") set (WEBRTCARGS is_chrome_branded=true\n${WEBRTCARGS}) else() set (WEBRTCARGS rtc_use_h264=true\nrtc_use_h265=true\n${WEBRTCARGS}) endif() if (CMAKE_SYSTEM_PROCESSOR MATCHES "armv6.*") set(ENV{PATH} "${WEBRTCROOT}/src/third_party/llvm-build/Release+Asserts/bin:$ENV{PATH}") set (CONFIGURE_ARGS --disable-everything --disable-all --disable-doc --disable-htmlpages --disable-manpages --disable-podpages --disable-txtpages --disable-static --enable-avcodec --enable-avformat --enable-avutil --enable-static --enable-libopus --disable-debug --disable-bzlib --disable-iconv --disable-network --disable-schannel --disable-sdl2 --disable-symver --disable-xlib --disable-zlib --disable-securetransport --disable-faan --disable-alsa --disable-autodetect --disable-error-resilience --enable-decoder=vorbis,libopus,flac --enable-decoder=pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,mp3 --enable-decoder=pcm_s16be,pcm_s24be,pcm_mulaw,pcm_alaw --enable-demuxer=ogg,matroska,wav,flac,mp3,mov --enable-parser=opus,vorbis,flac,mpegaudio,vp9 --extra-cflags=-I${WEBRTCROOT}/src/third_party/opus/src/include --disable-linux-perf --x86asmexe=nasm --optflags="-O2" --arch=arm --enable-armv6 --disable-armv6t2 --enable-vfp --disable-thumb --extra-cflags=-march=armv6 --enable-cross-compile --target-os=linux --extra-cflags=--target=arm-linux-gnueabihf --extra-ldflags=--target=arm-linux-gnueabihf --sysroot=${WEBRTCROOT}/src/build/linux/debian_bullseye_armhf-sysroot --extra-cflags=-mtune=cortex-a8 --extra-cflags=-mfloat-abi=hard --extra-cflags=-O2 --disable-neon --extra-cflags=-mfpu=vfpv3-d16 --enable-pic --cc=clang --cxx=clang++ --ld=clang --extra-ldflags=-fuse-ld=lld --enable-decoder=aac,h264 --enable-demuxer=aac --enable-parser=aac,h264) MESSAGE("CONFIGURE_ARGS = ${CONFIGURE_ARGS}") EXECUTE_PROCESS(WORKING_DIRECTORY ${WEBRTCROOT}/src/third_party/ffmpeg COMMAND ./configure ${CONFIGURE_ARGS}) file(COPY ${WEBRTCROOT}/src/third_party/ffmpeg/config.h DESTINATION ${WEBRTCROOT}/src/third_party/ffmpeg/chromium/config/Chrome/linux/arm/) file(COPY ${WEBRTCROOT}/src/third_party/ffmpeg/config_components.h DESTINATION ${WEBRTCROOT}/src/third_party/ffmpeg/chromium/config/Chrome/linux/arm/) file(COPY ${WEBRTCROOT}/src/third_party/ffmpeg/libavutil/avconfig.h DESTINATION ${WEBRTCROOT}/src/third_party/ffmpeg/chromium/config/Chrome/linux/arm/libavutil/) file(COPY ${WEBRTCROOT}/src/third_party/ffmpeg/libavfilter/filter_list.c DESTINATION ${WEBRTCROOT}/src/third_party/ffmpeg/chromium/config/Chrome/linux/arm/libavutil/) file(COPY ${WEBRTCROOT}/src/third_party/ffmpeg/libavcodec/codec_list.c DESTINATION ${WEBRTCROOT}/src/third_party/ffmpeg/chromium/config/Chrome/linux/arm/libavcodec/) file(COPY ${WEBRTCROOT}/src/third_party/ffmpeg/libavcodec/parser_list.c DESTINATION ${WEBRTCROOT}/src/third_party/ffmpeg/chromium/config/Chrome/linux/arm/libavcodec/) file(COPY ${WEBRTCROOT}/src/third_party/ffmpeg/libavcodec/bsf_list.c DESTINATION ${WEBRTCROOT}/src/third_party/ffmpeg/chromium/config/Chrome/linux/arm/libavcodec/) file(COPY ${WEBRTCROOT}/src/third_party/ffmpeg/libavformat/demuxer_list.c DESTINATION ${WEBRTCROOT}/src/third_party/ffmpeg/chromium/config/Chrome/linux/arm/libavformat/) file(COPY ${WEBRTCROOT}/src/third_party/ffmpeg/libavformat/muxer_list.c DESTINATION ${WEBRTCROOT}/src/third_party/ffmpeg/chromium/config/Chrome/linux/arm/libavformat/) file(COPY ${WEBRTCROOT}/src/third_party/ffmpeg/libavformat/protocol_list.c DESTINATION ${WEBRTCROOT}/src/third_party/ffmpeg/chromium/config/Chrome/linux/arm/libavformat/) endif() #patch file(READ ${WEBRTCROOT}/src/modules/congestion_controller/goog_cc/loss_based_bwe_v2.cc filecontent) string(REPLACE "config.emplace()" "config.emplace(Config())" filecontent "${filecontent}") file(WRITE ${WEBRTCROOT}/src/modules/congestion_controller/goog_cc/loss_based_bwe_v2.cc "${filecontent}") # sound support if (APPLE) set (WEBRTCARGS rtc_include_internal_audio_device=true\n${WEBRTCARGS}) set (WEBRTCARGS rtc_include_pulse_audio=true\n${WEBRTCARGS}) elseif (WIN32) set (WEBRTCARGS rtc_include_internal_audio_device=true\n${WEBRTCARGS}) else() if (NOT PulseAudio_FOUND) set (WEBRTCARGS rtc_include_pulse_audio=false\n${WEBRTCARGS}) endif() if (NOT ALSA_FOUND) set (WEBRTCARGS rtc_include_internal_audio_device=false\n${WEBRTCARGS}) endif() endif() # compilation mode depending on target if(CMAKE_SYSTEM_PROCESSOR MATCHES "armv6.*") set (WEBRTCARGS target_cpu="arm"\narm_version=6\narm_float_abi="hard"\nenable_libaom=false\n${WEBRTCARGS}) elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "armv.*") set (WEBRTCARGS target_cpu="arm"\n${WEBRTCARGS}) elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "arm64") set (WEBRTCARGS target_cpu="arm64"\n${WEBRTCARGS}) endif() if (DEFINED CMAKE_FIND_ROOT_PATH) set (WEBRTCARGS use_sysroot=true\n${WEBRTCARGS}) else() set (WEBRTCARGS use_sysroot=false\n${WEBRTCARGS}) endif() set (WEBRTCARGS is_clang=true\n${WEBRTCARGS}) # screen capture support find_package(PkgConfig QUIET) pkg_check_modules(GTK3 QUIET gtk+-3.0) MESSAGE("GTK3_FOUND = ${GTK3_FOUND}") if(NOT GTK3_FOUND OR (WEBRTCDESKTOPCAPTURE STREQUAL "OFF")) set (WEBRTCARGS rtc_use_x11=false\nrtc_use_pipewire=false\n${WEBRTCARGS}) endif() # write conf file FILE(WRITE ${WEBRTCROOT}/src/out/${CMAKE_BUILD_TYPE}/args.gn ${WEBRTCARGS}) if (WIN32) SET (SHELLCOMMAND cmd /c ) endif() EXECUTE_PROCESS(WORKING_DIRECTORY ${WEBRTCROOT}/src/out/${CMAKE_BUILD_TYPE} COMMAND ${SHELLCOMMAND} gn gen .) SET(NINJA_TARGET webrtc rtc_json builtin_video_decoder_factory builtin_video_encoder_factory p2p_server_utils task_queue default_task_queue_factory) EXECUTE_PROCESS(WORKING_DIRECTORY ${WEBRTCROOT}/src/out/${CMAKE_BUILD_TYPE} COMMAND ${SHELLCOMMAND} ninja ${NINJA_TARGET}) endif() FILE(GLOB_RECURSE WEBRTJSONCPPCOBJS ${WEBRTCOBJS}/third_party/jsoncpp/jsoncpp/*${CMAKE_C_OUTPUT_EXTENSION} ${WEBRTCOBJS}/rtc_base/rtc_json/*${CMAKE_C_OUTPUT_EXTENSION}) FILE(GLOB_RECURSE WEBRTP2POBJ ${WEBRTCOBJS}/p2p/p2p_server_utils/*${CMAKE_C_OUTPUT_EXTENSION}) SET (WEBRTCEXTRAOBJS ${WEBRTJSONCPPCOBJS} ${WEBRTP2POBJ} ${WEBRTCCOMOBJ}) # project target FILE(GLOB SOURCE src/*.cpp) add_executable (${CMAKE_PROJECT_NAME} ${SOURCE} ${WEBRTCEXTRAOBJS}) target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE inc) # webrtc set (WEBRTCINCLUDE ${WEBRTCROOT}/src ${WEBRTCROOT}/src/third_party/abseil-cpp ${WEBRTCROOT}/src/third_party/jsoncpp/source/include ${WEBRTCROOT}/src/third_party/jsoncpp/generated ${WEBRTCROOT}/src/third_party/libyuv/include) target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE ${WEBRTCINCLUDE}) target_link_libraries(${CMAKE_PROJECT_NAME} ${WEBRTCOBJS}/api/video_codecs/${CMAKE_STATIC_LIBRARY_PREFIX}builtin_video_encoder_factory${CMAKE_STATIC_LIBRARY_SUFFIX} ${WEBRTCOBJS}/api/video_codecs/${CMAKE_STATIC_LIBRARY_PREFIX}builtin_video_decoder_factory${CMAKE_STATIC_LIBRARY_SUFFIX}) target_link_libraries(${CMAKE_PROJECT_NAME} ${WEBRTCOBJS}/media/${CMAKE_STATIC_LIBRARY_PREFIX}rtc_internal_video_codecs${CMAKE_STATIC_LIBRARY_SUFFIX} ${WEBRTCOBJS}/media/${CMAKE_STATIC_LIBRARY_PREFIX}rtc_simulcast_encoder_adapter${CMAKE_STATIC_LIBRARY_SUFFIX}) target_link_libraries(${CMAKE_PROJECT_NAME} ${WEBRTCOBJS}/${CMAKE_STATIC_LIBRARY_PREFIX}webrtc${CMAKE_STATIC_LIBRARY_SUFFIX}) add_definitions(-DHAVE_JPEG) # thread set(CMAKE_THREAD_PREFER_PTHREAD TRUE) set(THREADS_PREFER_PTHREAD_FLAG TRUE) find_package (Threads) target_link_libraries (${CMAKE_PROJECT_NAME} Threads::Threads) # civetweb add_library (civetweb STATIC civetweb/src/civetweb.c civetweb/src/CivetServer.cpp) add_definitions(-DOPENSSL_API_3_0 -DUSE_WEBSOCKET) target_link_libraries (${CMAKE_PROJECT_NAME} civetweb) target_include_directories(civetweb PUBLIC civetweb/include) # rtmp ? find_package(PkgConfig QUIET) pkg_check_modules(RTMP QUIET librtmp) MESSAGE("RTMP_FOUND = ${RTMP_FOUND} RTMP_INCLUDE_DIRS=${RTMP_INCLUDE_DIRS} RTMP_LIBRARY_DIRS=${RTMP_LIBRARY_DIRS} RTMP_LIBRARIES=${RTMP_LIBRARIES}") if (RTMP_FOUND) add_definitions(-DHAVE_RTMP) target_include_directories (${CMAKE_PROJECT_NAME} PUBLIC ${RTMP_INCLUDE_DIRS}) target_link_directories (${CMAKE_PROJECT_NAME} PUBLIC ${RTMP_LIBRARY_DIRS}) find_library(RTMP_LIB rtmp) MESSAGE("RTMP_LIB=${RTMP_LIB}") target_link_libraries (${CMAKE_PROJECT_NAME} ${RTMP_LIB}) endif() # compiler specific if (WIN32) # overide compilation flags set(CompilerFlags CMAKE_CXX_FLAGS_DEBUG CMAKE_C_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_C_FLAGS_RELEASE) foreach(CompilerFlag ${CompilerFlags}) string(REPLACE "/MD" "/MT" ${CompilerFlag} "${${CompilerFlag}}") endforeach() # getopt add_library (getopt getopt/getopt.c) target_include_directories(getopt PUBLIC getopt) target_link_libraries (${CMAKE_PROJECT_NAME} getopt) # webrtc add_definitions(-DWEBRTC_WIN -EHsc -DNOMINMAX -D__PRETTY_FUNCTION__=__FUNCTION__ -D_HAS_ITERATOR_DEBUGGING=0) add_definitions(-DUSE_X11 -DHAVE_SOUND -D_WINSOCKAPI_) target_link_libraries (${CMAKE_PROJECT_NAME} secur32 dmoguids wmcodecdspuuid strmiids msdmo winmm dxgi d3d11 iphlpapi dwmapi shcore) elseif (APPLE) # live555 add_definitions(-DNEED_XLOCALE_H=1) # webrtc add_definitions(-DHAVE_SOUND) add_definitions(-DWEBRTC_MAC -DWEBRTC_POSIX -fno-rtti) find_library(CORE_FOUNDATION Foundation) find_library(APPLICATION_SERVICES ApplicationServices) find_library(CORE_SERVICES CoreServices) find_library(CORE_AUDIO CoreAudio) find_library(AUDIO_TOOLBOX AudioToolBox) find_library(IO_SURFACE IOSurface) find_library(APP_KIT AppKit) target_link_libraries (${CMAKE_PROJECT_NAME} ${CORE_FOUNDATION} ${APPLICATION_SERVICES} ${CORE_SERVICES} ${CORE_AUDIO} ${AUDIO_TOOLBOX} ${IO_SURFACE} ${APP_KIT}) else() # libv4l2cpp add_definitions(-DHAVE_V4L2) aux_source_directory(libv4l2cpp/src LIBSRC_FILES) include_directories("libv4l2cpp/inc") add_library(libv4l2cpp STATIC ${LIBSRC_FILES}) target_link_libraries (${CMAKE_PROJECT_NAME} libv4l2cpp) # webrtc add_definitions(-DWEBRTC_POSIX -fno-rtti) if (CMAKE_SYSTEM_PROCESSOR MATCHES "armv6.*") add_definitions(-marm -march=armv6 -mfpu=vfp -mfloat-abi=hard) endif() if (EXISTS ${WEBRTCROOT}/src/out/${CMAKE_BUILD_TYPE}/obj/modules/desktop_capture/desktop_capture.ninja) add_definitions(-DUSE_X11) find_package(X11) target_link_libraries(${CMAKE_PROJECT_NAME} ${X11_LIBRARIES} ${X11_Xdamage_LIB} ${X11_Xfixes_LIB} ${X11_Xcomposite_LIB} ${X11_Xrandr_LIB} ${X11_Xtst_LIB}) endif() # civetweb target_link_libraries(${CMAKE_PROJECT_NAME} dl) #alsa if (ALSA_FOUND) add_definitions(-DHAVE_SOUND) endif() endif() # prometheus include(GenerateExportHeader) include(GNUInstallDirs) set(PROJECT_NAME prometheus-cpp) add_subdirectory(prometheus-cpp/core EXCLUDE_FROM_ALL) target_link_libraries (${CMAKE_PROJECT_NAME} core) target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE prometheus-cpp/core/include) # live555helper include_directories(${WEBRTCROOT}/src/third_party/boringssl/src/include) add_subdirectory(live555helper EXCLUDE_FROM_ALL) target_link_libraries (${CMAKE_PROJECT_NAME} liblive555helper ${WEBRTCOBJS}/third_party/boringssl/${CMAKE_STATIC_LIBRARY_PREFIX}boringssl${CMAKE_STATIC_LIBRARY_SUFFIX}) add_definitions(-DHAVE_LIVE555) # static link of libatomic on armv6l if (CMAKE_SYSTEM_PROCESSOR MATCHES "armv6.*") target_link_libraries (${CMAKE_PROJECT_NAME} -Wl,-Bstatic -latomic -Wl,-Bdynamic) endif() # static link of stdc++ if available if (NOT APPLE) include(CheckCXXCompilerFlag) CHECK_CXX_COMPILER_FLAG("-static-libgcc" CXX_SUPPORTS_STATIC_LIBGCC) if (CXX_SUPPORTS_STATIC_LIBGCC) target_link_libraries (${CMAKE_PROJECT_NAME} -static-libgcc) endif() CHECK_CXX_COMPILER_FLAG("-static-libstdc++" CXX_SUPPORTS_STATIC_LIBSTDCPP) if (CXX_SUPPORTS_STATIC_LIBSTDCPP) target_link_libraries (${CMAKE_PROJECT_NAME} -static-libstdc++) endif() endif() #cpack install (TARGETS ${CMAKE_PROJECT_NAME} RUNTIME DESTINATION .) install (DIRECTORY html DESTINATION .) install (FILES config.json DESTINATION .) install (FILES Procfile DESTINATION .) SET(CPACK_GENERATOR "TGZ") SET(CPACK_SYSTEM_NAME ${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}-${CMAKE_BUILD_TYPE}) SET(CPACK_PACKAGE_CONTACT "michel.promonet@free.fr") if(PROJECTVERSION) SET(CPACK_PACKAGE_VERSION "${PROJECTVERSION}") endif() INCLUDE(CPack)
2301_81045437/webrtc-streamer
CMakeLists.txt
CMake
unlicense
15,629
# build FROM ubuntu:24.04 as builder LABEL maintainer=michel.promonet@free.fr ARG USERNAME=dev WORKDIR /webrtc-streamer COPY . /webrtc-streamer ENV PATH /depot_tools:$PATH RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ca-certificates wget git python3 python3-pkg-resources g++ autoconf automake libtool xz-utils libpulse-dev libasound2-dev libgtk-3-dev libxtst-dev libssl-dev librtmp-dev cmake make pkg-config p7zip-full sudo \ && useradd -m -s /bin/bash $USERNAME \ && echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME \ && chmod 0440 /etc/sudoers.d/$USERNAME \ && git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git /depot_tools \ && mkdir /webrtc \ && cd /webrtc \ && fetch --no-history --nohooks webrtc \ && sed -i -e "s|'src/resources'],|'src/resources'],'condition':'rtc_include_tests==true',|" src/DEPS \ && gclient sync \ && cd /webrtc-streamer \ && cmake . && make \ && cpack \ && mkdir /app && tar xvzf webrtc-streamer*.tar.gz --strip=1 -C /app/ && rm webrtc-streamer*.tar.gz \ && rm -rf /webrtc/src/out \ && apt-get clean && rm -rf /var/lib/apt/lists/ # run FROM ubuntu:24.04 WORKDIR /app COPY --from=builder /app/ /app/ RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends libssl-dev libasound2-dev libgtk-3-0 libxtst6 libpulse0 librtmp1 avahi-utils \ && useradd -m user -G video,audio \ && apt-get clean && rm -rf /var/lib/apt/lists/ \ && ./webrtc-streamer -V USER user ENTRYPOINT [ "./webrtc-streamer" ] CMD [ "-C", "config.json" ]
2301_81045437/webrtc-streamer
Dockerfile
Dockerfile
unlicense
1,606
# # configure application to run on Heroku # web: ./webrtc-streamer -a -C config.json -N10 -o
2301_81045437/webrtc-streamer
Procfile
Procfile
unlicense
94
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** CapturerFactory.h ** ** -------------------------------------------------------------------------*/ #pragma once #include <regex> #include "VcmCapturer.h" #ifdef HAVE_V4L2 #include "V4l2Capturer.h" #include "dirent.h" #endif #ifdef HAVE_LIVE555 #include "rtspvideocapturer.h" #include "rtpvideocapturer.h" #include "filevideocapturer.h" #include "rtspaudiocapturer.h" #include "fileaudiocapturer.h" #endif #ifdef USE_X11 #include "screencapturer.h" #include "windowcapturer.h" #endif #ifdef HAVE_RTMP #include "rtmpvideosource.h" #endif #include "pc/video_track_source.h" template<class T> class TrackSource : public webrtc::VideoTrackSource { public: static rtc::scoped_refptr<TrackSource> Create(const std::string & videourl, const std::map<std::string, std::string> & opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory) { std::unique_ptr<T> capturer = absl::WrapUnique(T::Create(videourl, opts, videoDecoderFactory)); if (!capturer) { return nullptr; } return rtc::make_ref_counted<TrackSource>(std::move(capturer)); } virtual bool GetStats(Stats* stats) override { bool result = false; T* source = m_capturer.get(); if (source) { stats->input_height = source->height(); stats->input_width = source->width(); result = true; } return result; } protected: explicit TrackSource(std::unique_ptr<T> capturer) : webrtc::VideoTrackSource(/*remote=*/false), m_capturer(std::move(capturer)) {} SourceState state() const override { return kLive; } private: rtc::VideoSourceInterface<webrtc::VideoFrame>* source() override { return m_capturer.get(); } std::unique_ptr<T> m_capturer; }; class CapturerFactory { public: static const std::list<std::string> GetVideoCaptureDeviceList(const std::regex & publishFilter, bool useNullCodec) { std::list<std::string> videoDeviceList; if (std::regex_match("videocap://",publishFilter) && !useNullCodec) { std::unique_ptr<webrtc::VideoCaptureModule::DeviceInfo> info(webrtc::VideoCaptureFactory::CreateDeviceInfo()); if (info) { int num_videoDevices = info->NumberOfDevices(); RTC_LOG(LS_INFO) << "nb video devices:" << num_videoDevices; for (int i = 0; i < num_videoDevices; ++i) { const uint32_t kSize = 256; char name[kSize] = {0}; char id[kSize] = {0}; if (info->GetDeviceName(i, name, kSize, id, kSize) != -1) { RTC_LOG(LS_INFO) << "video device name:" << name << " id:" << id; std::string devname; devname = "videocap://"; devname += std::to_string(i); videoDeviceList.push_back(devname); } } } } if (std::regex_match("v4l2://",publishFilter) && useNullCodec) { #ifdef HAVE_V4L2 DIR *dir = opendir("/dev"); if (dir != nullptr) { struct dirent* entry = NULL; while ((entry = readdir(dir)) != NULL) { if (strncmp(entry->d_name, "video", 5) == 0) { std::string device("/dev/"); device.append(entry->d_name); V4L2DeviceParameters param(device.c_str(), V4L2_PIX_FMT_H264, 0, 0, 0); V4l2Capture* capture = V4l2Capture::create(param); if (capture != NULL) { delete capture; std::string v4l2url("v4l2://"); v4l2url.append(device); videoDeviceList.push_back(v4l2url); } } } closedir(dir); } #endif } return videoDeviceList; } static const std::list<std::string> GetVideoSourceList(const std::regex & publishFilter, bool useNullCodec) { std::list<std::string> videoList; #ifdef USE_X11 if (std::regex_match("window://",publishFilter) && !useNullCodec) { std::unique_ptr<webrtc::DesktopCapturer> capturer = webrtc::DesktopCapturer::CreateWindowCapturer(webrtc::DesktopCaptureOptions::CreateDefault()); if (capturer) { webrtc::DesktopCapturer::SourceList sourceList; if (capturer->GetSourceList(&sourceList)) { for (auto source : sourceList) { std::ostringstream os; os << "window://" << source.title; videoList.push_back(os.str()); } } } } if (std::regex_match("screen://",publishFilter) && !useNullCodec) { std::unique_ptr<webrtc::DesktopCapturer> capturer = webrtc::DesktopCapturer::CreateScreenCapturer(webrtc::DesktopCaptureOptions::CreateDefault()); if (capturer) { webrtc::DesktopCapturer::SourceList sourceList; if (capturer->GetSourceList(&sourceList)) { for (auto source : sourceList) { std::ostringstream os; os << "screen://" << source.id; videoList.push_back(os.str()); } } } } #endif return videoList; } static rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> CreateVideoSource(const std::string & videourl, const std::map<std::string,std::string> & opts, const std::regex & publishFilter, rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> peer_connection_factory, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory) { rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> videoSource; if ( ((videourl.find("rtsp://") == 0) || (videourl.find("rtsps://") == 0) ) && (std::regex_match("rtsp://", publishFilter))) { #ifdef HAVE_LIVE555 videoSource = TrackSource<RTSPVideoCapturer>::Create(videourl,opts, videoDecoderFactory); #endif } else if ((videourl.find("file://") == 0) && (std::regex_match("file://", publishFilter))) { #ifdef HAVE_LIVE555 videoSource = TrackSource<FileVideoCapturer>::Create(videourl, opts, videoDecoderFactory); #endif } else if ((videourl.find("rtp://") == 0) && (std::regex_match("rtp://", publishFilter))) { #ifdef HAVE_LIVE555 videoSource = TrackSource<RTPVideoCapturer>::Create(SDPClient::getSdpFromRtpUrl(videourl), opts, videoDecoderFactory); #endif } else if ((videourl.find("screen://") == 0) && (std::regex_match("screen://", publishFilter))) { #ifdef USE_X11 videoSource = TrackSource<ScreenCapturer>::Create(videourl, opts, videoDecoderFactory); #endif } else if ((videourl.find("window://") == 0) && (std::regex_match("window://", publishFilter))) { #ifdef USE_X11 videoSource = TrackSource<WindowCapturer>::Create(videourl, opts, videoDecoderFactory); #endif } else if ((videourl.find("rtmp://") == 0) && (std::regex_match("rtmp://",publishFilter))) { #ifdef HAVE_RTMP videoSource = TrackSource<RtmpVideoSource>::Create(videourl, opts, videoDecoderFactory); #endif } else if ((videourl.find("v4l2://") == 0) && (std::regex_match("v4l2://",publishFilter))) { #ifdef HAVE_V4L2 videoSource = TrackSource<V4l2Capturer>::Create(videourl, opts, videoDecoderFactory); #endif } else if (std::regex_match("videocap://",publishFilter)) { videoSource = TrackSource<VcmCapturer>::Create(videourl, opts, videoDecoderFactory); } return videoSource; } static const std::list<std::string> GetAudioCaptureDeviceList(const std::regex & publishFilter, rtc::scoped_refptr<webrtc::AudioDeviceModule> audioDeviceModule) { std::list<std::string> audioList; if (std::regex_match("audiocap://", publishFilter)) { int16_t num_audioDevices = audioDeviceModule->RecordingDevices(); RTC_LOG(LS_INFO) << "nb audio devices:" << num_audioDevices; for (int i = 0; i < num_audioDevices; ++i) { char name[webrtc::kAdmMaxDeviceNameSize] = {0}; char id[webrtc::kAdmMaxGuidSize] = {0}; if (audioDeviceModule->RecordingDeviceName(i, name, id) != -1) { RTC_LOG(LS_INFO) << "audio device name:" << name << " id:" << id; std::string devname; devname = "audiocap://"; devname += std::to_string(i); audioList.push_back(devname); } } } return audioList; } static const std::list<std::string> GetAudioPlayoutDeviceList(const std::regex & publishFilter, rtc::scoped_refptr<webrtc::AudioDeviceModule> audioDeviceModule) { std::list<std::string> audioList; if (std::regex_match("audioplay://", publishFilter)) { int16_t num_audioDevices = audioDeviceModule->PlayoutDevices(); RTC_LOG(LS_INFO) << "nb audio devices:" << num_audioDevices; for (int i = 0; i < num_audioDevices; ++i) { char name[webrtc::kAdmMaxDeviceNameSize] = {0}; char id[webrtc::kAdmMaxGuidSize] = {0}; if (audioDeviceModule->PlayoutDeviceName(i, name, id) != -1) { RTC_LOG(LS_INFO) << "audio device name:" << name << " id:" << id; std::string devname; devname = "audioplay://"; devname += std::to_string(i); audioList.push_back(devname); } } } return audioList; } static rtc::scoped_refptr<webrtc::AudioSourceInterface> CreateAudioSource(const std::string & audiourl, const std::map<std::string,std::string> & opts, const std::regex & publishFilter, rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> peer_connection_factory, rtc::scoped_refptr<webrtc::AudioDecoderFactory> audioDecoderfactory, rtc::scoped_refptr<webrtc::AudioDeviceModule> audioDeviceModule) { rtc::scoped_refptr<webrtc::AudioSourceInterface> audioSource; if ( (audiourl.find("rtsp://") == 0) && (std::regex_match("rtsp://",publishFilter)) ) { #ifdef HAVE_LIVE555 audioDeviceModule->Terminate(); audioSource = RTSPAudioSource::Create(audioDecoderfactory, audiourl, opts); #endif } else if ( (audiourl.find("file://") == 0) && (std::regex_match("file://",publishFilter)) ) { #ifdef HAVE_LIVE555 audioDeviceModule->Terminate(); audioSource = FileAudioSource::Create(audioDecoderfactory, audiourl, opts); #endif } else if (std::regex_match("audiocap://",publishFilter)) { audioDeviceModule->Init(); int16_t num_audioDevices = audioDeviceModule->RecordingDevices(); int16_t idx_audioDevice = -1; char name[webrtc::kAdmMaxDeviceNameSize] = {0}; char id[webrtc::kAdmMaxGuidSize] = {0}; if (audiourl.find("audiocap://") == 0) { int deviceNumber = atoi(audiourl.substr(strlen("audiocap://")).c_str()); RTC_LOG(LS_INFO) << "audiourl:" << audiourl << " device number:" << deviceNumber; if (audioDeviceModule->RecordingDeviceName(deviceNumber, name, id) != -1) { idx_audioDevice = deviceNumber; } } RTC_LOG(LS_ERROR) << "audiourl:" << audiourl << " idx_audioDevice:" << idx_audioDevice << "/" << num_audioDevices; if ( (idx_audioDevice >= 0) && (idx_audioDevice < num_audioDevices) ) { audioDeviceModule->SetRecordingDevice(idx_audioDevice); cricket::AudioOptions opt; audioSource = peer_connection_factory->CreateAudioSource(opt); } } return audioSource; } };
2301_81045437/webrtc-streamer
inc/CapturerFactory.h
C++
unlicense
10,744
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** EncodedVideoFrameBuffer.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "rtc_base/ref_counted_object.h" #include "absl/strings/match.h" #include "api/video/i420_buffer.h" class EncodedVideoFrameBuffer : public webrtc::VideoFrameBuffer { public: EncodedVideoFrameBuffer(int width, int height, const rtc::scoped_refptr<webrtc::EncodedImageBufferInterface> &encoded_data, webrtc::VideoFrameType frameType) : m_width(width), m_height(height), m_encoded_data(encoded_data), m_frameType(frameType) {} virtual Type type() const { return webrtc::VideoFrameBuffer::Type::kNative; } virtual rtc::scoped_refptr<webrtc::I420BufferInterface> ToI420() { return nullptr; } virtual int width() const { return m_width; } virtual int height() const { return m_height; } webrtc::EncodedImage getEncodedImage(uint32_t rtptime, int ntptime ) const { webrtc::EncodedImage encoded_image; encoded_image.SetEncodedData(webrtc::EncodedImageBuffer::Create(m_encoded_data->data(), m_encoded_data->size())); encoded_image._frameType = m_frameType; encoded_image.SetAtTargetQuality(true); encoded_image.SetRtpTimestamp(rtptime); encoded_image.ntp_time_ms_ = ntptime; return encoded_image; } private: const int m_width; const int m_height; rtc::scoped_refptr<webrtc::EncodedImageBufferInterface> m_encoded_data; webrtc::VideoFrameType m_frameType; };
2301_81045437/webrtc-streamer
inc/EncodedVideoFrameBuffer.h
C++
unlicense
1,689
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** HttpServerRequestHandler.h ** ** -------------------------------------------------------------------------*/ #pragma once #include <list> #include <map> #include <functional> #include "prometheus/registry.h" #include "json/json.h" #include "CivetServer.h" /* --------------------------------------------------------------------------- ** http callback ** -------------------------------------------------------------------------*/ class HttpServerRequestHandler : public CivetServer { public: typedef std::tuple<int, std::map<std::string,std::string>,Json::Value> httpFunctionReturn; typedef std::function<httpFunctionReturn(const struct mg_request_info *req_info, const Json::Value &)> httpFunction; HttpServerRequestHandler(std::map<std::string,httpFunction>& func, const std::vector<std::string>& options); virtual ~HttpServerRequestHandler(); private: prometheus::Registry m_registry; std::vector<CivetHandler*> m_handlers; };
2301_81045437/webrtc-streamer
inc/HttpServerRequestHandler.h
C++
unlicense
1,223
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** NullDecoder.h ** ** -------------------------------------------------------------------------*/ #include "api/video_codecs/builtin_video_decoder_factory.h" #include "EncodedVideoFrameBuffer.h" #pragma once class NullDecoder : public webrtc::VideoDecoder { public: NullDecoder(const webrtc::SdpVideoFormat& format) : m_format(format) {} virtual ~NullDecoder() override {} bool Configure(const webrtc::VideoDecoder::Settings& settings) override { m_settings = settings; return true; } int32_t Release() override { return WEBRTC_VIDEO_CODEC_OK; } int32_t RegisterDecodeCompleteCallback(webrtc::DecodedImageCallback* callback) override { m_decoded_image_callback = callback; return WEBRTC_VIDEO_CODEC_OK; } int32_t Decode(const webrtc::EncodedImage& input_image, bool /*missing_frames*/, int64_t render_time_ms = -1) override { if (!m_decoded_image_callback) { RTC_LOG(LS_WARNING) << "RegisterDecodeCompleteCallback() not called"; return WEBRTC_VIDEO_CODEC_UNINITIALIZED; } rtc::scoped_refptr<webrtc::EncodedImageBufferInterface> encodedData = input_image.GetEncodedData(); rtc::scoped_refptr<webrtc::VideoFrameBuffer> frameBuffer = rtc::make_ref_counted<EncodedVideoFrameBuffer>(m_settings.max_render_resolution().Width(), m_settings.max_render_resolution().Height(), encodedData, input_image.FrameType()); webrtc::VideoFrame frame = webrtc::VideoFrame::Builder() .set_video_frame_buffer(frameBuffer) .set_rotation(webrtc::kVideoRotation_0) .set_timestamp_rtp(input_image.RtpTimestamp()) .set_timestamp_ms(render_time_ms) .set_ntp_time_ms(input_image.NtpTimeMs()) .build(); RTC_LOG(LS_VERBOSE) << "Decode " << frame.id() << " " << input_image._frameType << " " << frameBuffer->width() << "x" << frameBuffer->height() << " " << frameBuffer->GetI420()->StrideY(); m_decoded_image_callback->Decoded(frame); return WEBRTC_VIDEO_CODEC_OK; } const char* ImplementationName() const override { return "NullDecoder"; } webrtc::DecodedImageCallback* m_decoded_image_callback; webrtc::VideoDecoder::Settings m_settings; webrtc::SdpVideoFormat m_format; };
2301_81045437/webrtc-streamer
inc/NullDecoder.h
C++
unlicense
2,422
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** NullEncoder.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "api/video_codecs/builtin_video_encoder_factory.h" #include "modules/video_coding/codecs/h264/include/h264.h" #include "common_video/h264/h264_common.h" #include "modules/video_coding/include/video_codec_interface.h" #include "EncodedVideoFrameBuffer.h" class NullEncoder : public webrtc::VideoEncoder { public: NullEncoder(const webrtc::SdpVideoFormat& format) : m_format(format) {} virtual ~NullEncoder() override {} int32_t InitEncode(const webrtc::VideoCodec* codec_settings, const webrtc::VideoEncoder::Settings& settings) override { RTC_LOG(LS_WARNING) << "InitEncode"; return WEBRTC_VIDEO_CODEC_OK; } int32_t Release() override { return WEBRTC_VIDEO_CODEC_OK; } int32_t RegisterEncodeCompleteCallback(webrtc::EncodedImageCallback* callback) override { m_encoded_image_callback = callback; return WEBRTC_VIDEO_CODEC_OK; } void SetRates(const RateControlParameters& parameters) override { RTC_LOG(LS_VERBOSE) << "SetRates() " << parameters.target_bitrate.ToString() << " " << parameters.bitrate.ToString() << " " << parameters.bandwidth_allocation.kbps() << " " << parameters.framerate_fps; } int32_t Encode(const webrtc::VideoFrame& frame, const std::vector<webrtc::VideoFrameType>* frame_types) override { if (!m_encoded_image_callback) { RTC_LOG(LS_WARNING) << "RegisterEncodeCompleteCallback() not called"; return WEBRTC_VIDEO_CODEC_UNINITIALIZED; } rtc::scoped_refptr<webrtc::VideoFrameBuffer> buffer = frame.video_frame_buffer(); if (buffer->type() != webrtc::VideoFrameBuffer::Type::kNative) { RTC_LOG(LS_WARNING) << "buffer type must be kNative"; return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; } // get webrtc::EncodedImage EncodedVideoFrameBuffer* encodedBuffer = (EncodedVideoFrameBuffer*)buffer.get(); webrtc::EncodedImage encoded_image = encodedBuffer->getEncodedImage(frame.timestamp(), frame.ntp_time_ms()); RTC_LOG(LS_VERBOSE) << "EncodedImage " << frame.id() << " " << encoded_image.FrameType() << " " << buffer->width() << "x" << buffer->height(); // forward to callback webrtc::CodecSpecificInfo codec_specific; if (m_format.name == "H264") { codec_specific.codecType = webrtc::VideoCodecType::kVideoCodecH264; } else if (m_format.name == "H265") { codec_specific.codecType = webrtc::VideoCodecType::kVideoCodecH265; } webrtc::EncodedImageCallback::Result result = m_encoded_image_callback->OnEncodedImage(encoded_image, &codec_specific); if (result.error == webrtc::EncodedImageCallback::Result::ERROR_SEND_FAILED) { RTC_LOG(LS_ERROR) << "Error in parsing EncodedImage " << frame.id() << " " << encoded_image._frameType << " " << buffer->width() << "x" << buffer->height(); } return WEBRTC_VIDEO_CODEC_OK; } webrtc::VideoEncoder::EncoderInfo GetEncoderInfo() const override { webrtc::VideoEncoder::EncoderInfo info; info.supports_native_handle = true; info.has_trusted_rate_controller = true; info.implementation_name = "NullEncoder"; return info; } private: webrtc::EncodedImageCallback* m_encoded_image_callback; webrtc::SdpVideoFormat m_format; };
2301_81045437/webrtc-streamer
inc/NullEncoder.h
C++
unlicense
3,522
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** PeerConnectionManager.h ** ** -------------------------------------------------------------------------*/ #pragma once #include <string> #include <mutex> #include <regex> #include <thread> #include <future> #include "api/peer_connection_interface.h" #include "api/video_codecs/video_decoder_factory.h" #include "p2p/client/basic_port_allocator.h" #include "modules/audio_device/include/audio_device.h" #include "rtc_base/logging.h" #include "rtc_base/strings/json.h" #include "HttpServerRequestHandler.h" class PeerConnectionManager { class VideoSink : public rtc::VideoSinkInterface<webrtc::VideoFrame> { public: VideoSink(const rtc::scoped_refptr<webrtc::VideoTrackInterface> & track): m_track(track) { RTC_LOG(LS_INFO) << __PRETTY_FUNCTION__ << " videotrack:" << m_track->id(); m_track->AddOrUpdateSink(this, rtc::VideoSinkWants()); } virtual ~VideoSink() { RTC_LOG(LS_INFO) << __PRETTY_FUNCTION__ << " videotrack:" << m_track->id(); m_track->RemoveSink(this); } // VideoSinkInterface implementation virtual void OnFrame(const webrtc::VideoFrame& video_frame) { rtc::scoped_refptr<webrtc::I420BufferInterface> buffer(video_frame.video_frame_buffer()->ToI420()); RTC_LOG(LS_VERBOSE) << __PRETTY_FUNCTION__ << " frame:" << buffer->width() << "x" << buffer->height(); } protected: rtc::scoped_refptr<webrtc::VideoTrackInterface> m_track; }; class AudioSink : public webrtc::AudioTrackSinkInterface { public: AudioSink(const rtc::scoped_refptr<webrtc::AudioTrackInterface> & track): m_track(track) { RTC_LOG(LS_INFO) << __PRETTY_FUNCTION__ << " audiotrack:" << m_track->id(); m_track->AddSink(this); } virtual ~AudioSink() { RTC_LOG(LS_INFO) << __PRETTY_FUNCTION__ << " audiotrack:" << m_track->id(); m_track->RemoveSink(this); } virtual void OnData(const void* audio_data, int bits_per_sample, int sample_rate, size_t number_of_channels, size_t number_of_frames) { RTC_LOG(LS_VERBOSE) << __PRETTY_FUNCTION__ << "size:" << bits_per_sample << " format:" << sample_rate << "/" << number_of_channels << "/" << number_of_frames; } protected: rtc::scoped_refptr<webrtc::AudioTrackInterface> m_track; }; class SetSessionDescriptionObserver : public webrtc::SetSessionDescriptionObserver { public: static SetSessionDescriptionObserver* Create(const rtc::scoped_refptr<webrtc::PeerConnectionInterface> & pc, std::promise<const webrtc::SessionDescriptionInterface*> & promise) { return new rtc::RefCountedObject<SetSessionDescriptionObserver>(pc, promise); } virtual void OnSuccess() { std::string sdp; if (!m_cancelled) { if (m_pc->local_description()) { m_promise.set_value(m_pc->local_description()); m_pc->local_description()->ToString(&sdp); RTC_LOG(LS_INFO) << __PRETTY_FUNCTION__ << " Local SDP:" << sdp; } else if (m_pc->remote_description()) { m_promise.set_value(m_pc->remote_description()); m_pc->remote_description()->ToString(&sdp); RTC_LOG(LS_INFO) << __PRETTY_FUNCTION__ << " Remote SDP:" << sdp; } } } virtual void OnFailure(webrtc::RTCError error) { RTC_LOG(LS_ERROR) << __PRETTY_FUNCTION__ << " " << error.message(); if (!m_cancelled) { m_promise.set_value(NULL); } } void cancel() { m_cancelled = true; } protected: SetSessionDescriptionObserver(const rtc::scoped_refptr<webrtc::PeerConnectionInterface> & pc, std::promise<const webrtc::SessionDescriptionInterface*> & promise) : m_pc(pc), m_promise(promise), m_cancelled(false) {}; private: rtc::scoped_refptr<webrtc::PeerConnectionInterface> m_pc; std::promise<const webrtc::SessionDescriptionInterface*> & m_promise; bool m_cancelled; }; class CreateSessionDescriptionObserver : public webrtc::CreateSessionDescriptionObserver { public: static CreateSessionDescriptionObserver* Create(const rtc::scoped_refptr<webrtc::PeerConnectionInterface> & pc, std::promise<const webrtc::SessionDescriptionInterface*> & promise) { return new rtc::RefCountedObject<CreateSessionDescriptionObserver>(pc,promise); } virtual void OnSuccess(webrtc::SessionDescriptionInterface* desc) { std::string sdp; desc->ToString(&sdp); RTC_LOG(LS_INFO) << __PRETTY_FUNCTION__ << " type:" << desc->type() << " sdp:" << sdp; if (!m_cancelled) { m_pc->SetLocalDescription(SetSessionDescriptionObserver::Create(m_pc, m_promise), desc); } } virtual void OnFailure(webrtc::RTCError error) { RTC_LOG(LS_ERROR) << __PRETTY_FUNCTION__ << " " << error.message(); if (!m_cancelled) { m_promise.set_value(NULL); } } void cancel() { m_cancelled = true; } protected: CreateSessionDescriptionObserver(const rtc::scoped_refptr<webrtc::PeerConnectionInterface> & pc, std::promise<const webrtc::SessionDescriptionInterface*> & promise) : m_pc(pc), m_promise(promise), m_cancelled(false) {}; private: rtc::scoped_refptr<webrtc::PeerConnectionInterface> m_pc; std::promise<const webrtc::SessionDescriptionInterface*> & m_promise; bool m_cancelled; }; class PeerConnectionStatsCollectorCallback : public webrtc::RTCStatsCollectorCallback { public: PeerConnectionStatsCollectorCallback() {} void clearReport() { m_report.clear(); } Json::Value getReport() { return m_report; } protected: virtual void OnStatsDelivered(const rtc::scoped_refptr<const webrtc::RTCStatsReport>& report) { for (const webrtc::RTCStats& stats : *report) { Json::Value statsMembers; for (auto & attribute : stats.Attributes()) { statsMembers[attribute.name()] = attribute.ToString(); } m_report[stats.id()] = statsMembers; } } Json::Value m_report; }; class DataChannelObserver : public webrtc::DataChannelObserver { public: DataChannelObserver(rtc::scoped_refptr<webrtc::DataChannelInterface> dataChannel): m_dataChannel(dataChannel) { m_dataChannel->RegisterObserver(this); } virtual ~DataChannelObserver() { m_dataChannel->UnregisterObserver(); } // DataChannelObserver interface virtual void OnStateChange() { RTC_LOG(LS_ERROR) << __PRETTY_FUNCTION__ << " channel:" << m_dataChannel->label() << " state:"<< webrtc::DataChannelInterface::DataStateString(m_dataChannel->state()); std::string msg(m_dataChannel->label() + " " + webrtc::DataChannelInterface::DataStateString(m_dataChannel->state())); webrtc::DataBuffer buffer(msg); m_dataChannel->Send(buffer); } virtual void OnMessage(const webrtc::DataBuffer& buffer) { std::string msg((const char*)buffer.data.data(),buffer.data.size()); RTC_LOG(LS_ERROR) << __PRETTY_FUNCTION__ << " channel:" << m_dataChannel->label() << " msg:" << msg; } protected: rtc::scoped_refptr<webrtc::DataChannelInterface> m_dataChannel; }; class PeerConnectionObserver : public webrtc::PeerConnectionObserver { public: PeerConnectionObserver(PeerConnectionManager* peerConnectionManager, const std::string& peerid, const webrtc::PeerConnectionInterface::RTCConfiguration & config) : m_peerConnectionManager(peerConnectionManager) , m_peerid(peerid) , m_iceCandidateList(Json::arrayValue) , m_deleting(false) , m_creationTime(rtc::TimeMicros()) { RTC_LOG(LS_INFO) << __FUNCTION__ << "CreatePeerConnection peerid:" << peerid; webrtc::PeerConnectionDependencies dependencies(this); webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::PeerConnectionInterface>> result = m_peerConnectionManager->m_peer_connection_factory->CreatePeerConnectionOrError(config, std::move(dependencies)); if (result.ok()) { m_pc = result.MoveValue(); webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::DataChannelInterface>> errorOrChannel = m_pc->CreateDataChannelOrError("ServerDataChannel", NULL); if (errorOrChannel.ok()) { m_localChannel.reset(new DataChannelObserver(errorOrChannel.MoveValue())); } else { RTC_LOG(LS_ERROR) << __FUNCTION__ << "CreateDataChannel peerid:" << peerid << " error:" << errorOrChannel.error().message(); } } else { RTC_LOG(LS_ERROR) << __FUNCTION__ << "CreatePeerConnection peerid:" << peerid << " error:" << result.error().message(); } m_statsCallback = new rtc::RefCountedObject<PeerConnectionStatsCollectorCallback>(); RTC_LOG(LS_INFO) << __FUNCTION__ << "CreatePeerConnection peerid:" << peerid; }; virtual ~PeerConnectionObserver() { RTC_LOG(LS_INFO) << __PRETTY_FUNCTION__; if (m_pc.get()) { // warning: pc->close call OnIceConnectionChange m_deleting = true; m_pc->Close(); } } Json::Value getIceCandidateList() { return m_iceCandidateList; } Json::Value getStats() { m_statsCallback->clearReport(); m_pc->GetStats(m_statsCallback.get()); int count=10; while ( (m_statsCallback->getReport().empty()) && (--count > 0) ) { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } return Json::Value(m_statsCallback->getReport()); }; rtc::scoped_refptr<webrtc::PeerConnectionInterface> getPeerConnection() { return m_pc; }; // PeerConnectionObserver interface virtual void OnAddStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) { RTC_LOG(LS_ERROR) << __PRETTY_FUNCTION__ << " nb video tracks:" << stream->GetVideoTracks().size(); webrtc::VideoTrackVector videoTracks = stream->GetVideoTracks(); if (videoTracks.size()>0) { m_videosink.reset(new VideoSink(videoTracks.at(0))); } RTC_LOG(LS_ERROR) << __PRETTY_FUNCTION__ << " nb audio tracks:" << stream->GetAudioTracks().size(); webrtc::AudioTrackVector audioTracks = stream->GetAudioTracks(); if (audioTracks.size()>0) { m_audiosink.reset(new AudioSink(audioTracks.at(0))); } } virtual void OnRemoveStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) { RTC_LOG(LS_ERROR) << __PRETTY_FUNCTION__; m_videosink.reset(); m_audiosink.reset(); } virtual void OnDataChannel(rtc::scoped_refptr<webrtc::DataChannelInterface> channel) { RTC_LOG(LS_ERROR) << __PRETTY_FUNCTION__; m_remoteChannel.reset(new DataChannelObserver(channel)); } virtual void OnRenegotiationNeeded() { RTC_LOG(LS_ERROR) << __PRETTY_FUNCTION__ << " peerid:" << m_peerid;; } virtual void OnIceCandidate(const webrtc::IceCandidateInterface* candidate); virtual void OnSignalingChange(webrtc::PeerConnectionInterface::SignalingState state) { RTC_LOG(LS_WARNING) << __PRETTY_FUNCTION__ << " state:" << webrtc::PeerConnectionInterface::AsString(state) << " peerid:" << m_peerid; } virtual void OnIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState state) { RTC_LOG(LS_WARNING) << __PRETTY_FUNCTION__ << " state:" << webrtc::PeerConnectionInterface::AsString(state) << " peerid:" << m_peerid; if ( (state == webrtc::PeerConnectionInterface::kIceConnectionFailed) ||(state == webrtc::PeerConnectionInterface::kIceConnectionClosed) ) { m_iceCandidateList.clear(); if (!m_deleting) { std::thread([this]() { m_peerConnectionManager->hangUp(m_peerid); }).detach(); } } } virtual void OnIceGatheringChange(webrtc::PeerConnectionInterface::IceGatheringState state) { RTC_LOG(LS_WARNING) << __PRETTY_FUNCTION__ << " state:" << webrtc::PeerConnectionInterface::AsString(state) << " peerid:" << m_peerid; m_gatheringState = state; } uint64_t getCreationTime() { return m_creationTime; } std::string getPeerId() { return m_peerid; } webrtc::PeerConnectionInterface::IceGatheringState getGatheringState() { return m_gatheringState; } private: PeerConnectionManager* m_peerConnectionManager; const std::string m_peerid; rtc::scoped_refptr<webrtc::PeerConnectionInterface> m_pc; std::unique_ptr<DataChannelObserver> m_localChannel; std::unique_ptr<DataChannelObserver> m_remoteChannel; Json::Value m_iceCandidateList; rtc::scoped_refptr<PeerConnectionStatsCollectorCallback> m_statsCallback; std::unique_ptr<VideoSink> m_videosink; std::unique_ptr<AudioSink> m_audiosink; bool m_deleting; uint64_t m_creationTime; webrtc::PeerConnectionInterface::IceGatheringState m_gatheringState; }; public: PeerConnectionManager(const std::list<std::string> & iceServerList, const Json::Value & config, webrtc::AudioDeviceModule::AudioLayer audioLayer, const std::string& publishFilter, const std::string& webrtcUdpPortRange, bool useNullCodec, bool usePlanB, int maxpc, webrtc::PeerConnectionInterface::IceTransportsType transportType, const std::string & basePath); virtual ~PeerConnectionManager(); bool InitializePeerConnection(); const std::map<std::string,HttpServerRequestHandler::httpFunction> getHttpApi() { return m_func; }; const Json::Value getIceCandidateList(const std::string &peerid); const Json::Value addIceCandidate(const std::string &peerid, const Json::Value& jmessage); const Json::Value getVideoDeviceList(); const Json::Value getAudioDeviceList(); const Json::Value getAudioPlayoutList(); const Json::Value getMediaList(); const Json::Value hangUp(const std::string &peerid); const Json::Value call(const std::string &peerid, const std::string & videourl, const std::string & audiourl, const std::string & options, const Json::Value& jmessage); const Json::Value getIceServers(const std::string& clientIp); const Json::Value getPeerConnectionList(); const Json::Value getStreamList(); const Json::Value createOffer(const std::string &peerid, const std::string & videourl, const std::string & audiourl, const std::string & options); const Json::Value setAnswer(const std::string &peerid, const Json::Value& jmessage); std::tuple<int,std::map<std::string,std::string>,Json::Value> whep( const std::string &method, const std::string &url, const std::string &peerid, const std::string & videourl, const std::string & audiourl, const std::string & options, const Json::Value &in); protected: PeerConnectionObserver* CreatePeerConnection(const std::string& peerid); bool AddStreams(webrtc::PeerConnectionInterface* peer_connection, const std::string & videourl, const std::string & audiourl, const std::string & options); rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> CreateVideoSource(const std::string & videourl, const std::map<std::string,std::string> & opts); rtc::scoped_refptr<webrtc::AudioSourceInterface> CreateAudioSource(const std::string & audiourl, const std::map<std::string,std::string> & opts); bool streamStillUsed(const std::string & streamLabel); const std::list<std::string> getVideoCaptureDeviceList(); rtc::scoped_refptr<webrtc::PeerConnectionInterface> getPeerConnection(const std::string& peerid); const std::string sanitizeLabel(const std::string &label); void createAudioModule(webrtc::AudioDeviceModule::AudioLayer audioLayer); std::unique_ptr<webrtc::SessionDescriptionInterface> getAnswer(const std::string & peerid, const std::string & sdpoffer, const std::string & videourl, const std::string & audiourl, const std::string & options, bool waitgatheringcompletion = false); std::unique_ptr<webrtc::SessionDescriptionInterface> getAnswer(const std::string & peerid, webrtc::SessionDescriptionInterface *session_description, const std::string & videourl, const std::string & audiourl, const std::string & options, bool waitgatheringcompletion = false); std::string getOldestPeerCannection(); protected: std::unique_ptr<rtc::Thread> m_signalingThread; std::unique_ptr<rtc::Thread> m_workerThread; std::unique_ptr<rtc::Thread> m_networkThread; typedef std::pair< rtc::scoped_refptr<webrtc::VideoTrackSourceInterface>, rtc::scoped_refptr<webrtc::AudioSourceInterface>> AudioVideoPair; rtc::scoped_refptr<webrtc::AudioDecoderFactory> m_audioDecoderfactory; std::unique_ptr<webrtc::TaskQueueFactory> m_task_queue_factory; rtc::scoped_refptr<webrtc::AudioDeviceModule> m_audioDeviceModule; std::unique_ptr<webrtc::VideoDecoderFactory> m_video_decoder_factory; rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> m_peer_connection_factory; std::mutex m_peerMapMutex; std::map<std::string, PeerConnectionObserver* > m_peer_connectionobs_map; std::map<std::string, AudioVideoPair> m_stream_map; std::mutex m_streamMapMutex; std::list<std::string> m_iceServerList; const Json::Value m_config; std::map<std::string,std::string> m_videoaudiomap; const std::regex m_publishFilter; std::map<std::string,HttpServerRequestHandler::httpFunction> m_func; std::string m_webrtcPortRange; bool m_useNullCodec; bool m_usePlanB; int m_maxpc; webrtc::PeerConnectionInterface::IceTransportsType m_transportType; };
2301_81045437/webrtc-streamer
inc/PeerConnectionManager.h
C++
unlicense
18,791
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** V4l2AlsaMap.h ** ** -------------------------------------------------------------------------*/ #pragma once #ifdef HAVE_V4L2 #include <string> #include <cstring> #include <map> #include <filesystem> #include <sstream> #include <iostream> #include <linux/videodev2.h> #include <fcntl.h> #include <sys/ioctl.h> /* --------------------------------------------------------------------------- ** get "deviceid" ** -------------------------------------------------------------------------*/ std::string getDeviceId(const std::string& devicePath) { std::string deviceid; std::filesystem::path fspath(devicePath); if (std::filesystem::exists(fspath)) { std::string filename = std::filesystem::read_symlink(fspath).filename(); std::stringstream ss(filename); getline(ss, deviceid, ':'); } return deviceid; } std::map<int,int> videoDev2Idx() { std::map<int,int> dev2idx; uint32_t count = 0; char device[20]; int fd = -1; struct v4l2_capability cap; for (int devId = 0; devId < 64; devId++) { snprintf(device, sizeof(device), "/dev/video%d", devId); if ((fd = open(device, O_RDONLY)) != -1) { if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0 || !(cap.device_caps & V4L2_CAP_VIDEO_CAPTURE)) { close(fd); continue; } else { close(fd); dev2idx[devId] = count; count++; } } } return dev2idx; } std::map<std::string,std::string> getVideoDevices() { std::map<int,int> dev2Idx = videoDev2Idx(); std::map<std::string,std::string> videodevices; std::string video4linuxPath("/sys/class/video4linux"); if (std::filesystem::exists(video4linuxPath)) { for (auto const& dir_entry : std::filesystem::directory_iterator{video4linuxPath}) { std::string devname(dir_entry.path().filename()); if (devname.find("video") == 0) { std::filesystem::path devicePath(dir_entry.path()); devicePath.append("device"); std::string deviceid = getDeviceId(devicePath); if (!deviceid.empty()) { int deviceNumber = atoi(devname.substr(strlen("video")).c_str()); std::string devicename = "videocap://"; devicename += std::to_string(dev2Idx[deviceNumber]); videodevices[devicename] = deviceid; } } } } return videodevices; } std::map<std::string,std::string> getAudioDevices() { std::map<std::string,std::string> audiodevices; std::string audioLinuxPath("/sys/class/sound"); if (std::filesystem::exists(audioLinuxPath)) { for (auto const& dir_entry : std::filesystem::directory_iterator{audioLinuxPath}) { std::string devname(dir_entry.path().filename()); if (devname.find("card") == 0) { std::filesystem::path devicePath(dir_entry.path()); devicePath.append("device"); std::string deviceid = getDeviceId(devicePath); if (!deviceid.empty()) { int deviceNumber = atoi(devname.substr(strlen("card")).c_str()); std::string devicename = "audiocap://"; devicename += std::to_string(deviceNumber); audiodevices[deviceid] = devicename; } } } } return audiodevices; } std::map<std::string,std::string> getV4l2AlsaMap() { std::map<std::string,std::string> videoaudiomap; std::map<std::string,std::string> videodevices = getVideoDevices(); std::map<std::string,std::string> audiodevices = getAudioDevices(); for (auto & id : videodevices) { auto audioDevice = audiodevices.find(id.second); if (audioDevice != audiodevices.end()) { std::cout << id.first << "=>" << audioDevice->second << std::endl; videoaudiomap[id.first] = audioDevice->second; } } return videoaudiomap; } #else std::map<std::string,std::string> getV4l2AlsaMap() { return std::map<std::string,std::string>(); }; #endif
2301_81045437/webrtc-streamer
inc/V4l2AlsaMap.h
C++
unlicense
3,936
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** V4l2Capturer.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "media/base/video_broadcaster.h" #include "common_video/h264/h264_common.h" #include "common_video/h264/sps_parser.h" #include "modules/video_coding/h264_sprop_parameter_sets.h" #include "rtc_base/logging.h" #include "EncodedVideoFrameBuffer.h" #include "V4l2Capture.h" #include "VideoSource.h" class V4l2Capturer : public VideoSource { public: static V4l2Capturer *Create(const std::string &videourl, const std::map<std::string, std::string> &opts, std::unique_ptr<webrtc::VideoDecoderFactory> &videoDecoderFactory) { size_t width = 0; size_t height = 0; size_t fps = 0; if (opts.find("width") != opts.end()) { width = std::stoi(opts.at("width")); } if (opts.find("height") != opts.end()) { height = std::stoi(opts.at("height")); } if (opts.find("fps") != opts.end()) { fps = std::stoi(opts.at("fps")); } std::unique_ptr<V4l2Capturer> capturer(new V4l2Capturer()); if (!capturer->Init(width, height, fps, videourl)) { RTC_LOG(LS_WARNING) << "Failed to create V4l2Capturer(w = " << width << ", h = " << height << ", fps = " << fps << ")"; return nullptr; } return capturer.release(); } virtual ~V4l2Capturer() { Destroy(); } int width() { return m_width; } int height() { return m_height; } private: V4l2Capturer() : m_stop(false) {} bool Init(size_t width, size_t height, size_t fps, const std::string &videourl) { m_width = width; m_height = height; std::string device = "/dev/video0"; if (videourl.find("v4l2://") == 0) { device = videourl.substr(strlen("v4l2://")); } V4L2DeviceParameters param(device.c_str(), V4L2_PIX_FMT_H264, width, height, fps); m_capture.reset(V4l2Capture::create(param)); bool ret = false; if (m_capture) { m_capturethread = std::thread(&V4l2Capturer::CaptureThread, this); ret = true; } return ret; } void CaptureThread() { fd_set fdset; FD_ZERO(&fdset); timeval tv; while (!m_stop) { tv.tv_sec=1; tv.tv_usec=0; if (m_capture->isReadable(&tv) > 0) { char* buffer = new char[m_capture->getBufferSize()]; int frameSize = m_capture->read(buffer, m_capture->getBufferSize()); bool idr = false; int cfg = 0; std::vector<webrtc::H264::NaluIndex> naluIndexes = webrtc::H264::FindNaluIndices((uint8_t*)buffer, frameSize); for (webrtc::H264::NaluIndex index : naluIndexes) { webrtc::H264::NaluType nalu_type = webrtc::H264::ParseNaluType(buffer[index.payload_start_offset]); RTC_LOG(LS_VERBOSE) << __FUNCTION__ << " nalu:" << nalu_type << " payload_start_offset:" << index.payload_start_offset << " start_offset:" << index.start_offset << " size:" << index.payload_size; if (nalu_type == webrtc::H264::NaluType::kSps) { m_sps = webrtc::EncodedImageBuffer::Create((uint8_t*)&buffer[index.start_offset], index.payload_size + index.payload_start_offset - index.start_offset); cfg++; } else if (nalu_type == webrtc::H264::NaluType::kPps) { m_pps = webrtc::EncodedImageBuffer::Create((uint8_t*)&buffer[index.start_offset], index.payload_size + index.payload_start_offset - index.start_offset); cfg++; } else if (nalu_type == webrtc::H264::NaluType::kIdr) { idr = true; } } RTC_LOG(LS_VERBOSE) << __FUNCTION__ << " idr:" << idr << " cfg:" << cfg << " " << m_sps->size() << " " << m_pps->size() << " " << frameSize; rtc::scoped_refptr<webrtc::EncodedImageBufferInterface> encodedData = webrtc::EncodedImageBuffer::Create((uint8_t*)buffer, frameSize); delete [] buffer; // add last SPS/PPS if not present before an IDR if (idr && (cfg == 0) && (m_sps->size() != 0) && (m_pps->size() != 0) ) { char * newBuffer = new char[encodedData->size() + m_sps->size() + m_pps->size()]; memcpy(newBuffer, m_sps->data(), m_sps->size()); memcpy(newBuffer+m_sps->size(), m_pps->data(), m_pps->size()); memcpy(newBuffer+m_sps->size()+m_pps->size(), encodedData->data(), encodedData->size()); encodedData = webrtc::EncodedImageBuffer::Create((uint8_t*)newBuffer, encodedData->size() + m_sps->size() + m_pps->size()); delete [] newBuffer; } int64_t ts = std::chrono::high_resolution_clock::now().time_since_epoch().count()/1000/1000; webrtc::VideoFrameType frameType = idr ? webrtc::VideoFrameType::kVideoFrameKey : webrtc::VideoFrameType::kVideoFrameDelta; rtc::scoped_refptr<webrtc::VideoFrameBuffer> frameBuffer = rtc::make_ref_counted<EncodedVideoFrameBuffer>(m_capture->getWidth(), m_capture->getHeight(), encodedData, frameType); webrtc::VideoFrame frame = webrtc::VideoFrame::Builder() .set_video_frame_buffer(frameBuffer) .set_rotation(webrtc::kVideoRotation_0) .set_timestamp_ms(ts) .set_id(ts) .build(); m_broadcaster.OnFrame(frame); } } } void Destroy() { if (m_capture) { m_stop = true; m_capturethread.join(); m_capture.reset(); } } bool m_stop; std::thread m_capturethread; std::unique_ptr<V4l2Capture> m_capture; rtc::scoped_refptr<webrtc::EncodedImageBufferInterface> m_sps; rtc::scoped_refptr<webrtc::EncodedImageBufferInterface> m_pps; int m_width; int m_height; };
2301_81045437/webrtc-streamer
inc/V4l2Capturer.h
C++
unlicense
5,815
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** VcmCapturer.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "modules/video_capture/video_capture_factory.h" #include "VideoSource.h" class VcmCapturer : public rtc::VideoSinkInterface<webrtc::VideoFrame>, public VideoSource { public: static VcmCapturer* Create(const std::string & videourl, const std::map<std::string, std::string> & opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory) { std::unique_ptr<VcmCapturer> vcm_capturer(new VcmCapturer()); size_t width = 800; size_t height = 600; size_t fps = 0; if (opts.find("width") != opts.end()) { width = std::stoi(opts.at("width")); } if (opts.find("height") != opts.end()) { height = std::stoi(opts.at("height")); } if (opts.find("fps") != opts.end()) { fps = std::stoi(opts.at("fps")); } if (!vcm_capturer->Init(width, height, fps, videourl)) { RTC_LOG(LS_WARNING) << "Failed to create VcmCapturer(w = " << width << ", h = " << height << ", fps = " << fps << ")"; return nullptr; } return vcm_capturer.release(); } virtual ~VcmCapturer() { Destroy(); } int width() { return m_width; } int height() { return m_height; } void OnFrame(const webrtc::VideoFrame& frame) override { m_broadcaster.OnFrame(frame); } private: VcmCapturer() : m_vcm(nullptr) {} bool Init(size_t width, size_t height, size_t target_fps, const std::string & videourl) { std::unique_ptr<webrtc::VideoCaptureModule::DeviceInfo> device_info(webrtc::VideoCaptureFactory::CreateDeviceInfo()); m_width = width; m_height = height; std::string deviceId; int num_videoDevices = device_info->NumberOfDevices(); RTC_LOG(LS_INFO) << "nb video devices:" << num_videoDevices; const uint32_t kSize = 256; char name[kSize] = {0}; char id[kSize] = {0}; if (videourl.find("videocap://") == 0) { int deviceNumber = atoi(videourl.substr(strlen("videocap://")).c_str()); RTC_LOG(LS_WARNING) << "device number:" << deviceNumber; if (device_info->GetDeviceName(deviceNumber, name, kSize, id, kSize) == 0) { deviceId = id; } } if (deviceId.empty()) { RTC_LOG(LS_WARNING) << "device not found:" << videourl; Destroy(); return false; } m_vcm = webrtc::VideoCaptureFactory::Create(deviceId.c_str()); m_vcm->RegisterCaptureDataCallback(this); webrtc::VideoCaptureCapability capability; capability.width = static_cast<int32_t>(width); capability.height = static_cast<int32_t>(height); capability.maxFPS = static_cast<int32_t>(target_fps); capability.videoType = webrtc::VideoType::kI420; if (device_info->GetBestMatchedCapability(m_vcm->CurrentDeviceName(), capability, capability)<0) { device_info->GetCapability(m_vcm->CurrentDeviceName(), 0, capability); } if (m_vcm->StartCapture(capability) != 0) { Destroy(); return false; } RTC_CHECK(m_vcm->CaptureStarted()); return true; } void Destroy() { if (m_vcm) { m_vcm->StopCapture(); m_vcm->DeRegisterCaptureDataCallback(); m_vcm = nullptr; } } int m_width; int m_height; rtc::scoped_refptr<webrtc::VideoCaptureModule> m_vcm; };
2301_81045437/webrtc-streamer
inc/VcmCapturer.h
C++
unlicense
3,508
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** VideoDecoder.h ** ** -------------------------------------------------------------------------*/ #pragma once #include <string.h> #include <vector> #include "api/video/i420_buffer.h" #include "api/environment/environment_factory.h" #include "modules/video_coding/include/video_error_codes.h" #include "modules/video_coding/h264_sprop_parameter_sets.h" #include "rtc_base/third_party/base64/base64.h" #include "SessionSink.h" #include "VideoScaler.h" class VideoDecoder : public rtc::VideoSourceInterface<webrtc::VideoFrame>, public webrtc::DecodedImageCallback { private: class Frame { public: Frame(): m_timestamp_ms(0) {} Frame(const rtc::scoped_refptr<webrtc::EncodedImageBuffer> & content, uint64_t timestamp_ms, webrtc::VideoFrameType frameType) : m_content(content), m_timestamp_ms(timestamp_ms), m_frameType(frameType) {} Frame(const std::string & format, int width, int height) : m_format(format), m_width(width), m_height(height) {} rtc::scoped_refptr<webrtc::EncodedImageBuffer> m_content; uint64_t m_timestamp_ms; webrtc::VideoFrameType m_frameType; std::string m_format; int m_width; int m_height; }; public: VideoDecoder(const std::map<std::string,std::string> & opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory, bool wait = false) : m_scaler(opts), m_env(webrtc::CreateEnvironment()), m_factory(videoDecoderFactory), m_stop(false), m_wait(wait), m_previmagets(0), m_prevts(0) { this->Start(); } virtual ~VideoDecoder() { this->Stop(); } int width() { return m_scaler.width(); } int height() { return m_scaler.height(); } static std::vector<uint8_t> extractParameters(const std::string & buffer) { std::vector<uint8_t> binary; std::string value(buffer); size_t pos = value.find_first_of(" ;\r\n"); if (pos != std::string::npos) { value.erase(pos); } rtc::Base64::DecodeFromArray(value.data(), value.size(), rtc::Base64::DO_STRICT, &binary, nullptr); binary.insert(binary.begin(), H26X_marker, H26X_marker+sizeof(H26X_marker)); return binary; } std::vector< std::vector<uint8_t> > getInitFrames(const std::string & codec, const char* sdp) { std::vector< std::vector<uint8_t> > frames; if (codec == "H264") { const char* pattern="sprop-parameter-sets="; const char* sprop=strstr(sdp, pattern); if (sprop) { std::string sdpstr(sprop+strlen(pattern)); size_t pos = sdpstr.find_first_of(" ;\r\n"); if (pos != std::string::npos) { sdpstr.erase(pos); } webrtc::H264SpropParameterSets sprops; if (sprops.DecodeSprop(sdpstr)) { std::vector<uint8_t> sps; sps.insert(sps.end(), H26X_marker, H26X_marker+sizeof(H26X_marker)); sps.insert(sps.end(), sprops.sps_nalu().begin(), sprops.sps_nalu().end()); frames.push_back(sps); std::vector<uint8_t> pps; pps.insert(pps.end(), H26X_marker, H26X_marker+sizeof(H26X_marker)); pps.insert(pps.end(), sprops.pps_nalu().begin(), sprops.pps_nalu().end()); frames.push_back(pps); } else { RTC_LOG(LS_WARNING) << "Cannot decode SPS:" << sprop; } } } else if (codec == "H265") { const char* pattern="sprop-vps="; const char* spropvps=strstr(sdp, pattern); const char* spropsps=strstr(sdp, "sprop-sps="); const char* sproppps=strstr(sdp, "sprop-pps="); if (spropvps && spropsps && sproppps) { std::string vpsstr(spropvps+strlen(pattern)); std::vector<uint8_t> vps = extractParameters(vpsstr); frames.push_back(vps); std::string spsstr(spropsps+strlen(pattern)); std::vector<uint8_t> sps = extractParameters(spsstr); frames.push_back(sps); std::string ppsstr(sproppps+strlen(pattern)); std::vector<uint8_t> pps = extractParameters(ppsstr); frames.push_back(pps); } } return frames; } void postFormat(const std::string & format, int width, int height) { Frame frame(format, width, height); { std::unique_lock<std::mutex> lock(m_queuemutex); m_queue.push(frame); } m_queuecond.notify_all(); } void PostFrame(const rtc::scoped_refptr<webrtc::EncodedImageBuffer>& content, uint64_t ts, webrtc::VideoFrameType frameType) { Frame frame(content, ts, frameType); { std::unique_lock<std::mutex> lock(m_queuemutex); m_queue.push(frame); } m_queuecond.notify_all(); } // overide webrtc::DecodedImageCallback virtual int32_t Decoded(webrtc::VideoFrame& decodedImage) override { int64_t ts = std::chrono::high_resolution_clock::now().time_since_epoch().count()/1000/1000; RTC_LOG(LS_VERBOSE) << "VideoDecoder::Decoded size:" << decodedImage.size() << " decode ts:" << decodedImage.ntp_time_ms() << " source ts:" << ts; // waiting if ( (m_wait) && (m_prevts != 0) ) { int64_t periodSource = decodedImage.timestamp() - m_previmagets; int64_t periodDecode = ts-m_prevts; RTC_LOG(LS_VERBOSE) << "VideoDecoder::Decoded interframe decode:" << periodDecode << " source:" << periodSource; int64_t delayms = periodSource-periodDecode; if ( (delayms > 0) && (delayms < 1000) ) { std::this_thread::sleep_for(std::chrono::milliseconds(delayms)); } } else { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } m_scaler.OnFrame(decodedImage); m_previmagets = decodedImage.timestamp(); m_prevts = std::chrono::high_resolution_clock::now().time_since_epoch().count()/1000/1000; return 1; } void AddOrUpdateSink(rtc::VideoSinkInterface<webrtc::VideoFrame> *sink, const rtc::VideoSinkWants &wants) override { m_scaler.AddOrUpdateSink(sink, wants); } void RemoveSink(rtc::VideoSinkInterface<webrtc::VideoFrame> *sink) override { m_scaler.RemoveSink(sink); } protected: bool hasDecoder() { return (m_decoder.get() != NULL); } void createDecoder(const std::string & format, int width, int height) { webrtc::VideoDecoder::Settings settings; webrtc::RenderResolution resolution(width, height); settings.set_max_render_resolution(resolution); if (format == "H264") { m_decoder=m_factory->Create(m_env,webrtc::SdpVideoFormat(cricket::kH264CodecName)); settings.set_codec_type(webrtc::VideoCodecType::kVideoCodecH264); } else if (format == "H265") { m_decoder=m_factory->Create(m_env,webrtc::SdpVideoFormat(format)); settings.set_codec_type(webrtc::VideoCodecType::kVideoCodecH265); } else if (format == "VP9") { m_decoder=m_factory->Create(m_env,webrtc::SdpVideoFormat(cricket::kVp9CodecName)); settings.set_codec_type(webrtc::VideoCodecType::kVideoCodecVP9); } if (m_decoder.get() != NULL) { m_decoder->Configure(settings); m_decoder->RegisterDecodeCompleteCallback(this); } } Frame getFrame() { std::unique_lock<std::mutex> mlock(m_queuemutex); while (m_queue.empty()) { m_queuecond.wait(mlock); } Frame frame = m_queue.front(); m_queue.pop(); return frame; } void DecoderThread() { while (!m_stop) { Frame frame = this->getFrame(); if (!frame.m_format.empty()) { if (this->hasDecoder()) { if ((m_format != frame.m_format) || (m_width != frame.m_width) || (m_height != frame.m_height)) { RTC_LOG(LS_INFO) << "format changed => set format from " << m_format << " " << m_width << "x" << m_height << " to " << frame.m_format << " " << frame.m_width << "x" << frame.m_height; m_decoder.reset(NULL); } } if (!this->hasDecoder()) { RTC_LOG(LS_INFO) << "VideoDecoder:DecoderThread set format:" << frame.m_format << " " << frame.m_width << "x" << frame.m_height; m_format = frame.m_format; m_width = frame.m_width; m_height = frame.m_height; this->createDecoder(frame.m_format, frame.m_width, frame.m_height); } } if (frame.m_content.get() != NULL) { RTC_LOG(LS_VERBOSE) << "VideoDecoder::DecoderThread size:" << frame.m_content->size() << " ts:" << frame.m_timestamp_ms; ssize_t size = frame.m_content->size(); if (size) { webrtc::EncodedImage input_image; input_image.SetEncodedData(frame.m_content); input_image.SetFrameType(frame.m_frameType); input_image.ntp_time_ms_ = frame.m_timestamp_ms; input_image.SetRtpTimestamp(frame.m_timestamp_ms); // store time in ms that overflow the 32bits if (this->hasDecoder()) { int res = m_decoder->Decode(input_image, false, frame.m_timestamp_ms); if (res != WEBRTC_VIDEO_CODEC_OK) { RTC_LOG(LS_ERROR) << "VideoDecoder::DecoderThread failure:" << res; } } else { RTC_LOG(LS_ERROR) << "VideoDecoder::DecoderThread no decoder"; } } } } } void Start() { RTC_LOG(LS_INFO) << "VideoDecoder::start"; m_stop = false; m_decoderthread = std::thread(&VideoDecoder::DecoderThread, this); } void Stop() { RTC_LOG(LS_INFO) << "VideoDecoder::stop"; m_stop = true; Frame frame; { std::unique_lock<std::mutex> lock(m_queuemutex); m_queue.push(frame); } m_queuecond.notify_all(); m_decoderthread.join(); } public: std::unique_ptr<webrtc::VideoDecoder> m_decoder; protected: VideoScaler m_scaler; const webrtc::Environment m_env; std::unique_ptr<webrtc::VideoDecoderFactory>& m_factory; std::string m_format; int m_width; int m_height; std::queue<Frame> m_queue; std::mutex m_queuemutex; std::condition_variable m_queuecond; std::thread m_decoderthread; bool m_stop; bool m_wait; int64_t m_previmagets; int64_t m_prevts; };
2301_81045437/webrtc-streamer
inc/VideoDecoder.h
C++
unlicense
13,518
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** VideoDecoderFactory.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "api/video_codecs/builtin_video_decoder_factory.h" #include "NullDecoder.h" class VideoDecoderFactory : public webrtc::VideoDecoderFactory { public: VideoDecoderFactory(): supported_formats_(webrtc::SupportedH264Codecs()) { supported_formats_.push_back(webrtc::SdpVideoFormat(cricket::kH265CodecName)); } virtual ~VideoDecoderFactory() override {} std::unique_ptr<webrtc::VideoDecoder> Create(const webrtc::Environment& env, const webrtc::SdpVideoFormat& format) override { RTC_LOG(LS_INFO) << "Create Null Decoder format:" << format.ToString(); return std::make_unique<NullDecoder>(format); } std::vector<webrtc::SdpVideoFormat> GetSupportedFormats() const override { return supported_formats_; } private: std::vector<webrtc::SdpVideoFormat> supported_formats_; };
2301_81045437/webrtc-streamer
inc/VideoDecoderFactory.h
C++
unlicense
1,205
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** VideoEncoderFactory.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "api/video_codecs/builtin_video_encoder_factory.h" #include "modules/video_coding/codecs/h264/include/h264.h" #include "common_video/h264/h264_common.h" #include "NullEncoder.h" class VideoEncoderFactory : public webrtc::VideoEncoderFactory { public: VideoEncoderFactory(): supported_formats_(webrtc::SupportedH264Codecs()) { supported_formats_.push_back(webrtc::SdpVideoFormat(cricket::kH265CodecName)); } virtual ~VideoEncoderFactory() override {} std::unique_ptr<webrtc::VideoEncoder> Create(const webrtc::Environment & env, const webrtc::SdpVideoFormat& format) override { RTC_LOG(LS_INFO) << "Create Null Encoder format:" << format.ToString(); return std::make_unique<NullEncoder>(format); } std::vector<webrtc::SdpVideoFormat> GetSupportedFormats() const override { return supported_formats_; } private: std::vector<webrtc::SdpVideoFormat> supported_formats_; };
2301_81045437/webrtc-streamer
inc/VideoEncoderFactory.h
C++
unlicense
1,312
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** VideoScaler.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "media/base/video_broadcaster.h" #include "api/media_stream_interface.h" #include "api/video/i420_buffer.h" #include "VideoSource.h" class VideoScaler : public rtc::VideoSinkInterface<webrtc::VideoFrame>, public VideoSource { public: VideoScaler(const std::map<std::string, std::string> &opts) : m_width(0), m_height(0), m_rotation(webrtc::kVideoRotation_0), m_roi_x(0), m_roi_y(0), m_roi_width(0), m_roi_height(0) { if (opts.find("width") != opts.end()) { m_width = std::stoi(opts.at("width")); } if (opts.find("height") != opts.end()) { m_height = std::stoi(opts.at("height")); } if (opts.find("rotation") != opts.end()) { int rotation = std::stoi(opts.at("rotation")); switch (rotation) { case 90: m_rotation = webrtc::kVideoRotation_90; break; case 180: m_rotation = webrtc::kVideoRotation_180; break; case 270: m_rotation = webrtc::kVideoRotation_270; break; } } if (opts.find("roi_x") != opts.end()) { m_roi_x = std::stoi(opts.at("roi_x")); if (m_roi_x < 0) { RTC_LOG(LS_ERROR) << "Ignore roi_x=" << m_roi_x << ", it muss be >=0"; m_roi_x = 0; } } if (opts.find("roi_y") != opts.end()) { m_roi_y = std::stoi(opts.at("roi_y")); if (m_roi_y < 0) { RTC_LOG(LS_ERROR) << "Ignore roi_<=" << m_roi_y << ", it muss be >=0"; m_roi_y = 0; } } if (opts.find("roi_width") != opts.end()) { m_roi_width = std::stoi(opts.at("roi_width")); if (m_roi_width <= 0) { RTC_LOG(LS_ERROR) << "Ignore roi_width<=" << m_roi_width << ", it muss be >0"; m_roi_width = 0; } } if (opts.find("roi_height") != opts.end()) { m_roi_height = std::stoi(opts.at("roi_height")); if (m_roi_height <= 0) { RTC_LOG(LS_ERROR) << "Ignore roi_height<=" << m_roi_height << ", it muss be >0"; m_roi_height = 0; } } } virtual ~VideoScaler() { } rtc::scoped_refptr<webrtc::I420Buffer> createOutputBuffer() { int height = m_height; int width = m_width; if ( (height == 0) && (width == 0) ) { height = m_roi_height; width = m_roi_width; } else if (height == 0) { height = (m_roi_height * width) / m_roi_width; } else if (width == 0) { width = (m_roi_width * height) / m_roi_height; } return webrtc::I420Buffer::Create(width, height); } void OnFrame(const webrtc::VideoFrame &frame) override { if ((m_roi_x != 0) && (m_roi_x >= frame.width())) { RTC_LOG(LS_WARNING) << "The ROI position protrudes beyond the right edge of the image. Ignore roi_x."; m_roi_x = 0; } if ((m_roi_y !=0) && (m_roi_y >= frame.height())) { RTC_LOG(LS_WARNING) << "The ROI position protrudes beyond the bottom edge of the image. Ignore roi_y."; m_roi_y = 0; } if ((m_roi_width != 0) && ((m_roi_width + m_roi_x) > frame.width())) { RTC_LOG(LS_WARNING) << "The ROI protrudes beyond the right edge of the image. Ignore roi_width."; m_roi_width = 0; } if ((m_roi_height != 0) && ((m_roi_height + m_roi_y) > frame.height())) { RTC_LOG(LS_WARNING) << "The ROI protrudes beyond the bottom edge of the image. Ignore roi_height."; m_roi_height = 0; } if (m_roi_width == 0) { m_roi_width = frame.width() - m_roi_x; } if (m_roi_height == 0) { m_roi_height = frame.height() - m_roi_y; } if ( ((m_roi_width != frame.width()) && (m_roi_height == frame.height()) && (m_rotation == webrtc::kVideoRotation_0)) || (frame.video_frame_buffer()->type() == webrtc::VideoFrameBuffer::Type::kNative) ) { m_broadcaster.OnFrame(frame); } else { rtc::scoped_refptr<webrtc::I420Buffer> scaled_buffer = this->createOutputBuffer(); if (m_roi_width != frame.width() || m_roi_height != frame.height()) { RTC_LOG(LS_VERBOSE) << "crop:" << m_roi_x << "x" << m_roi_y << " " << m_roi_width << "x" << m_roi_height << " scale: " << scaled_buffer->width() << "x" << scaled_buffer->height(); scaled_buffer->CropAndScaleFrom(*frame.video_frame_buffer()->ToI420(), m_roi_x, m_roi_y, m_roi_width, m_roi_height); } else { RTC_LOG(LS_VERBOSE) << "scale: " << scaled_buffer->width() << "x" << scaled_buffer->height(); scaled_buffer->ScaleFrom(*frame.video_frame_buffer()->ToI420()); } webrtc::VideoFrame scaledFrame = webrtc::VideoFrame::Builder() .set_video_frame_buffer(scaled_buffer) .set_rotation(m_rotation) .set_timestamp_rtp(frame.timestamp()) .set_timestamp_ms(frame.render_time_ms()) .set_id(frame.timestamp()) .build(); m_broadcaster.OnFrame(scaledFrame); } } int width() { return m_roi_width; } int height() { return m_roi_height; } private: int m_width; int m_height; webrtc::VideoRotation m_rotation; int m_roi_x; int m_roi_y; int m_roi_width; int m_roi_height; };
2301_81045437/webrtc-streamer
inc/VideoScaler.h
C++
unlicense
6,541
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** VideoSource.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "modules/video_capture/video_capture_factory.h" #include "media/base/video_broadcaster.h" class VideoSource : public rtc::VideoSourceInterface<webrtc::VideoFrame> { public: void AddOrUpdateSink(rtc::VideoSinkInterface<webrtc::VideoFrame>* sink, const rtc::VideoSinkWants& wants) override { m_broadcaster.AddOrUpdateSink(sink, wants); } void RemoveSink(rtc::VideoSinkInterface<webrtc::VideoFrame>* sink) override { m_broadcaster.RemoveSink(sink); } protected: rtc::VideoBroadcaster m_broadcaster; };
2301_81045437/webrtc-streamer
inc/VideoSource.h
C++
unlicense
922
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** screencapturer.h ** ** -------------------------------------------------------------------------*/ #pragma once #include <thread> #include "api/video/i420_buffer.h" #include "libyuv/video_common.h" #include "libyuv/convert.h" #include "media/base/video_common.h" #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_capture_options.h" #include "VideoSource.h" class DesktopCapturer : public VideoSource, public webrtc::DesktopCapturer::Callback { public: DesktopCapturer(const std::map<std::string,std::string> & opts) : m_width(0), m_height(0) { if (opts.find("width") != opts.end()) { m_width = std::stoi(opts.at("width")); } if (opts.find("height") != opts.end()) { m_height = std::stoi(opts.at("height")); } } bool Init() { return this->Start(); } virtual ~DesktopCapturer() { this->Stop(); } void CaptureThread(); bool Start(); void Stop(); bool IsRunning() { return m_isrunning; } // overide webrtc::DesktopCapturer::Callback virtual void OnCaptureResult(webrtc::DesktopCapturer::Result result, std::unique_ptr<webrtc::DesktopFrame> frame); int width() { return m_width; } int height() { return m_height; } protected: std::thread m_capturethread; std::unique_ptr<webrtc::DesktopCapturer> m_capturer; int m_width; int m_height; bool m_isrunning; };
2301_81045437/webrtc-streamer
inc/desktopcapturer.h
C++
unlicense
1,813
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** rtspaudiocapturer.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "liveaudiosource.h" #include "mkvclient.h" #include "rtc_base/ref_counted_object.h" class FileAudioSource : public LiveAudioSource<MKVClient> { public: static rtc::scoped_refptr<FileAudioSource> Create(rtc::scoped_refptr<webrtc::AudioDecoderFactory> audioDecoderFactory, const std::string & uri, const std::map<std::string,std::string> & opts) { rtc::scoped_refptr<FileAudioSource> source(new rtc::FinalRefCountedObject<FileAudioSource>(audioDecoderFactory, uri, opts)); return source; } protected: FileAudioSource(rtc::scoped_refptr<webrtc::AudioDecoderFactory> audioDecoderFactory, const std::string & uri, const std::map<std::string,std::string> & opts); virtual ~FileAudioSource(); };
2301_81045437/webrtc-streamer
inc/fileaudiocapturer.h
C++
unlicense
1,128
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** filecapturer.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "livevideosource.h" #include "mkvclient.h" class FileVideoCapturer : public LiveVideoSource<MKVClient> { public: FileVideoCapturer(const std::string & uri, const std::map<std::string,std::string> & opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory); virtual ~FileVideoCapturer(); static FileVideoCapturer* Create(const std::string & url, const std::map<std::string, std::string> & opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory) { return new FileVideoCapturer(url, opts, videoDecoderFactory); } };
2301_81045437/webrtc-streamer
inc/filevideocapturer.h
C++
unlicense
942
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** liveaudiosource.h ** ** -------------------------------------------------------------------------*/ #pragma once #ifdef WIN32 #include "base/win/wincrypt_shim.h" #endif #include <iostream> #include <thread> #include <mutex> #include <queue> #include <cctype> #include "environment.h" #include "pc/local_audio_source.h" #include "api/audio_codecs/builtin_audio_decoder_factory.h" template <typename T> class LiveAudioSource : public webrtc::Notifier<webrtc::AudioSourceInterface>, public T::Callback { public: SourceState state() const override { return kLive; } bool remote() const override { return true; } virtual void AddSink(webrtc::AudioTrackSinkInterface *sink) override { RTC_LOG(LS_INFO) << "LiveAudioSource::AddSink "; std::lock_guard<std::mutex> lock(m_sink_lock); m_sinks.push_back(sink); } virtual void RemoveSink(webrtc::AudioTrackSinkInterface *sink) override { RTC_LOG(LS_INFO) << "LiveAudioSource::RemoveSink "; std::lock_guard<std::mutex> lock(m_sink_lock); m_sinks.remove(sink); } void CaptureThread() { m_env.mainloop(); } // overide RTSPConnection::Callback virtual bool onNewSession(const char *id, const char *media, const char *codec, const char *sdp, unsigned int rtpfrequency, unsigned int channels) override { bool success = false; if (strcmp(media, "audio") == 0) { RTC_LOG(LS_INFO) << "LiveAudioSource::onNewSession " << media << "/" << codec << " " << sdp; m_freq = rtpfrequency; m_channel = channels; RTC_LOG(LS_INFO) << "LiveAudioSource::onNewSession codec:" << " freq:" << m_freq << " channel:" << m_channel; std::map<std::string, std::string> params; if (m_channel == 2) { params["stereo"] = "1"; } webrtc::SdpAudioFormat format = webrtc::SdpAudioFormat(codec, m_freq, m_channel, std::move(params)); if (m_factory->IsSupportedDecoder(format)) { m_decoder = m_factory->MakeAudioDecoder(format, absl::optional<webrtc::AudioCodecPairId>()); m_codec[id] = codec; success = true; } else { RTC_LOG(LS_ERROR) << "LiveAudioSource::onNewSession not support codec" << sdp; } } return success; } virtual bool onData(const char *id, unsigned char *buffer, ssize_t size, struct timeval presentationTime) override { bool success = false; int segmentLength = m_freq / 100; if (m_codec.find(id) != m_codec.end()) { int64_t sourcets = presentationTime.tv_sec; sourcets = sourcets * 1000 + presentationTime.tv_usec / 1000; int64_t ts = std::chrono::high_resolution_clock::now().time_since_epoch().count() / 1000 / 1000; RTC_LOG(LS_VERBOSE) << "LiveAudioSource::onData decode ts:" << ts << " source ts:" << sourcets; if (m_decoder.get() != NULL) { // waiting if ((m_wait) && (m_prevts != 0)) { int64_t periodSource = sourcets - m_previmagets; int64_t periodDecode = ts - m_prevts; RTC_LOG(LS_VERBOSE) << "LiveAudioSource::onData interframe decode:" << periodDecode << " source:" << periodSource; int64_t delayms = periodSource - periodDecode; if ((delayms > 0) && (delayms < 1000)) { std::this_thread::sleep_for(std::chrono::milliseconds(delayms)); } } int maxDecodedBufferSize = m_decoder->PacketDuration(buffer, size) * m_channel * sizeof(int16_t); int16_t *decoded = new int16_t[maxDecodedBufferSize]; webrtc::AudioDecoder::SpeechType speech_type; int decodedBufferSize = m_decoder->Decode(buffer, size, m_freq, maxDecodedBufferSize, decoded, &speech_type); RTC_LOG(LS_VERBOSE) << "LiveAudioSource::onData size:" << size << " decodedBufferSize:" << decodedBufferSize << " maxDecodedBufferSize: " << maxDecodedBufferSize << " channels: " << m_channel; if (decodedBufferSize > 0) { for (int i = 0; i < decodedBufferSize; ++i) { m_buffer.push(decoded[i]); } } else { RTC_LOG(LS_ERROR) << "LiveAudioSource::onData error:Decode Audio failed"; } delete[] decoded; while (m_buffer.size() > segmentLength * m_channel) { int16_t *outbuffer = new int16_t[segmentLength * m_channel]; for (int i = 0; i < segmentLength * m_channel; ++i) { uint16_t value = m_buffer.front(); outbuffer[i] = value; m_buffer.pop(); } std::lock_guard<std::mutex> lock(m_sink_lock); for (auto *sink : m_sinks) { sink->OnData(outbuffer, 16, m_freq, m_channel, segmentLength); } delete[] outbuffer; } m_previmagets = sourcets; m_prevts = std::chrono::high_resolution_clock::now().time_since_epoch().count() / 1000 / 1000; success = true; } else { RTC_LOG(LS_VERBOSE) << "LiveAudioSource::onData error:No Audio decoder"; } } return success; } protected: LiveAudioSource(rtc::scoped_refptr<webrtc::AudioDecoderFactory> audioDecoderFactory, const std::string &uri, const std::map<std::string, std::string> &opts, bool wait) : m_env(m_stop) , m_connection(m_env, this, uri.c_str(), opts, rtc::LogMessage::GetLogToDebug() <= 2) , m_factory(audioDecoderFactory) , m_freq(8000) , m_channel(1) , m_wait(wait) , m_previmagets(0) , m_prevts(0) { m_capturethread = std::thread(&LiveAudioSource::CaptureThread, this); } virtual ~LiveAudioSource() { m_env.stop(); m_capturethread.join(); } private: char m_stop; Environment m_env; private: T m_connection; std::thread m_capturethread; rtc::scoped_refptr<webrtc::AudioDecoderFactory> m_factory; std::unique_ptr<webrtc::AudioDecoder> m_decoder; int m_freq; int m_channel; std::queue<uint16_t> m_buffer; std::list<webrtc::AudioTrackSinkInterface *> m_sinks; std::mutex m_sink_lock; std::map<std::string, std::string> m_codec; bool m_wait; int64_t m_previmagets; int64_t m_prevts; };
2301_81045437/webrtc-streamer
inc/liveaudiosource.h
C++
unlicense
7,495
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** livevideosource.h ** ** -------------------------------------------------------------------------*/ #pragma once #include <string.h> #include <vector> #include <queue> #include <thread> #include <mutex> #include <condition_variable> #include "environment.h" #include "libyuv/video_common.h" #include "libyuv/convert.h" #include "media/base/codec.h" #include "media/base/video_common.h" #include "media/base/video_broadcaster.h" #include "media/engine/internal_decoder_factory.h" #include "common_video/h265/h265_common.h" #include "common_video/h265/h265_sps_parser.h" #include "common_video/h264/h264_common.h" #include "common_video/h264/sps_parser.h" #include "api/video_codecs/video_decoder.h" #include "VideoDecoder.h" template <typename T> class LiveVideoSource : public VideoDecoder, public T::Callback { public: LiveVideoSource(const std::string &uri, const std::map<std::string, std::string> &opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory, bool wait) : VideoDecoder(opts, videoDecoderFactory, wait), m_env(m_stop), m_liveclient(m_env, this, uri.c_str(), opts, rtc::LogMessage::GetLogToDebug()<=2) { m_liveclient.start(); this->Start(); } virtual ~LiveVideoSource() { this->Stop(); } void Start() { RTC_LOG(LS_INFO) << "LiveVideoSource::Start"; m_capturethread = std::thread(&LiveVideoSource::CaptureThread, this); } void Stop() { RTC_LOG(LS_INFO) << "LiveVideoSource::stop"; m_env.stop(); m_capturethread.join(); } bool IsRunning() { return (m_stop == 0); } void CaptureThread() { m_env.mainloop(); } // overide T::onNewSession virtual bool onNewSession(const char *id, const char *media, const char *codec, const char *sdp, unsigned int rtpfrequency, unsigned int channels) override { bool success = false; if (strcmp(media, "video") == 0) { RTC_LOG(LS_INFO) << "LiveVideoSource::onNewSession id:"<< id << " media:" << media << "/" << codec << " sdp:" << sdp; if ( (strcmp(codec, "H264") == 0) || (strcmp(codec, "H265") == 0) || (strcmp(codec, "JPEG") == 0) || (strcmp(codec, "VP9") == 0) ) { RTC_LOG(LS_INFO) << "LiveVideoSource::onNewSession id:'" << id << "' '" << codec << "'\n"; m_codec[id] = codec; success = true; } RTC_LOG(LS_INFO) << "LiveVideoSource::onNewSession success:" << success << "\n"; if (success) { struct timeval presentationTime; timerclear(&presentationTime); std::vector<std::vector<uint8_t>> initFrames = getInitFrames(codec, sdp); for (auto frame : initFrames) { onData(id, frame.data(), frame.size(), presentationTime); } } } return success; } void onH264Data(unsigned char *buffer, ssize_t size, int64_t ts, const std::string & codec) { std::vector<webrtc::H264::NaluIndex> indexes = webrtc::H264::FindNaluIndices(buffer,size); RTC_LOG(LS_VERBOSE) << "LiveVideoSource:onData nbNalu:" << indexes.size(); for (const webrtc::H264::NaluIndex & index : indexes) { webrtc::H264::NaluType nalu_type = webrtc::H264::ParseNaluType(buffer[index.payload_start_offset]); RTC_LOG(LS_VERBOSE) << "LiveVideoSource:onData NALU type:" << nalu_type << " payload_size:" << index.payload_size << " payload_start_offset:" << index.payload_start_offset << " start_offset:" << index.start_offset; if (nalu_type == webrtc::H264::NaluType::kSps) { RTC_LOG(LS_VERBOSE) << "LiveVideoSource:onData SPS"; m_cfg.clear(); m_cfg.insert(m_cfg.end(), buffer + index.start_offset, buffer + index.payload_size + index.payload_start_offset); absl::optional<webrtc::SpsParser::SpsState> sps = webrtc::SpsParser::ParseSps(buffer + index.payload_start_offset + webrtc::H264::kNaluTypeSize, index.payload_size - webrtc::H264::kNaluTypeSize); if (!sps) { RTC_LOG(LS_ERROR) << "cannot parse sps"; postFormat(codec, 0, 0); } else { RTC_LOG(LS_INFO) << "LiveVideoSource:onData SPS set format " << sps->width << "x" << sps->height; postFormat(codec, sps->width, sps->height); } } else if (nalu_type == webrtc::H264::NaluType::kPps) { RTC_LOG(LS_VERBOSE) << "LiveVideoSource:onData PPS"; m_cfg.insert(m_cfg.end(), buffer + index.start_offset, buffer + index.payload_size + index.payload_start_offset); } else if (nalu_type == webrtc::H264::NaluType::kSei) { } else { webrtc::VideoFrameType frameType = webrtc::VideoFrameType::kVideoFrameDelta; std::vector<uint8_t> content; if (nalu_type == webrtc::H264::NaluType::kIdr) { frameType = webrtc::VideoFrameType::kVideoFrameKey; RTC_LOG(LS_VERBOSE) << "LiveVideoSource:onData IDR"; content.insert(content.end(), m_cfg.begin(), m_cfg.end()); } else { RTC_LOG(LS_VERBOSE) << "LiveVideoSource:onData SLICE NALU:" << nalu_type; } if (m_prevTimestamp && ts < m_prevTimestamp && m_decoder && strcmp(m_decoder->ImplementationName(),"FFmpeg")==0) { RTC_LOG(LS_ERROR) << "LiveVideoSource:onData drop frame in past for FFmpeg:" << (m_prevTimestamp-ts); } else { content.insert(content.end(), buffer + index.start_offset, buffer + index.payload_size + index.payload_start_offset); rtc::scoped_refptr<webrtc::EncodedImageBuffer> frame = webrtc::EncodedImageBuffer::Create(content.data(), content.size()); PostFrame(frame, ts, frameType); } } } } void onH265Data(unsigned char *buffer, ssize_t size, int64_t ts, const std::string & codec) { std::vector<webrtc::H265::NaluIndex> indexes = webrtc::H265::FindNaluIndices(buffer,size); RTC_LOG(LS_VERBOSE) << "LiveVideoSource:onData nbNalu:" << indexes.size(); for (const webrtc::H265::NaluIndex & index : indexes) { webrtc::H265::NaluType nalu_type = webrtc::H265::ParseNaluType(buffer[index.payload_start_offset]); RTC_LOG(LS_VERBOSE) << "LiveVideoSource:onData NALU type:" << nalu_type << " payload_size:" << index.payload_size << " payload_start_offset:" << index.payload_start_offset << " start_offset:" << index.start_offset; if (nalu_type == webrtc::H265::NaluType::kVps) { RTC_LOG(LS_VERBOSE) << "LiveVideoSource:onData VPS"; m_cfg.clear(); m_cfg.insert(m_cfg.end(), buffer + index.start_offset, buffer + index.payload_size + index.payload_start_offset); } else if (nalu_type == webrtc::H265::NaluType::kSps) { RTC_LOG(LS_VERBOSE) << "LiveVideoSource:onData SPS"; m_cfg.insert(m_cfg.end(), buffer + index.start_offset, buffer + index.payload_size + index.payload_start_offset); absl::optional<webrtc::H265SpsParser::SpsState> sps = webrtc::H265SpsParser::ParseSps(buffer + index.payload_start_offset + webrtc::H265::kNaluHeaderSize, index.payload_size - webrtc::H265::kNaluHeaderSize); if (!sps) { RTC_LOG(LS_ERROR) << "cannot parse sps"; postFormat(codec, 0, 0); } else { RTC_LOG(LS_INFO) << "LiveVideoSource:onData SPS set format " << sps->width << "x" << sps->height; postFormat(codec, sps->width, sps->height); } } else if (nalu_type == webrtc::H265::NaluType::kPps) { RTC_LOG(LS_VERBOSE) << "LiveVideoSource:onData PPS"; m_cfg.insert(m_cfg.end(), buffer + index.start_offset, buffer + index.payload_size + index.payload_start_offset); } else { webrtc::VideoFrameType frameType = webrtc::VideoFrameType::kVideoFrameDelta; std::vector<uint8_t> content; if ( (nalu_type == webrtc::H265::NaluType::kIdrWRadl) || (nalu_type == webrtc::H265::NaluType::kIdrNLp) ) { frameType = webrtc::VideoFrameType::kVideoFrameKey; RTC_LOG(LS_VERBOSE) << "LiveVideoSource:onData IDR"; content.insert(content.end(), m_cfg.begin(), m_cfg.end()); } else { RTC_LOG(LS_VERBOSE) << "LiveVideoSource:onData SLICE NALU:" << nalu_type; } if (m_prevTimestamp && ts < m_prevTimestamp && m_decoder && strcmp(m_decoder->ImplementationName(),"FFmpeg")==0) { RTC_LOG(LS_ERROR) << "LiveVideoSource:onData drop frame in past for FFmpeg:" << (m_prevTimestamp-ts); } else { content.insert(content.end(), buffer + index.start_offset, buffer + index.payload_size + index.payload_start_offset); rtc::scoped_refptr<webrtc::EncodedImageBuffer> frame = webrtc::EncodedImageBuffer::Create(content.data(), content.size()); PostFrame(frame, ts, frameType); } } } } int onJPEGData(unsigned char *buffer, ssize_t size, int64_t ts, const std::string & codec) { int res = 0; int32_t width = 0; int32_t height = 0; if (libyuv::MJPGSize(buffer, size, &width, &height) == 0) { int stride_y = width; int stride_uv = (width + 1) / 2; rtc::scoped_refptr<webrtc::I420Buffer> I420buffer = webrtc::I420Buffer::Create(width, height, stride_y, stride_uv, stride_uv); const int conversionResult = libyuv::ConvertToI420((const uint8_t *)buffer, size, I420buffer->MutableDataY(), I420buffer->StrideY(), I420buffer->MutableDataU(), I420buffer->StrideU(), I420buffer->MutableDataV(), I420buffer->StrideV(), 0, 0, width, height, width, height, libyuv::kRotate0, ::libyuv::FOURCC_MJPG); if (conversionResult >= 0) { webrtc::VideoFrame frame = webrtc::VideoFrame::Builder() .set_video_frame_buffer(I420buffer) .set_rotation(webrtc::kVideoRotation_0) .set_timestamp_ms(ts) .set_id(ts) .build(); Decoded(frame); } else { RTC_LOG(LS_ERROR) << "LiveVideoSource:onData decoder error:" << conversionResult; res = -1; } } else { RTC_LOG(LS_ERROR) << "LiveVideoSource:onData cannot JPEG dimension"; res = -1; } return res; } virtual bool onData(const char *id, unsigned char *buffer, ssize_t size, struct timeval presentationTime) override { int64_t ts = presentationTime.tv_sec; ts = ts * 1000 + presentationTime.tv_usec / 1000; RTC_LOG(LS_VERBOSE) << "LiveVideoSource:onData id:" << id << " size:" << size << " ts:" << ts; int res = 0; std::string codec = m_codec[id]; if (codec == "H264") { onH264Data(buffer, size, ts, codec); } else if (codec == "H265") { onH265Data(buffer, size, ts, codec); } else if (codec == "JPEG") { res = onJPEGData(buffer, size, ts, codec); } else if (codec == "VP9") { postFormat(codec, 0, 0); webrtc::VideoFrameType frameType = webrtc::VideoFrameType::kVideoFrameKey; rtc::scoped_refptr<webrtc::EncodedImageBuffer> frame = webrtc::EncodedImageBuffer::Create(buffer, size); PostFrame(frame, ts, frameType); } m_prevTimestamp = ts; return (res == 0); } private: char m_stop; Environment m_env; protected: T m_liveclient; private: std::thread m_capturethread; std::vector<uint8_t> m_cfg; std::map<std::string, std::string> m_codec; uint64_t m_prevTimestamp; };
2301_81045437/webrtc-streamer
inc/livevideosource.h
C++
unlicense
13,961
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** rtmpvideosource.h ** ** -------------------------------------------------------------------------*/ #pragma once #include <string.h> #include <vector> #include <queue> #include <thread> #include <mutex> #include <condition_variable> #include "media/base/codec.h" #include "media/base/video_common.h" #include "media/base/video_broadcaster.h" #include "media/engine/internal_decoder_factory.h" #include "common_video/h264/h264_common.h" #include "common_video/h264/sps_parser.h" #include "common_video/h265/h265_common.h" #include "common_video/h265/h265_sps_parser.h" #include "api/video_codecs/video_decoder.h" #include "VideoDecoder.h" #include <librtmp/rtmp.h> #include <librtmp/log.h> #define CODEC_ID_AVC 7 #define CODEC_ID_HEVC 12 class RtmpVideoSource : public VideoDecoder { public: static RtmpVideoSource *Create(const std::string &url, const std::map<std::string, std::string> &opts, std::unique_ptr<webrtc::VideoDecoderFactory> &videoDecoderFactory) { std::unique_ptr<RtmpVideoSource> capturer(new RtmpVideoSource(url, opts, videoDecoderFactory)); return capturer.release(); } virtual ~RtmpVideoSource() { this->Stop(); RTMP_Close(&m_rtmp); } private: RtmpVideoSource(const std::string &uri, const std::map<std::string, std::string> &opts, std::unique_ptr<webrtc::VideoDecoderFactory> &videoDecoderFactory) : m_stop(false), m_url(uri), VideoDecoder(opts, videoDecoderFactory) { RTMP_Init(&m_rtmp); RTMP_LogSetOutput(stderr); RTMP_LogSetLevel(RTMP_LOGINFO); if (!RTMP_SetupURL(&m_rtmp, const_cast<char*>(m_url.c_str()))) { RTC_LOG(LS_INFO) << "Unable to parse rtmp url:" << m_url; } this->Start(); } void Start() { RTC_LOG(LS_INFO) << "RtmpVideoSource::Start"; m_capturethread = std::thread(&RtmpVideoSource::CaptureThread, this); } void Stop() { RTC_LOG(LS_INFO) << "RtmpVideoSource::stop"; m_stop = true; m_capturethread.join(); } bool IsRunning() { return (!m_stop); } void CaptureThread() { RTC_LOG(LS_INFO) << "RtmpVideoSource::CaptureThread begin"; while (!m_stop) { if ( !RTMP_IsConnected(&m_rtmp) && (!RTMP_Connect(&m_rtmp, NULL) || !RTMP_ConnectStream(&m_rtmp, 0)) ) { RTC_LOG(LS_INFO) << "Unable to connect to stream"; } if (RTMP_IsConnected(&m_rtmp)) { RTMPPacket packet; if (RTMP_ReadPacket(&m_rtmp, &packet)) { RTMPPacket_Dump(&packet); if (packet.m_packetType == RTMP_PACKET_TYPE_VIDEO) { this->processVideoPacket(packet.m_body, packet.m_nBodySize); } } RTMPPacket_Free(&packet); } } RTC_LOG(LS_INFO) << "RtmpVideoSource::CaptureThread end"; } private: char m_stop; void processVideoPacket(char * body, unsigned int size) { int64_t ts = RTMP_GetTime(); unsigned char frameTypeAndCodecId = body[0]; unsigned char frameType = frameTypeAndCodecId >> 4; // Shift right to get the first 4 bits unsigned char codecId = frameTypeAndCodecId & 0x0F; // Bitwise AND to get the last 4 bits if (codecId == CODEC_ID_AVC) { if (frameType == 1 && body[1] == 0) { RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H264 SPS/PPS"; int start_sps = 11; int spssize = (body[start_sps]<<8) + body[start_sps+1]; webrtc::H264::NaluType nalu_type = webrtc::H264::ParseNaluType(body[start_sps+2]); RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H264 NALU type:" << nalu_type; if (nalu_type == webrtc::H264::NaluType::kSps) { m_cfg.clear(); RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H264 SPS size:" << spssize; absl::optional<webrtc::SpsParser::SpsState> sps = webrtc::SpsParser::ParseSps((const unsigned char*)(&body[start_sps+3]), spssize); if (!sps) { RTC_LOG(LS_ERROR) << "cannot parse H264 sps"; } else { RTC_LOG(LS_ERROR) << "sps " << sps->width << "x" << sps->height; RTC_LOG(LS_INFO) << "RtmpVideoSource:onData H264 SPS set format " << sps->width << "x" << sps->height; postFormat("H264", sps->width, sps->height); m_cfg.insert(m_cfg.end(), H26X_marker, H26X_marker+sizeof(H26X_marker)); m_cfg.insert(m_cfg.end(), &body[start_sps+2], &body[start_sps+2 + spssize + 1]); int start_pps = start_sps + spssize + 3; int ppssize = (body[start_pps]<<8) + body[start_pps+1]; nalu_type = webrtc::H264::ParseNaluType(body[start_pps+2]); RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H264 NALU type:" << nalu_type; RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H264 PPS size:" << ppssize; m_cfg.insert(m_cfg.end(), H26X_marker, H26X_marker+sizeof(H26X_marker)); m_cfg.insert(m_cfg.end(), &body[start_pps+2], &body[start_pps + 2 + ppssize + 1]); } } } else if (frameType == 1 && body[1] == 1) { webrtc::H264::NaluType nalu_type = webrtc::H264::ParseNaluType(body[9]); RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H264 IDR NALU type:" << nalu_type; std::vector<uint8_t> content; content.insert(content.end(), m_cfg.begin(), m_cfg.end()); content.insert(content.end(), H26X_marker, H26X_marker+sizeof(H26X_marker)); content.insert(content.end(), &body[9], &body[size]); rtc::scoped_refptr<webrtc::EncodedImageBuffer> frame = webrtc::EncodedImageBuffer::Create(content.data(), content.size()); PostFrame(frame, ts, webrtc::VideoFrameType::kVideoFrameKey); } else if (frameType == 2) { webrtc::H264::NaluType nalu_type = webrtc::H264::ParseNaluType(body[9]); RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H264 Slice NALU type:" << nalu_type; std::vector<uint8_t> content; content.insert(content.end(), H26X_marker, H26X_marker+sizeof(H26X_marker)); content.insert(content.end(), &body[9], &body[size]); rtc::scoped_refptr<webrtc::EncodedImageBuffer> frame = webrtc::EncodedImageBuffer::Create(content.data(), content.size()); PostFrame(frame, ts, webrtc::VideoFrameType::kVideoFrameDelta); } } else if (codecId == CODEC_ID_HEVC) { if (frameType == 1 && body[1] == 0) { RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H265 VPS/SPS/PPS"; int start_vps = 31; int vpssize = (body[start_vps]<<8) + body[start_vps+1]; webrtc::H265::NaluType nalu_type = webrtc::H265::ParseNaluType(body[start_vps+2]); RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H265 NALU type:" << nalu_type; RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H265 VPS size:" << vpssize; if (nalu_type == webrtc::H265::NaluType::kVps) { m_cfg.clear(); m_cfg.insert(m_cfg.end(), H26X_marker, H26X_marker+sizeof(H26X_marker)); m_cfg.insert(m_cfg.end(), &body[start_vps+2], &body[start_vps+2 + vpssize + 1]); int start_sps = start_vps + vpssize + 3 + 2; int spssize = (body[start_sps]<<8) + body[start_sps+1]; nalu_type = webrtc::H265::ParseNaluType(body[start_sps+2]); RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H265 NALU type:" << nalu_type; RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H265 SPS size:" << spssize; if (nalu_type == webrtc::H265::NaluType::kSps) { absl::optional<webrtc::H265SpsParser::SpsState> sps = webrtc::H265SpsParser::ParseSps((const unsigned char*)(&body[start_sps+3]), spssize); if (!sps) { RTC_LOG(LS_ERROR) << "cannot parse H265 sps"; } else { RTC_LOG(LS_ERROR) << "sps " << sps->width << "x" << sps->height; RTC_LOG(LS_INFO) << "RtmpVideoSource:onData H265 SPS set format " << sps->width << "x" << sps->height; postFormat("H265", sps->width, sps->height); } m_cfg.insert(m_cfg.end(), H26X_marker, H26X_marker+sizeof(H26X_marker)); m_cfg.insert(m_cfg.end(), &body[start_sps+2], &body[start_sps+2 + spssize + 1]); int start_pps = start_sps + spssize + 3 + 2; int ppssize = (body[start_pps]<<8) + body[start_pps+1]; nalu_type = webrtc::H265::ParseNaluType(body[start_pps+2]); RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H265 NALU type:" << nalu_type; RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H265 PPS size:" << ppssize; m_cfg.insert(m_cfg.end(), H26X_marker, H26X_marker+sizeof(H26X_marker)); m_cfg.insert(m_cfg.end(), &body[start_pps+2], &body[start_pps+2 + ppssize + 1]); } } } else if (frameType == 1 && body[1] == 1) { webrtc::H265::NaluType nalu_type = webrtc::H265::ParseNaluType(body[9]); RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H265 IDR type:" << nalu_type; std::vector<uint8_t> content; content.insert(content.end(), m_cfg.begin(), m_cfg.end()); content.insert(content.end(), H26X_marker, H26X_marker+sizeof(H26X_marker)); content.insert(content.end(), &body[9], &body[size]); rtc::scoped_refptr<webrtc::EncodedImageBuffer> frame = webrtc::EncodedImageBuffer::Create(content.data(), content.size()); PostFrame(frame, ts, webrtc::VideoFrameType::kVideoFrameKey); } else if (frameType == 2) { webrtc::H265::NaluType nalu_type = webrtc::H265::ParseNaluType(body[9]); RTC_LOG(LS_INFO) << "RtmpVideoSource::onNewSession H265 Slice NALU type:" << nalu_type; std::vector<uint8_t> content; content.insert(content.end(), H26X_marker, H26X_marker+sizeof(H26X_marker)); content.insert(content.end(), &body[9], &body[size]); rtc::scoped_refptr<webrtc::EncodedImageBuffer> frame = webrtc::EncodedImageBuffer::Create(content.data(), content.size()); PostFrame(frame, ts, webrtc::VideoFrameType::kVideoFrameDelta); } } } protected: RTMP m_rtmp; std::string m_url; private: std::thread m_capturethread; std::vector<uint8_t> m_cfg; };
2301_81045437/webrtc-streamer
inc/rtmpvideosource.h
C++
unlicense
12,169
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** rtspvideocapturer.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "sdpclient.h" #include "livevideosource.h" class RTPVideoCapturer : public LiveVideoSource<SDPClient> { public: RTPVideoCapturer(const std::string & uri, const std::map<std::string,std::string> & opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory); virtual ~RTPVideoCapturer(); static RTPVideoCapturer* Create(const std::string & url, const std::map<std::string, std::string> & opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory) { return new RTPVideoCapturer(url, opts, videoDecoderFactory); } // overide SDPClient::Callback virtual void onError(SDPClient& connection,const char* error) override; };
2301_81045437/webrtc-streamer
inc/rtpvideocapturer.h
C++
unlicense
1,056
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** rtspaudiocapturer.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "liveaudiosource.h" #include "rtspconnectionclient.h" #include "rtc_base/ref_counted_object.h" class RTSPAudioSource : public LiveAudioSource<RTSPConnection> { public: static rtc::scoped_refptr<RTSPAudioSource> Create(rtc::scoped_refptr<webrtc::AudioDecoderFactory> audioDecoderFactory, const std::string & uri, const std::map<std::string,std::string> & opts) { rtc::scoped_refptr<RTSPAudioSource> source(new rtc::FinalRefCountedObject<RTSPAudioSource>(audioDecoderFactory, uri, opts)); return source; } protected: RTSPAudioSource(rtc::scoped_refptr<webrtc::AudioDecoderFactory> audioDecoderFactory, const std::string & uri, const std::map<std::string,std::string> & opts); virtual ~RTSPAudioSource(); };
2301_81045437/webrtc-streamer
inc/rtspaudiocapturer.h
C++
unlicense
1,116
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** rtspvideocapturer.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "livevideosource.h" #include "rtspconnectionclient.h" class RTSPVideoCapturer : public LiveVideoSource<RTSPConnection> { public: RTSPVideoCapturer(const std::string & uri, const std::map<std::string,std::string> & opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory); virtual ~RTSPVideoCapturer(); static RTSPVideoCapturer* Create(const std::string & url, const std::map<std::string, std::string> & opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory) { return new RTSPVideoCapturer(url, opts, videoDecoderFactory); } // overide RTSPConnection::Callback virtual void onConnectionTimeout(RTSPConnection& connection) override { connection.start(); } virtual void onDataTimeout(RTSPConnection& connection) override { connection.start(); } virtual void onError(RTSPConnection& connection,const char* erro) override; };
2301_81045437/webrtc-streamer
inc/rtspvideocapturer.h
C++
unlicense
1,289
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** screencapturer.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "desktopcapturer.h" class ScreenCapturer : public DesktopCapturer { public: ScreenCapturer(const std::string & url, const std::map<std::string,std::string> & opts) : DesktopCapturer(opts) { const std::string prefix("screen://"); m_capturer = webrtc::DesktopCapturer::CreateScreenCapturer(webrtc::DesktopCaptureOptions::CreateDefault()); if (m_capturer) { webrtc::DesktopCapturer::SourceList sourceList; if (m_capturer->GetSourceList(&sourceList)) { const std::string screen(url.substr(prefix.length())); if (screen.empty() == false) { for (auto source : sourceList) { RTC_LOG(LS_ERROR) << "ScreenCapturer source:" << source.id << " title:"<< source.title; if (atoi(screen.c_str()) == source.id) { m_capturer->SelectSource(source.id); break; } } } } } } static ScreenCapturer* Create(const std::string & url, const std::map<std::string, std::string> & opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory) { std::unique_ptr<ScreenCapturer> capturer(new ScreenCapturer(url, opts)); if (!capturer->Init()) { RTC_LOG(LS_WARNING) << "Failed to create WindowCapturer"; return nullptr; } return capturer.release(); } };
2301_81045437/webrtc-streamer
inc/screencapturer.h
C++
unlicense
1,635
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** windowcapturer.h ** ** -------------------------------------------------------------------------*/ #pragma once #include "desktopcapturer.h" class WindowCapturer : public DesktopCapturer { public: WindowCapturer(const std::string & url, const std::map<std::string,std::string> & opts) : DesktopCapturer(opts) { const std::string windowprefix("window://"); if (url.find(windowprefix) == 0) { m_capturer = webrtc::DesktopCapturer::CreateWindowCapturer(webrtc::DesktopCaptureOptions::CreateDefault()); if (m_capturer) { webrtc::DesktopCapturer::SourceList sourceList; if (m_capturer->GetSourceList(&sourceList)) { const std::string windowtitle(url.substr(windowprefix.length())); for (auto source : sourceList) { RTC_LOG(LS_ERROR) << "WindowCapturer source:" << source.id << " title:"<< source.title; if (windowtitle == source.title) { m_capturer->SelectSource(source.id); break; } } } } } } static WindowCapturer* Create(const std::string & url, const std::map<std::string, std::string> & opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory) { std::unique_ptr<WindowCapturer> capturer(new WindowCapturer(url, opts)); if (!capturer->Init()) { RTC_LOG(LS_WARNING) << "Failed to create WindowCapturer"; return nullptr; } return capturer.release(); } };
2301_81045437/webrtc-streamer
inc/windowcapturer.h
C++
unlicense
1,657
#!/usr/bin/env node /* * NodeJS example to send a webrtc-streamer stream to janus-gateway */ // decode arguments if (process.argv.length < 4) { console.log("Usage: " + __filename + " <webrtc-streamer url> <videourl> <janus url> <janus room>"); process.exit(-1); } var webrtcstreamerurl = process.argv[2]; console.log("webrtcstreamerurl: " + webrtcstreamerurl); var videourl = process.argv[3]; console.log("videourl: " + videourl); var janusRoomUrl = process.argv[4]; console.log("janusRoomUrl: " + janusRoomUrl); var roomId = 1234 if (process.argv.length >= 5) { roomId = process.argv[5]; } console.log("roomId: " + roomId); global.fetch = require("node-fetch"); var JanusVideoRoom = require("./html/janusvideoroom.js"); var janus = new JanusVideoRoom(janusRoomUrl, webrtcstreamerurl); janus.join(roomId,videourl,"video");
2301_81045437/webrtc-streamer
joinjanusvideoroom.js
JavaScript
unlicense
838
#!/usr/bin/env node /* * NodeJS example to send a webrtc-streamer stream to jitsi */ process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; // decode arguments if (process.argv.length <= 4) { console.log("Usage: " + __filename + " <webrtc-streamer url> <videourl> <xmpp url> <xmpp room>"); process.exit(-1); } var webrtcstreamerurl = process.argv[2]; console.log("webrtcstreamerurl: " + webrtcstreamerurl); var videourl = process.argv[3]; console.log("videourl: " + videourl); var xmppRoomUrl = process.argv[4]; console.log("xmppRoomUrl: " + xmppRoomUrl); var xmppRoomId = "testroom" if (process.argv.length >= 5) { xmppRoomId = process.argv[5]; } console.log("xmppRoomId: " + xmppRoomId); var jsdom = require("jsdom"); const { JSDOM } = jsdom; const { window } = new JSDOM(""); global.jquery = require("jquery")(window); global.$ = (selector,context) => {return new jquery.fn.init(selector,context); }; global.window = window; global.document = window.document; global.DOMParser = window.document.DOMParser; global.XMLHttpRequest = window.XMLHttpRequest; var strophe = require("strophe.js"); global.Strophe = strophe.Strophe; global.$iq = strophe.$iq; //global.Strophe.log = console.log; require("strophejs-plugin-disco"); require("strophejs-plugin-muc"); global.SDP = require("strophe.jingle/strophe.jingle.sdp.js"); global.fetch = require("node-fetch"); var XMPPVideoRoom = require("./html/xmppvideoroom.js"); var xmpp = new XMPPVideoRoom(xmppRoomUrl, webrtcstreamerurl); var username = "user"+Math.random().toString(36).slice(2); console.log("join " + xmppRoomId + "/" + username); xmpp.join(xmppRoomId,videourl,username);
2301_81045437/webrtc-streamer
joinxmpproom.js
JavaScript
unlicense
1,645
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** HttpServerRequestHandler.cpp ** ** -------------------------------------------------------------------------*/ #include <string.h> #ifndef WIN32 #include <unistd.h> #include <dirent.h> #endif #include <iostream> #include <fstream> #include <iterator> #include <vector> #include "prometheus/counter.h" #include "prometheus/gauge.h" #include "prometheus/text_serializer.h" #include "rtc_base/logging.h" #include "HttpServerRequestHandler.h" int log_message(const struct mg_connection *conn, const char *message) { fprintf(stderr, "%s\n", message); return 0; } static struct CivetCallbacks _callbacks; const struct CivetCallbacks * getCivetCallbacks() { memset(&_callbacks, 0, sizeof(_callbacks)); _callbacks.log_message = &log_message; return &_callbacks; } /* --------------------------------------------------------------------------- ** Civet HTTP callback ** -------------------------------------------------------------------------*/ class RequestHandler : public CivetHandler { public: RequestHandler(HttpServerRequestHandler::httpFunction & func, prometheus::Counter & counter): m_func(func), m_counter(counter) { } bool handle(CivetServer *server, struct mg_connection *conn) { // increment metrics m_counter.Increment(); const struct mg_request_info *req_info = mg_get_request_info(conn); RTC_LOG(LS_INFO) << "uri:" << req_info->request_uri; // read input Json::Value in = this->getInputMessage(req_info, conn); // invoke API implementation std::tuple<int, std::map<std::string,std::string>,Json::Value> out(m_func(req_info, in)); int code = std::get<0>(out); std::string answer; // fill out Json::Value& body = std::get<2>(out); if (body.isNull() == false) { if (body.isString()) { answer = body.asString(); } else { answer = Json::writeString(m_writerBuilder,body); } } else { code = 500; answer = mg_get_response_code_text(conn, code); } RTC_LOG(LS_VERBOSE) << "code:" << code << " answer:" << answer; mg_printf(conn,"HTTP/1.1 %d OK\r\n", code); mg_printf(conn,"Access-Control-Allow-Origin: *\r\n"); mg_printf(conn,"Content-Type: text/plain\r\n"); mg_printf(conn,"Content-Length: %zd\r\n", answer.size()); std::map<std::string,std::string> & headers = std::get<1>(out); for (auto & it : headers) { mg_printf(conn,"%s: %s\r\n", it.first.c_str(), it.second.c_str()); } mg_printf(conn,"\r\n"); mg_write(conn,answer.c_str(),answer.size()); return true; } bool handleGet(CivetServer *server, struct mg_connection *conn) { return handle(server, conn); } bool handlePost(CivetServer *server, struct mg_connection *conn) { return handle(server, conn); } bool handlePatch(CivetServer *server, struct mg_connection *conn) { return handle(server, conn); } bool handleDelete(CivetServer *server, struct mg_connection *conn) { return handle(server, conn); } private: HttpServerRequestHandler::httpFunction m_func; Json::StreamWriterBuilder m_writerBuilder; Json::CharReaderBuilder m_readerBuilder; prometheus::Counter& m_counter; Json::Value getInputMessage(const struct mg_request_info *req_info, struct mg_connection *conn) { Json::Value jmessage; // read input long long tlen = req_info->content_length; if (tlen > 0) { std::string body = CivetServer::getPostData(conn); // parse in std::unique_ptr<Json::CharReader> reader(m_readerBuilder.newCharReader()); std::string errors; if (!reader->parse(body.c_str(), body.c_str() + body.size(), &jmessage, &errors)) { RTC_LOG(LS_WARNING) << "Received unknown message:" << body << " errors:" << errors; jmessage = body; } } return jmessage; } }; /* --------------------------------------------------------------------------- ** Civet HTTP callback ** -------------------------------------------------------------------------*/ class PrometheusHandler : public CivetHandler { public: PrometheusHandler(prometheus::Registry& registry) : m_registry(registry), m_fds(prometheus::BuildGauge().Name("process_open_fds").Register(m_registry).Add({})), m_threads(prometheus::BuildGauge().Name("process_threads_total").Register(m_registry).Add({})), m_virtual_memory(prometheus::BuildGauge().Name("process_virtual_memory_bytes").Register(m_registry).Add({})), m_resident_memory(prometheus::BuildGauge().Name("process_resident_memory_bytes").Register(m_registry).Add({})), m_cpu(prometheus::BuildGauge().Name("process_cpu_seconds_total").Register(m_registry).Add({})) { } bool handleGet(CivetServer *server, struct mg_connection *conn) { #ifndef WIN32 updateMetrics(); #endif auto collected = m_registry.Collect(); // format body prometheus::TextSerializer textSerializer; std::ostringstream os; textSerializer.Serialize(os,collected); std::string answer(os.str()); // format http answer mg_printf(conn,"HTTP/1.1 200 OK\r\n"); mg_printf(conn,"Access-Control-Allow-Origin: *\r\n"); mg_printf(conn,"Content-Type: text/plain\r\n"); mg_printf(conn,"Content-Length: %zd\r\n", answer.size()); mg_printf(conn,"\r\n"); mg_write(conn,answer.c_str(),answer.size()); return true; } private: #ifndef WIN32 void updateMetrics() { long fds = get_fds_total(); m_fds.Set(fds); std::vector<std::string> stat = read_proc_stat(); long threads_total = std::stoul(stat[19]); m_threads.Set(threads_total); long vm_bytes = std::stoul(stat[22]); m_virtual_memory.Set(vm_bytes); long rm_bytes = std::stoul(stat[23]) * sysconf(_SC_PAGESIZE); m_resident_memory.Set(rm_bytes); long cpu = (std::stoul(stat[13]) + std::stoul(stat[14]))/sysconf(_SC_CLK_TCK); m_cpu.Set(cpu); } static std::vector<std::string> read_proc_stat() { char stat_path[32]; std::snprintf(stat_path, sizeof(stat_path),"/proc/%d/stat", getpid()); std::ifstream file(stat_path); std::string line; std::getline(file, line); std::istringstream is(line); return std::vector<std::string>{std::istream_iterator<std::string>{is}, std::istream_iterator<std::string>{}}; } static long get_fds_total() { char fd_path[32]; std::snprintf(fd_path, sizeof(fd_path), "/proc/%d/fd", getpid()); long file_total = 0; DIR *dirp = opendir(fd_path); if (dirp != NULL) { struct dirent *entry; while ((entry = readdir(dirp)) != NULL) { if (entry->d_type == DT_LNK) { file_total++; } } closedir(dirp); } return file_total; } #endif private: prometheus::Registry& m_registry; prometheus::Gauge& m_fds; prometheus::Gauge& m_threads; prometheus::Gauge& m_virtual_memory; prometheus::Gauge& m_resident_memory; prometheus::Gauge& m_cpu; }; class WebsocketHandler: public CivetWebSocketHandler { public: WebsocketHandler(std::map<std::string,HttpServerRequestHandler::httpFunction> & func): m_func(func) { } private: std::map<std::string,HttpServerRequestHandler::httpFunction> m_func; Json::StreamWriterBuilder m_jsonWriterBuilder; virtual bool handleConnection(CivetServer *server, const struct mg_connection *conn) { RTC_LOG(LS_INFO) << "WS connected"; return true; } virtual void handleReadyState(CivetServer *server, struct mg_connection *conn) { RTC_LOG(LS_INFO) << "WS ready"; } virtual bool handleData(CivetServer *server, struct mg_connection *conn, int bits, char *data, size_t data_len) { int opcode = bits&0xf; printf("WS got %lu bytes\n", (long unsigned)data_len); if (opcode == MG_WEBSOCKET_OPCODE_TEXT) { // parse in std::string body(data, data_len); Json::CharReaderBuilder builder; std::unique_ptr<Json::CharReader> reader(builder.newCharReader()); Json::Value in; if (!reader->parse(body.c_str(), body.c_str() + body.size(), &in, NULL)) { RTC_LOG(LS_WARNING) << "Received unknown message:" << body; } std::cout << Json::writeString(m_jsonWriterBuilder,in) << std::endl; std::string request = in.get("request","").asString(); auto it = m_func.find(request); std::string answer; if (it != m_func.end()) { HttpServerRequestHandler::httpFunction func = it->second; // invoke API implementation const struct mg_request_info *req_info = mg_get_request_info(conn); std::tuple<int, std::map<std::string,std::string>,Json::Value> out(func(req_info, in.get("body",""))); answer = Json::writeString(m_jsonWriterBuilder,std::get<2>(out)); } else { answer = mg_get_response_code_text(conn, 500); } mg_websocket_write(conn, MG_WEBSOCKET_OPCODE_TEXT, answer.c_str(), answer.size()); } return true; } virtual void handleClose(CivetServer *server, const struct mg_connection *conn) { RTC_LOG(LS_INFO) << "WS closed"; } }; /* --------------------------------------------------------------------------- ** Constructor ** -------------------------------------------------------------------------*/ HttpServerRequestHandler::HttpServerRequestHandler(std::map<std::string,httpFunction>& func, const std::vector<std::string>& options) : CivetServer(options, getCivetCallbacks()) { auto& family = prometheus::BuildCounter() .Name("http_requests") .Register(m_registry); // register handlers for (auto it : func) { auto & counter = family.Add({{"uri", it.first}}); CivetHandler* handler = new RequestHandler(it.second, counter); this->addHandler(it.first, handler); m_handlers.push_back(handler); } CivetHandler* handler = new PrometheusHandler(m_registry); this->addHandler("/metrics", handler); m_handlers.push_back(handler); this->addWebSocketHandler("/ws", new WebsocketHandler(func)); } /* --------------------------------------------------------------------------- ** Constructor ** -------------------------------------------------------------------------*/ HttpServerRequestHandler::~HttpServerRequestHandler() { while (m_handlers.size() > 0) { CivetHandler* handler = m_handlers.back(); m_handlers.pop_back(); delete handler; } }
2301_81045437/webrtc-streamer
src/HttpServerRequestHandler.cpp
C++
unlicense
11,639
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** PeerConnectionManager.cpp ** ** -------------------------------------------------------------------------*/ #include <iostream> #include <fstream> #include <utility> #include <functional> #include "api/video_codecs/builtin_video_decoder_factory.h" #include "api/video_codecs/builtin_video_encoder_factory.h" #include "api/audio_codecs/builtin_audio_encoder_factory.h" #include "api/audio_codecs/builtin_audio_decoder_factory.h" #include "api/rtc_event_log/rtc_event_log_factory.h" #include "api/task_queue/default_task_queue_factory.h" #include "media/engine/webrtc_media_engine.h" #include "modules/audio_device/include/fake_audio_device.h" #include "api/enable_media.h" #include "PeerConnectionManager.h" #include "V4l2AlsaMap.h" #include "CapturerFactory.h" #include "VideoEncoderFactory.h" #include "VideoDecoderFactory.h" // Names used for a IceCandidate JSON object. const char kCandidateSdpMidName[] = "sdpMid"; const char kCandidateSdpMlineIndexName[] = "sdpMLineIndex"; const char kCandidateSdpName[] = "candidate"; // Names used for a SessionDescription JSON object. const char kSessionDescriptionTypeName[] = "type"; const char kSessionDescriptionSdpName[] = "sdp"; // character to remove from url to make webrtc label bool ignoreInLabel(char c) { return c == ' ' || c == ':' || c == '.' || c == '/' || c == '&'; } /* --------------------------------------------------------------------------- ** helpers that should be moved somewhere else ** -------------------------------------------------------------------------*/ #ifdef WIN32 #include <winsock2.h> #include <iphlpapi.h> #include <stdio.h> #include <stdlib.h> #pragma comment(lib, "IPHLPAPI.lib") #pragma comment(lib, "ws2_32.lib") #else #include <net/if.h> #include <ifaddrs.h> #endif std::string getServerIpFromClientIp(long clientip) { std::string serverAddress("127.0.0.1"); #ifdef WIN32 ULONG outBufLen = 0; DWORD dwRetVal = GetAdaptersAddresses(AF_INET, GAA_FLAG_INCLUDE_PREFIX, NULL, NULL, &outBufLen); if (dwRetVal == ERROR_BUFFER_OVERFLOW) { PIP_ADAPTER_ADDRESSES pAddresses = (IP_ADAPTER_ADDRESSES*)malloc(outBufLen); if (pAddresses != NULL) { if (GetAdaptersAddresses(AF_INET, GAA_FLAG_INCLUDE_PREFIX, NULL, pAddresses, &outBufLen) == NO_ERROR) { for (PIP_ADAPTER_ADDRESSES pCurrAddresses = pAddresses; pCurrAddresses != NULL; pCurrAddresses = pCurrAddresses->Next) { for (PIP_ADAPTER_UNICAST_ADDRESS pUnicast = pCurrAddresses->FirstUnicastAddress; pUnicast != NULL; pUnicast = pUnicast->Next) { sockaddr* sa = pUnicast->Address.lpSockaddr; if (sa->sa_family == AF_INET) { struct sockaddr_in* ipv4 = (struct sockaddr_in*)sa; struct in_addr addr = ipv4->sin_addr; struct in_addr mask; mask.s_addr = htonl((0xFFFFFFFFU << (32 - pUnicast->OnLinkPrefixLength)) & 0xFFFFFFFFU); if ((addr.s_addr & mask.s_addr) == (clientip & mask.s_addr)) { serverAddress = inet_ntoa(addr); break; } } } } } } free(pAddresses); } #else struct ifaddrs *ifaddr = NULL; if (getifaddrs(&ifaddr) == 0) { for (struct ifaddrs *ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if ((ifa->ifa_netmask != NULL) && (ifa->ifa_netmask->sa_family == AF_INET) && (ifa->ifa_addr != NULL) && (ifa->ifa_addr->sa_family == AF_INET)) { struct sockaddr_in *addr = (struct sockaddr_in *)ifa->ifa_addr; struct sockaddr_in *mask = (struct sockaddr_in *)ifa->ifa_netmask; if ((addr->sin_addr.s_addr & mask->sin_addr.s_addr) == (clientip & mask->sin_addr.s_addr)) { char host[NI_MAXHOST]; if (getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, sizeof(host), NULL, 0, NI_NUMERICHOST) == 0) { serverAddress = host; break; } } } } } freeifaddrs(ifaddr); #endif return serverAddress; } webrtc::PeerConnectionInterface::IceServer getIceServerFromUrl(const std::string &url, const std::string &clientIp = "") { webrtc::PeerConnectionInterface::IceServer srv; srv.uri = url; std::size_t pos = url.find_first_of(':'); if (pos != std::string::npos) { std::string protocol = url.substr(0, pos); std::string uri = url.substr(pos + 1); std::string credentials; std::size_t pos = uri.rfind('@'); if (pos != std::string::npos) { credentials = uri.substr(0, pos); uri = uri.substr(pos + 1); } if ((uri.find("0.0.0.0:") == 0) && (clientIp.empty() == false)) { // answer with ip that is on same network as client std::string clienturl = getServerIpFromClientIp(inet_addr(clientIp.c_str())); clienturl += uri.substr(uri.find_first_of(':')); uri = clienturl; } srv.uri = protocol + ":" + uri; if (!credentials.empty()) { pos = credentials.find(':'); if (pos == std::string::npos) { srv.username = credentials; } else { srv.username = credentials.substr(0, pos); srv.password = credentials.substr(pos + 1); } } } return srv; } std::unique_ptr<webrtc::VideoEncoderFactory> CreateEncoderFactory(bool nullCodec) { std::unique_ptr<webrtc::VideoEncoderFactory> factory; if (nullCodec) { factory = std::make_unique<VideoEncoderFactory>(); } else { factory = webrtc::CreateBuiltinVideoEncoderFactory(); } return factory; } std::unique_ptr<webrtc::VideoDecoderFactory> CreateDecoderFactory(bool nullCodec) { std::unique_ptr<webrtc::VideoDecoderFactory> factory; if (nullCodec) { factory = std::make_unique<VideoDecoderFactory>(); } else { factory = webrtc::CreateBuiltinVideoDecoderFactory(); } return factory; } webrtc::PeerConnectionFactoryDependencies CreatePeerConnectionFactoryDependencies(rtc::Thread* signalingThread, rtc::Thread* workerThread, rtc::scoped_refptr<webrtc::AudioDeviceModule> audioDeviceModule, rtc::scoped_refptr<webrtc::AudioDecoderFactory> audioDecoderfactory, bool useNullCodec) { webrtc::PeerConnectionFactoryDependencies dependencies; dependencies.network_thread = NULL; dependencies.worker_thread = workerThread; dependencies.signaling_thread = signalingThread; dependencies.task_queue_factory = webrtc::CreateDefaultTaskQueueFactory(); dependencies.event_log_factory = absl::make_unique<webrtc::RtcEventLogFactory>(dependencies.task_queue_factory.get()); dependencies.adm = std::move(audioDeviceModule); dependencies.audio_encoder_factory = webrtc::CreateBuiltinAudioEncoderFactory(); dependencies.audio_decoder_factory = std::move(audioDecoderfactory); dependencies.audio_processing = webrtc::AudioProcessingBuilder().Create(); dependencies.video_encoder_factory = CreateEncoderFactory(useNullCodec); dependencies.video_decoder_factory = CreateDecoderFactory(useNullCodec); webrtc::EnableMedia(dependencies); return dependencies; } std::string getParam(const char *queryString, const char *paramName) { std::string value; if (queryString) { CivetServer::getParam(queryString, paramName, value); } return value; } /* --------------------------------------------------------------------------- ** Constructor ** -------------------------------------------------------------------------*/ PeerConnectionManager::PeerConnectionManager(const std::list<std::string> &iceServerList, const Json::Value & config, const webrtc::AudioDeviceModule::AudioLayer audioLayer, const std::string &publishFilter, const std::string & webrtcUdpPortRange, bool useNullCodec, bool usePlanB, int maxpc, webrtc::PeerConnectionInterface::IceTransportsType transportType, const std::string & basePath) : m_signalingThread(rtc::Thread::Create()), m_workerThread(rtc::Thread::Create()), m_audioDecoderfactory(webrtc::CreateBuiltinAudioDecoderFactory()), m_task_queue_factory(webrtc::CreateDefaultTaskQueueFactory()), m_video_decoder_factory(CreateDecoderFactory(useNullCodec)), m_iceServerList(iceServerList), m_config(config), m_publishFilter(publishFilter), m_webrtcPortRange(webrtcUdpPortRange), m_useNullCodec(useNullCodec), m_usePlanB(usePlanB), m_maxpc(maxpc), m_transportType(transportType) { m_workerThread->SetName("worker", NULL); m_workerThread->Start(); m_workerThread->BlockingCall([this, audioLayer] { this->createAudioModule(audioLayer); }); m_signalingThread->SetName("signaling", NULL); m_signalingThread->Start(); m_peer_connection_factory = webrtc::CreateModularPeerConnectionFactory(CreatePeerConnectionFactoryDependencies(m_signalingThread.get(), m_workerThread.get(), m_audioDeviceModule, m_audioDecoderfactory, useNullCodec)); // build video audio map m_videoaudiomap = getV4l2AlsaMap(); // register api in http server m_func[basePath + "/api/getMediaList"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { return std::make_tuple(200, std::map<std::string,std::string>(),this->getMediaList()); }; m_func[basePath + "/api/getVideoDeviceList"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { return std::make_tuple(200, std::map<std::string,std::string>(),this->getVideoDeviceList()); }; m_func[basePath + "/api/getAudioDeviceList"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { return std::make_tuple(200, std::map<std::string,std::string>(),this->getAudioDeviceList()); }; m_func[basePath + "/api/getAudioPlayoutList"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { return std::make_tuple(200, std::map<std::string,std::string>(),this->getAudioPlayoutList()); }; m_func[basePath + "/api/getIceServers"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { return std::make_tuple(200, std::map<std::string,std::string>(),this->getIceServers(req_info->remote_addr)); }; m_func[basePath + "/api/call"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { std::string peerid = getParam(req_info->query_string, "peerid"); std::string url = getParam(req_info->query_string, "url"); std::string audiourl = getParam(req_info->query_string, "audiourl"); std::string options = getParam(req_info->query_string, "options"); return std::make_tuple(200, std::map<std::string,std::string>(),this->call(peerid, url, audiourl, options, in)); }; m_func[basePath + "/api/whep"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { std::string peerid = getParam(req_info->query_string, "peerid"); std::string videourl = getParam(req_info->query_string, "url"); std::string audiourl = getParam(req_info->query_string, "audiourl"); std::string options = getParam(req_info->query_string, "options"); std::string url(req_info->request_uri); url.append("?").append(req_info->query_string); return this->whep(req_info->request_method, url, peerid, videourl, audiourl, options, in); }; m_func[basePath + "/api/hangup"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { std::string peerid = getParam(req_info->query_string, "peerid"); return std::make_tuple(200, std::map<std::string,std::string>(),this->hangUp(peerid)); }; m_func[basePath + "/api/createOffer"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { std::string peerid = getParam(req_info->query_string, "peerid"); std::string url = getParam(req_info->query_string, "url"); std::string audiourl = getParam(req_info->query_string, "audiourl"); std::string options = getParam(req_info->query_string, "options"); return std::make_tuple(200, std::map<std::string,std::string>(),this->createOffer(peerid, url, audiourl, options)); }; m_func[basePath + "/api/setAnswer"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { std::string peerid = getParam(req_info->query_string, "peerid"); return std::make_tuple(200, std::map<std::string,std::string>(),this->setAnswer(peerid, in)); }; m_func[basePath + "/api/getIceCandidate"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { std::string peerid = getParam(req_info->query_string, "peerid"); return std::make_tuple(200, std::map<std::string,std::string>(),this->getIceCandidateList(peerid)); }; m_func[basePath + "/api/addIceCandidate"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { std::string peerid = getParam(req_info->query_string, "peerid"); return std::make_tuple(200, std::map<std::string,std::string>(),this->addIceCandidate(peerid, in)); }; m_func[basePath + "/api/getPeerConnectionList"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { return std::make_tuple(200, std::map<std::string,std::string>(),this->getPeerConnectionList()); }; m_func[basePath + "/api/getStreamList"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { return std::make_tuple(200, std::map<std::string,std::string>(),this->getStreamList()); }; m_func[basePath + "/api/version"] = [](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { Json::Value answer(VERSION); return std::make_tuple(200, std::map<std::string,std::string>(), answer); }; m_func[basePath + "/api/log"] = [](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { std::string loglevel = getParam(req_info->query_string, "level"); if (!loglevel.empty()) { rtc::LogMessage::LogToDebug((rtc::LoggingSeverity)atoi(loglevel.c_str())); } Json::Value answer(rtc::LogMessage::GetLogToDebug()); return std::make_tuple(200, std::map<std::string,std::string>(), answer); }; m_func[basePath + "/api/help"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> HttpServerRequestHandler::httpFunctionReturn { Json::Value answer(Json::ValueType::arrayValue); for (auto it : m_func) { answer.append(it.first); } return std::make_tuple(200, std::map<std::string,std::string>(), answer); }; } /* --------------------------------------------------------------------------- ** Destructor ** -------------------------------------------------------------------------*/ PeerConnectionManager::~PeerConnectionManager() { m_workerThread->BlockingCall([this] { m_audioDeviceModule->Release(); }); } // from https://stackoverflow.com/a/12468109/3102264 std::string random_string( size_t length ) { auto randchar = []() -> char { const char charset[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; const size_t max_index = (sizeof(charset) - 1); return charset[ rand() % max_index ]; }; std::string str(length,0); std::generate_n( str.begin(), length, randchar ); return str; } std::tuple<int, std::map<std::string,std::string>,Json::Value> PeerConnectionManager::whep(const std::string & method, const std::string & url, const std::string & requestPeerId, const std::string & videourl, const std::string & audiourl, const std::string & options, const Json::Value &in) { int httpcode = 501; std::string locationurl(url); std::string peerid(requestPeerId); if (peerid.empty()) { peerid = random_string(32); locationurl.append("&").append("peerid=").append(peerid); } std::map<std::string,std::string> headers; std::string answersdp; if (method == "DELETE") { this->hangUp(peerid); } else if (method == "PATCH") { RTC_LOG(LS_INFO) << "PATCH\n" << in.asString(); std::istringstream is(in.asString()); std::string str; std::string mid; while(std::getline(is,str)) { str.erase(std::remove(str.begin(), str.end(), '\r'), str.end()); if (strstr(str.c_str(),"a=mid:")) { mid = str.substr(strlen("a=mid:")); } else if (strstr(str.c_str(),"a=candidate")) { std::string sdp = str.substr(strlen("a=")); std::unique_ptr<webrtc::IceCandidateInterface> candidate(webrtc::CreateIceCandidate(mid, 0, sdp, NULL)); if (!candidate.get()) { RTC_LOG(LS_WARNING) << "Can't parse received candidate message."; } else { std::lock_guard<std::mutex> peerlock(m_peerMapMutex); rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = this->getPeerConnection(peerid); if (peerConnection) { if (!peerConnection->AddIceCandidate(candidate.get())) { RTC_LOG(LS_WARNING) << "Failed to apply the received candidate"; } else { httpcode = 200; } } } } else if (strstr(str.c_str(),"a=end-of-candidates")) { RTC_LOG(LS_INFO) << "end of candidate"; httpcode = 200; } } } else { std::string offersdp(in.asString()); RTC_LOG(LS_WARNING) << "offer:" << offersdp; std::unique_ptr<webrtc::SessionDescriptionInterface> desc = this->getAnswer(peerid, offersdp, videourl, audiourl, options, true); if (desc.get()) { desc->ToString(&answersdp); headers["Location"] = locationurl; headers["Access-Control-Expose-Headers"] = "Location"; headers["Content-Type"] = "application/sdp"; httpcode = 201; } else { RTC_LOG(LS_ERROR) << "Failed to create answer - no SDP"; } RTC_LOG(LS_WARNING) << "anwser:" << answersdp; } return std::make_tuple(httpcode, headers, answersdp); } void PeerConnectionManager::createAudioModule(webrtc::AudioDeviceModule::AudioLayer audioLayer) { #ifdef HAVE_SOUND m_audioDeviceModule = webrtc::AudioDeviceModule::Create(audioLayer, m_task_queue_factory.get()); if (m_audioDeviceModule->Init() != 0) { RTC_LOG(LS_WARNING) << "audio init fails -> disable audio capture"; m_audioDeviceModule = new webrtc::FakeAudioDeviceModule(); } #else m_audioDeviceModule = new webrtc::FakeAudioDeviceModule(); #endif } /* --------------------------------------------------------------------------- ** return deviceList as JSON vector ** -------------------------------------------------------------------------*/ const Json::Value PeerConnectionManager::getMediaList() { Json::Value value(Json::arrayValue); const std::list<std::string> videoCaptureDevice = CapturerFactory::GetVideoCaptureDeviceList(m_publishFilter, m_useNullCodec); for (auto videoDevice : videoCaptureDevice) { Json::Value media; media["video"] = videoDevice; std::map<std::string, std::string>::iterator it = m_videoaudiomap.find(videoDevice); if (it != m_videoaudiomap.end()) { media["audio"] = it->second; } value.append(media); } const std::list<std::string> videoList = CapturerFactory::GetVideoSourceList(m_publishFilter, m_useNullCodec); for (auto videoSource : videoList) { Json::Value media; media["video"] = videoSource; value.append(media); } for( auto it = m_config.begin() ; it != m_config.end() ; it++ ) { std::string name = it.key().asString(); Json::Value media(*it); if (media.isMember("video")) { media["video"]=name; } if (media.isMember("audio")) { media["audio"]=name; } value.append(media); } return value; } /* --------------------------------------------------------------------------- ** return video device List as JSON vector ** -------------------------------------------------------------------------*/ const Json::Value PeerConnectionManager::getVideoDeviceList() { Json::Value value(Json::arrayValue); const std::list<std::string> videoCaptureDevice = CapturerFactory::GetVideoCaptureDeviceList(m_publishFilter, m_useNullCodec); for (auto videoDevice : videoCaptureDevice) { value.append(videoDevice); } return value; } /* --------------------------------------------------------------------------- ** return audio device List as JSON vector ** -------------------------------------------------------------------------*/ const Json::Value PeerConnectionManager::getAudioDeviceList() { Json::Value value(Json::arrayValue); const std::list<std::string> audioCaptureDevice = CapturerFactory::GetAudioCaptureDeviceList(m_publishFilter, m_audioDeviceModule); for (auto audioDevice : audioCaptureDevice) { value.append(audioDevice); } return value; } const Json::Value PeerConnectionManager::getAudioPlayoutList() { Json::Value value(Json::arrayValue); const std::list<std::string> audioPlayoutDevice = CapturerFactory::GetAudioPlayoutDeviceList(m_publishFilter, m_audioDeviceModule); for (auto audioDevice : audioPlayoutDevice) { value.append(audioDevice); } return value; } /* --------------------------------------------------------------------------- ** return iceServers as JSON vector ** -------------------------------------------------------------------------*/ const Json::Value PeerConnectionManager::getIceServers(const std::string &clientIp) { Json::Value urls(Json::arrayValue); for (auto iceServer : m_iceServerList) { Json::Value server; Json::Value urlList(Json::arrayValue); webrtc::PeerConnectionInterface::IceServer srv = getIceServerFromUrl(iceServer, clientIp); RTC_LOG(LS_INFO) << "ICE URL:" << srv.uri; if (srv.uri.find("turn:") == 0) { urlList.append(srv.uri+"?transport=udp"); urlList.append(srv.uri+"?transport=tcp"); } else { urlList.append(srv.uri); } server["urls"] = urlList; if (srv.username.length() > 0) server["username"] = srv.username; if (srv.password.length() > 0) server["credential"] = srv.password; urls.append(server); } Json::Value iceServers; iceServers["iceServers"] = urls; if (m_transportType == webrtc::PeerConnectionInterface::IceTransportsType::kRelay) { iceServers["iceTransportPolicy"] = "relay"; } else { iceServers["iceTransportPolicy"] = "all"; } return iceServers; } /* --------------------------------------------------------------------------- ** get PeerConnection associated with peerid ** -------------------------------------------------------------------------*/ rtc::scoped_refptr<webrtc::PeerConnectionInterface> PeerConnectionManager::getPeerConnection(const std::string &peerid) { rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection; std::map<std::string, PeerConnectionObserver *>::iterator it = m_peer_connectionobs_map.find(peerid); if (it != m_peer_connectionobs_map.end()) { peerConnection = it->second->getPeerConnection(); } return peerConnection; } /* --------------------------------------------------------------------------- ** add ICE candidate to a PeerConnection ** -------------------------------------------------------------------------*/ const Json::Value PeerConnectionManager::addIceCandidate(const std::string &peerid, const Json::Value &jmessage) { bool result = false; std::string sdp_mid; int sdp_mlineindex = 0; std::string sdp; if (!rtc::GetStringFromJsonObject(jmessage, kCandidateSdpMidName, &sdp_mid) || !rtc::GetIntFromJsonObject(jmessage, kCandidateSdpMlineIndexName, &sdp_mlineindex) || !rtc::GetStringFromJsonObject(jmessage, kCandidateSdpName, &sdp)) { RTC_LOG(LS_WARNING) << "Can't parse received message:" << jmessage; } else { std::unique_ptr<webrtc::IceCandidateInterface> candidate(webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, sdp, NULL)); if (!candidate.get()) { RTC_LOG(LS_WARNING) << "Can't parse received candidate message."; } else { std::lock_guard<std::mutex> peerlock(m_peerMapMutex); rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = this->getPeerConnection(peerid); if (peerConnection) { if (!peerConnection->AddIceCandidate(candidate.get())) { RTC_LOG(LS_WARNING) << "Failed to apply the received candidate"; } else { result = true; } } } } Json::Value answer; if (result) { answer = result; } return answer; } /* --------------------------------------------------------------------------- ** create an offer for a call ** -------------------------------------------------------------------------*/ const Json::Value PeerConnectionManager::createOffer(const std::string &peerid, const std::string &videourl, const std::string &audiourl, const std::string &options) { RTC_LOG(LS_INFO) << __FUNCTION__ << " video:" << videourl << " audio:" << audiourl << " options:" << options; Json::Value offer; PeerConnectionObserver *peerConnectionObserver = this->CreatePeerConnection(peerid); if (!peerConnectionObserver) { RTC_LOG(LS_ERROR) << "Failed to initialize PeerConnection"; } else { rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = peerConnectionObserver->getPeerConnection(); if (!this->AddStreams(peerConnection.get(), videourl, audiourl, options)) { RTC_LOG(LS_WARNING) << "Can't add stream"; } // register peerid { std::lock_guard<std::mutex> peerlock(m_peerMapMutex); m_peer_connectionobs_map.insert(std::pair<std::string, PeerConnectionObserver *>(peerid, peerConnectionObserver)); } // ask to create offer webrtc::PeerConnectionInterface::RTCOfferAnswerOptions rtcoptions; rtcoptions.offer_to_receive_video = 0; rtcoptions.offer_to_receive_audio = 0; std::promise<const webrtc::SessionDescriptionInterface *> localpromise; rtc::scoped_refptr<CreateSessionDescriptionObserver> localSessionObserver(CreateSessionDescriptionObserver::Create(peerConnection, localpromise)); peerConnection->CreateOffer(localSessionObserver.get(), rtcoptions); // waiting for offer std::future<const webrtc::SessionDescriptionInterface *> future = localpromise.get_future(); if (future.wait_for(std::chrono::milliseconds(5000)) == std::future_status::ready) { // answer with the created offer const webrtc::SessionDescriptionInterface *desc = future.get(); if (desc) { std::string sdp; desc->ToString(&sdp); offer[kSessionDescriptionTypeName] = desc->type(); offer[kSessionDescriptionSdpName] = sdp; } else { RTC_LOG(LS_ERROR) << "Failed to create offer - no session"; } } else { localSessionObserver->cancel(); RTC_LOG(LS_ERROR) << "Failed to create offer - timeout"; } } return offer; } /* --------------------------------------------------------------------------- ** set answer to a call initiated by createOffer ** -------------------------------------------------------------------------*/ const Json::Value PeerConnectionManager::setAnswer(const std::string &peerid, const Json::Value &jmessage) { RTC_LOG(LS_INFO) << jmessage; Json::Value answer; std::string type; std::string sdp; if (!rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionTypeName, &type) || !rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionSdpName, &sdp)) { RTC_LOG(LS_WARNING) << "Can't parse received message."; answer["error"] = "Can't parse received message."; } else { webrtc::SessionDescriptionInterface *session_description(webrtc::CreateSessionDescription(type, sdp, NULL)); if (!session_description) { RTC_LOG(LS_WARNING) << "Can't parse received session description message."; answer["error"] = "Can't parse received session description message."; } else { RTC_LOG(LS_ERROR) << "From peerid:" << peerid << " received session description :" << session_description->type(); std::lock_guard<std::mutex> peerlock(m_peerMapMutex); rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = this->getPeerConnection(peerid); if (peerConnection) { std::promise<const webrtc::SessionDescriptionInterface *> remotepromise; rtc::scoped_refptr<SetSessionDescriptionObserver> remoteSessionObserver(SetSessionDescriptionObserver::Create(peerConnection, remotepromise)); peerConnection->SetRemoteDescription(remoteSessionObserver.get(), session_description); // waiting for remote description std::future<const webrtc::SessionDescriptionInterface *> remotefuture = remotepromise.get_future(); if (remotefuture.wait_for(std::chrono::milliseconds(5000)) == std::future_status::ready) { RTC_LOG(LS_INFO) << "remote_description is ready"; const webrtc::SessionDescriptionInterface *desc = remotefuture.get(); if (desc) { std::string sdp; desc->ToString(&sdp); answer[kSessionDescriptionTypeName] = desc->type(); answer[kSessionDescriptionSdpName] = sdp; } else { answer["error"] = "Can't get remote description."; } } else { remoteSessionObserver->cancel(); RTC_LOG(LS_WARNING) << "Can't get remote description."; answer["error"] = "Can't get remote description."; } } } } return answer; } std::unique_ptr<webrtc::SessionDescriptionInterface> PeerConnectionManager::getAnswer(const std::string & peerid, const std::string& sdpoffer, const std::string & videourl, const std::string & audiourl, const std::string & options, bool waitgatheringcompletion) { std::unique_ptr<webrtc::SessionDescriptionInterface> answer; webrtc::SessionDescriptionInterface *session_description(webrtc::CreateSessionDescription(webrtc::SessionDescriptionInterface::kOffer, sdpoffer, NULL)); if (!session_description) { RTC_LOG(LS_WARNING) << "Can't parse received session description message."; } else { answer = this->getAnswer(peerid, session_description, videourl, audiourl, options, waitgatheringcompletion); } return answer; } std::unique_ptr<webrtc::SessionDescriptionInterface> PeerConnectionManager::getAnswer(const std::string & peerid, webrtc::SessionDescriptionInterface *session_description, const std::string & videourl, const std::string & audiourl, const std::string & options, bool waitgatheringcompletion) { std::unique_ptr<webrtc::SessionDescriptionInterface> answer; PeerConnectionObserver *peerConnectionObserver = this->CreatePeerConnection(peerid); if (!peerConnectionObserver) { RTC_LOG(LS_ERROR) << "Failed to initialize PeerConnectionObserver"; } else if (!peerConnectionObserver->getPeerConnection().get()) { RTC_LOG(LS_ERROR) << "Failed to initialize PeerConnection"; delete peerConnectionObserver; } else { rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = peerConnectionObserver->getPeerConnection(); RTC_LOG(LS_INFO) << "nbStreams local:" << peerConnection->GetSenders().size() << " remote:" << peerConnection->GetReceivers().size() << " localDescription:" << peerConnection->local_description(); // register peerid { std::lock_guard<std::mutex> peerlock(m_peerMapMutex); m_peer_connectionobs_map.insert(std::pair<std::string, PeerConnectionObserver *>(peerid, peerConnectionObserver)); } // add local stream if (!this->AddStreams(peerConnection.get(), videourl, audiourl, options)) { RTC_LOG(LS_WARNING) << "Can't add stream"; } // set remote offer std::promise<const webrtc::SessionDescriptionInterface *> remotepromise; rtc::scoped_refptr<SetSessionDescriptionObserver> remoteSessionObserver(SetSessionDescriptionObserver::Create(peerConnection, remotepromise)); peerConnection->SetRemoteDescription(remoteSessionObserver.get(), session_description); // waiting for remote description std::future<const webrtc::SessionDescriptionInterface *> remotefuture = remotepromise.get_future(); if (remotefuture.wait_for(std::chrono::milliseconds(5000)) == std::future_status::ready) { RTC_LOG(LS_INFO) << "remote_description is ready"; } else { remoteSessionObserver->cancel(); RTC_LOG(LS_WARNING) << "remote_description is NULL"; } // create answer webrtc::PeerConnectionInterface::RTCOfferAnswerOptions rtcoptions; std::promise<const webrtc::SessionDescriptionInterface *> localpromise; rtc::scoped_refptr<CreateSessionDescriptionObserver> localSessionObserver(CreateSessionDescriptionObserver::Create(peerConnection, localpromise)); peerConnection->CreateAnswer(localSessionObserver.get(), rtcoptions); // wait gathering completion if (waitgatheringcompletion) { int retry = 5; while ( (peerConnectionObserver->getGatheringState() != webrtc::PeerConnectionInterface::IceGatheringState::kIceGatheringComplete) && (retry > 0) ) { RTC_LOG(LS_ERROR) << "waiting..." << retry; retry --; std::this_thread::sleep_for(std::chrono::milliseconds(250)); } } // waiting for answer std::future<const webrtc::SessionDescriptionInterface *> localfuture = localpromise.get_future(); if (localfuture.wait_for(std::chrono::milliseconds(5000)) == std::future_status::ready) { const webrtc::SessionDescriptionInterface *desc = localfuture.get(); if (desc) { answer = desc->Clone(); } else { RTC_LOG(LS_ERROR) << "Failed to create answer - no SDP"; } } else { RTC_LOG(LS_ERROR) << "Failed to create answer - timeout"; localSessionObserver->cancel(); } } return answer; } /* --------------------------------------------------------------------------- ** auto-answer to a call ** -------------------------------------------------------------------------*/ const Json::Value PeerConnectionManager::call(const std::string &peerid, const std::string &videourl, const std::string &audiourl, const std::string &options, const Json::Value &jmessage) { RTC_LOG(LS_INFO) << __FUNCTION__ << " video:" << videourl << " audio:" << audiourl << " options:" << options; Json::Value answer; std::string type; std::string sdp; if (!rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionTypeName, &type) || !rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionSdpName, &sdp)) { RTC_LOG(LS_WARNING) << "Can't parse received message."; } else { std::unique_ptr<webrtc::SessionDescriptionInterface> desc = this->getAnswer(peerid, sdp, videourl, audiourl, options); if (desc.get()) { std::string sdp; desc->ToString(&sdp); answer[kSessionDescriptionTypeName] = desc->type(); answer[kSessionDescriptionSdpName] = sdp; } else { RTC_LOG(LS_ERROR) << "Failed to create answer - no SDP"; } } return answer; } bool PeerConnectionManager::streamStillUsed(const std::string &streamLabel) { bool stillUsed = false; for (auto it : m_peer_connectionobs_map) { rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = it.second->getPeerConnection(); std::vector<rtc::scoped_refptr<webrtc::RtpSenderInterface>> localstreams = peerConnection->GetSenders(); for (auto stream : localstreams) { std::vector<std::string> streamVector = stream->stream_ids(); if (streamVector.size() > 0) { if (streamVector[0] == streamLabel) { stillUsed = true; break; } } } } return stillUsed; } /* --------------------------------------------------------------------------- ** hangup a call ** -------------------------------------------------------------------------*/ const Json::Value PeerConnectionManager::hangUp(const std::string &peerid) { bool result = false; RTC_LOG(LS_INFO) << __FUNCTION__ << " " << peerid; PeerConnectionObserver *pcObserver = NULL; { std::lock_guard<std::mutex> peerlock(m_peerMapMutex); std::map<std::string, PeerConnectionObserver *>::iterator it = m_peer_connectionobs_map.find(peerid); if (it != m_peer_connectionobs_map.end()) { pcObserver = it->second; RTC_LOG(LS_ERROR) << "Remove PeerConnection peerid:" << peerid; m_peer_connectionobs_map.erase(it); } if (pcObserver) { rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = pcObserver->getPeerConnection(); std::vector<rtc::scoped_refptr<webrtc::RtpSenderInterface>> localstreams = peerConnection->GetSenders(); for (auto stream : localstreams) { std::vector<std::string> streamVector = stream->stream_ids(); if (streamVector.size() > 0) { std::string streamLabel = streamVector[0]; bool stillUsed = this->streamStillUsed(streamLabel); if (!stillUsed) { RTC_LOG(LS_ERROR) << "hangUp stream is no more used " << streamLabel; std::lock_guard<std::mutex> mlock(m_streamMapMutex); std::map<std::string, std::pair<rtc::scoped_refptr<webrtc::VideoTrackSourceInterface>, rtc::scoped_refptr<webrtc::AudioSourceInterface>>>::iterator it = m_stream_map.find(streamLabel); if (it != m_stream_map.end()) { m_stream_map.erase(it); } RTC_LOG(LS_ERROR) << "hangUp stream closed " << streamLabel; } peerConnection->RemoveTrackOrError(stream); } } delete pcObserver; result = true; } } Json::Value answer; if (result) { answer = result; } RTC_LOG(LS_INFO) << __FUNCTION__ << " " << peerid << " result:" << result; return answer; } /* --------------------------------------------------------------------------- ** get list ICE candidate associayed with a PeerConnection ** -------------------------------------------------------------------------*/ const Json::Value PeerConnectionManager::getIceCandidateList(const std::string &peerid) { RTC_LOG(LS_INFO) << __FUNCTION__; Json::Value value; std::lock_guard<std::mutex> peerlock(m_peerMapMutex); std::map<std::string, PeerConnectionObserver *>::iterator it = m_peer_connectionobs_map.find(peerid); if (it != m_peer_connectionobs_map.end()) { PeerConnectionObserver *obs = it->second; if (obs) { value = obs->getIceCandidateList(); } else { RTC_LOG(LS_ERROR) << "No observer for peer:" << peerid; } } return value; } /* --------------------------------------------------------------------------- ** get PeerConnection list ** -------------------------------------------------------------------------*/ const Json::Value PeerConnectionManager::getPeerConnectionList() { Json::Value value(Json::arrayValue); std::lock_guard<std::mutex> peerlock(m_peerMapMutex); for (auto it : m_peer_connectionobs_map) { Json::Value content; // get local SDP rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = it.second->getPeerConnection(); if ((peerConnection) && (peerConnection->local_description())) { content["pc_state"] = std::string(webrtc::PeerConnectionInterface::AsString(peerConnection->peer_connection_state())); content["signaling_state"] = std::string(webrtc::PeerConnectionInterface::AsString(peerConnection->signaling_state())); content["ice_state"] = std::string(webrtc::PeerConnectionInterface::AsString(peerConnection->ice_connection_state())); std::string sdp; peerConnection->local_description()->ToString(&sdp); content["sdp"] = sdp; content["candidateList"] = it.second->getIceCandidateList(); Json::Value streams; std::vector<rtc::scoped_refptr<webrtc::RtpSenderInterface>> localstreams = peerConnection->GetSenders(); for (auto localStream : localstreams) { if (localStream != NULL) { rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> mediaTrack = localStream->track(); if (mediaTrack) { Json::Value track; track["kind"] = mediaTrack->kind(); if (track["kind"] == "video") { webrtc::VideoTrackInterface* videoTrack = (webrtc::VideoTrackInterface*)mediaTrack.get(); webrtc::VideoTrackSourceInterface::Stats stats; if (videoTrack->GetSource()) { track["state"] = videoTrack->GetSource()->state(); if (videoTrack->GetSource()->GetStats(&stats)) { track["width"] = stats.input_width; track["height"] = stats.input_height; } } } else if (track["kind"] == "audio") { webrtc::AudioTrackInterface* audioTrack = (webrtc::AudioTrackInterface*)mediaTrack.get(); if (audioTrack->GetSource()) { track["state"] = audioTrack->GetSource()->state(); } int level = 0; if (audioTrack->GetSignalLevel(&level)) { track["level"] = level; } } std::string streamLabel = localStream->stream_ids()[0]; if (!streams.isMember(streamLabel)) { streams[streamLabel] = Json::Value(Json::objectValue); } streams[streamLabel][mediaTrack->id()] = track; } } } content["streams"] = streams; } Json::Value pc; pc[it.first] = content; value.append(pc); } return value; } /* --------------------------------------------------------------------------- ** get StreamList list ** -------------------------------------------------------------------------*/ const Json::Value PeerConnectionManager::getStreamList() { std::lock_guard<std::mutex> mlock(m_streamMapMutex); Json::Value value(Json::arrayValue); for (auto it : m_stream_map) { value.append(it.first); } return value; } /* --------------------------------------------------------------------------- ** check if factory is initialized ** -------------------------------------------------------------------------*/ bool PeerConnectionManager::InitializePeerConnection() { return (m_peer_connection_factory.get() != NULL); } /* --------------------------------------------------------------------------- ** get oldest PeerConnection ** -------------------------------------------------------------------------*/ std::string PeerConnectionManager::getOldestPeerCannection() { uint64_t oldestpc = std::numeric_limits<uint64_t>::max(); std::string oldestpeerid; std::lock_guard<std::mutex> peerlock(m_peerMapMutex); if ( (m_maxpc > 0) && (m_peer_connectionobs_map.size() >= m_maxpc) ) { for (auto it : m_peer_connectionobs_map) { uint64_t creationTime = it.second->getCreationTime(); if (creationTime < oldestpc) { oldestpc = creationTime; oldestpeerid = it.second->getPeerId(); } } } return oldestpeerid; } /* --------------------------------------------------------------------------- ** create a new PeerConnection ** -------------------------------------------------------------------------*/ PeerConnectionManager::PeerConnectionObserver *PeerConnectionManager::CreatePeerConnection(const std::string &peerid) { std::string oldestpeerid = this->getOldestPeerCannection(); if (!oldestpeerid.empty()) { this->hangUp(oldestpeerid); } webrtc::PeerConnectionInterface::RTCConfiguration config; if (m_usePlanB) { config.sdp_semantics = webrtc::SdpSemantics::kPlanB; } else { config.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan; } for (auto iceServer : m_iceServerList) { webrtc::PeerConnectionInterface::IceServer server = getIceServerFromUrl(iceServer); config.servers.push_back(server); } config.type = m_transportType; // Use example From https://soru.site/questions/51578447/api-c-webrtcyi-kullanarak-peerconnection-ve-ucretsiz-baglant-noktasn-serbest-nasl int minPort = 0; int maxPort = 65535; std::istringstream is(m_webrtcPortRange); std::string port; if (std::getline(is, port, ':')) { minPort = std::stoi(port); if (std::getline(is, port, ':')) { maxPort = std::stoi(port); } } config.port_allocator_config.min_port = minPort; config.port_allocator_config.max_port = maxPort; RTC_LOG(LS_INFO) << __FUNCTION__ << "CreatePeerConnection peerid:" << peerid << " webrtcPortRange:" << minPort << ":" << maxPort; PeerConnectionObserver *obs = new PeerConnectionObserver(this, peerid, config); if (!obs) { RTC_LOG(LS_ERROR) << __FUNCTION__ << "CreatePeerConnection failed"; } return obs; } /* --------------------------------------------------------------------------- ** get the capturer from its URL ** -------------------------------------------------------------------------*/ rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> PeerConnectionManager::CreateVideoSource(const std::string &videourl, const std::map<std::string, std::string> &opts) { RTC_LOG(LS_INFO) << "videourl:" << videourl; return CapturerFactory::CreateVideoSource(videourl, opts, m_publishFilter, m_peer_connection_factory, m_video_decoder_factory); } rtc::scoped_refptr<webrtc::AudioSourceInterface> PeerConnectionManager::CreateAudioSource(const std::string &audiourl, const std::map<std::string, std::string> &opts) { RTC_LOG(LS_INFO) << "audiourl:" << audiourl; return m_workerThread->BlockingCall([this, audiourl, opts] { return CapturerFactory::CreateAudioSource(audiourl, opts, m_publishFilter, m_peer_connection_factory, m_audioDecoderfactory, m_audioDeviceModule); }); } const std::string PeerConnectionManager::sanitizeLabel(const std::string &label) { std::string out(label); // conceal labels that contain rtsp URL to prevent sensitive data leaks. if (label.find("rtsp:") != std::string::npos) { std::hash<std::string> hash_fn; size_t hash = hash_fn(out); return std::to_string(hash); } out.erase(std::remove_if(out.begin(), out.end(), ignoreInLabel), out.end()); return out; } /* --------------------------------------------------------------------------- ** Add a stream to a PeerConnection ** -------------------------------------------------------------------------*/ bool PeerConnectionManager::AddStreams(webrtc::PeerConnectionInterface *peer_connection, const std::string &videourl, const std::string &audiourl, const std::string &options) { bool ret = false; // compute options std::string optstring = options; if (m_config.isMember(videourl)) { std::string urlopts = m_config[videourl]["options"].asString(); if (options.empty()) { optstring = urlopts; } else if (options.find_first_of("&")==0) { optstring = urlopts + options; } else { optstring = options; } } // convert options string into map std::istringstream is(optstring); std::map<std::string, std::string> opts; std::string key, value; while (std::getline(std::getline(is, key, '='), value, '&')) { opts[key] = value; } std::string video = videourl; if (m_config.isMember(video)) { video = m_config[video]["video"].asString(); } std::string audio = audiourl; if (m_config.isMember(audio)) { audio = m_config[audio]["audio"].asString(); } // set bandwidth if (opts.find("bitrate") != opts.end()) { int bitrate = std::stoi(opts.at("bitrate")); webrtc::BitrateSettings bitrateParam; bitrateParam.min_bitrate_bps = absl::optional<int>(bitrate / 2); bitrateParam.start_bitrate_bps = absl::optional<int>(bitrate); bitrateParam.max_bitrate_bps = absl::optional<int>(bitrate * 2); peer_connection->SetBitrate(bitrateParam); RTC_LOG(LS_WARNING) << "set bitrate:" << bitrate; } // keep capturer options (to improve!!!) std::string optcapturer; if ((video.find("rtsp://") == 0) || (audio.find("rtsp://") == 0)) { if (opts.find("rtptransport") != opts.end()) { optcapturer += opts["rtptransport"]; } if (opts.find("timeout") != opts.end()) { optcapturer += opts["timeout"]; } if (opts.find("width") != opts.end()) { optcapturer += opts["width"]; } if (opts.find("height") != opts.end()) { optcapturer += opts["height"]; } } // compute stream label removing space because SDP use label std::string streamLabel = this->sanitizeLabel(videourl + "|" + audiourl + "|" + optcapturer); bool existingStream = false; { std::lock_guard<std::mutex> mlock(m_streamMapMutex); existingStream = (m_stream_map.find(streamLabel) != m_stream_map.end()); } if (!existingStream) { // need to create the stream rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> videoSource(this->CreateVideoSource(video, opts)); rtc::scoped_refptr<webrtc::AudioSourceInterface> audioSource(this->CreateAudioSource(audio, opts)); RTC_LOG(LS_INFO) << "Adding Stream to map"; std::lock_guard<std::mutex> mlock(m_streamMapMutex); m_stream_map[streamLabel] = std::make_pair(videoSource, audioSource); } // create a new webrtc stream { std::lock_guard<std::mutex> mlock(m_streamMapMutex); std::map<std::string, std::pair<rtc::scoped_refptr<webrtc::VideoTrackSourceInterface>, rtc::scoped_refptr<webrtc::AudioSourceInterface>>>::iterator it = m_stream_map.find(streamLabel); if (it != m_stream_map.end()) { std::pair<rtc::scoped_refptr<webrtc::VideoTrackSourceInterface>, rtc::scoped_refptr<webrtc::AudioSourceInterface>> pair = it->second; rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> videoSource(pair.first); if (!videoSource) { RTC_LOG(LS_ERROR) << "Cannot create capturer video:" << videourl; } else { rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track = m_peer_connection_factory->CreateVideoTrack(videoSource, streamLabel + "_video"); if ((video_track) && (!peer_connection->AddTrack(video_track, {streamLabel}).ok())) { RTC_LOG(LS_ERROR) << "Adding VideoTrack to MediaStream failed"; } else { RTC_LOG(LS_INFO) << "VideoTrack added to PeerConnection"; ret = true; } } rtc::scoped_refptr<webrtc::AudioSourceInterface> audioSource(pair.second); if (!audioSource) { RTC_LOG(LS_ERROR) << "Cannot create capturer audio:" << audio; } else { rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track = m_peer_connection_factory->CreateAudioTrack(streamLabel + "_audio", audioSource.get()); if ((audio_track) && (!peer_connection->AddTrack(audio_track, {streamLabel}).ok())) { RTC_LOG(LS_ERROR) << "Adding AudioTrack to MediaStream failed"; } else { RTC_LOG(LS_INFO) << "AudioTrack added to PeerConnection"; ret = true; } } } else { RTC_LOG(LS_ERROR) << "Cannot find stream"; } } return ret; } /* --------------------------------------------------------------------------- ** ICE callback ** -------------------------------------------------------------------------*/ void PeerConnectionManager::PeerConnectionObserver::OnIceCandidate(const webrtc::IceCandidateInterface *candidate) { RTC_LOG(LS_INFO) << __FUNCTION__ << " " << candidate->sdp_mline_index(); std::string sdp; if (!candidate->ToString(&sdp)) { RTC_LOG(LS_ERROR) << "Failed to serialize candidate"; } else { RTC_LOG(LS_INFO) << sdp; Json::Value jmessage; jmessage[kCandidateSdpMidName] = candidate->sdp_mid(); jmessage[kCandidateSdpMlineIndexName] = candidate->sdp_mline_index(); jmessage[kCandidateSdpName] = sdp; m_iceCandidateList.append(jmessage); } }
2301_81045437/webrtc-streamer
src/PeerConnectionManager.cpp
C++
unlicense
50,943
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** screencapturer.cpp ** ** -------------------------------------------------------------------------*/ #ifdef USE_X11 #include "rtc_base/logging.h" #include "desktopcapturer.h" void DesktopCapturer::OnCaptureResult(webrtc::DesktopCapturer::Result result, std::unique_ptr<webrtc::DesktopFrame> frame) { RTC_LOG(LS_INFO) << "DesktopCapturer:OnCaptureResult"; if (result == webrtc::DesktopCapturer::Result::SUCCESS) { int width = frame->stride() / webrtc::DesktopFrame::kBytesPerPixel; int height = frame->rect().height(); rtc::scoped_refptr<webrtc::I420Buffer> I420buffer = webrtc::I420Buffer::Create(width, height); const int conversionResult = libyuv::ConvertToI420(frame->data(), 0, I420buffer->MutableDataY(), I420buffer->StrideY(), I420buffer->MutableDataU(), I420buffer->StrideU(), I420buffer->MutableDataV(), I420buffer->StrideV(), 0, 0, width, height, I420buffer->width(), I420buffer->height(), libyuv::kRotate0, ::libyuv::FOURCC_ARGB); if (conversionResult >= 0) { webrtc::VideoFrame videoFrame(I420buffer, webrtc::VideoRotation::kVideoRotation_0, rtc::TimeMicros()); if ( (m_height == 0) && (m_width == 0) ) { m_broadcaster.OnFrame(videoFrame); } else { int height = m_height; int width = m_width; if (height == 0) { height = (videoFrame.height() * width) / videoFrame.width(); } else if (width == 0) { width = (videoFrame.width() * height) / videoFrame.height(); } int stride_y = width; int stride_uv = (width + 1) / 2; rtc::scoped_refptr<webrtc::I420Buffer> scaled_buffer = webrtc::I420Buffer::Create(width, height, stride_y, stride_uv, stride_uv); scaled_buffer->ScaleFrom(*videoFrame.video_frame_buffer()->ToI420()); webrtc::VideoFrame frame = webrtc::VideoFrame::Builder() .set_video_frame_buffer(scaled_buffer) .set_rotation(webrtc::kVideoRotation_0) .set_timestamp_us(rtc::TimeMicros()) .build(); m_broadcaster.OnFrame(frame); } } else { RTC_LOG(LS_ERROR) << "DesktopCapturer:OnCaptureResult conversion error:" << conversionResult; } } else { RTC_LOG(LS_ERROR) << "DesktopCapturer:OnCaptureResult capture error:" << (int)result; } } void DesktopCapturer::CaptureThread() { RTC_LOG(LS_INFO) << "DesktopCapturer:Run start"; while (IsRunning()) { m_capturer->CaptureFrame(); } RTC_LOG(LS_INFO) << "DesktopCapturer:Run exit"; } bool DesktopCapturer::Start() { m_isrunning = true; m_capturethread = std::thread(&DesktopCapturer::CaptureThread, this); m_capturer->Start(this); return true; } void DesktopCapturer::Stop() { m_isrunning = false; m_capturethread.join(); } #endif
2301_81045437/webrtc-streamer
src/desktopcapturer.cpp
C++
unlicense
2,958
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** fileaudiocapturer.cpp ** ** -------------------------------------------------------------------------*/ #ifdef HAVE_LIVE555 #include "rtc_base/logging.h" #include "fileaudiocapturer.h" FileAudioSource::FileAudioSource(rtc::scoped_refptr<webrtc::AudioDecoderFactory> audioDecoderFactory, const std::string & uri, const std::map<std::string,std::string> & opts) : LiveAudioSource(audioDecoderFactory, uri, opts, true) { RTC_LOG(LS_INFO) << "FileAudioSource " << uri ; } FileAudioSource::~FileAudioSource() { } #endif
2301_81045437/webrtc-streamer
src/fileaudiocapturer.cpp
C++
unlicense
817
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** filevideocapturer.cpp ** ** -------------------------------------------------------------------------*/ #ifdef HAVE_LIVE555 #include "rtc_base/logging.h" #include "filevideocapturer.h" FileVideoCapturer::FileVideoCapturer(const std::string & uri, const std::map<std::string,std::string> & opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory) : LiveVideoSource(uri, opts, videoDecoderFactory, true) { RTC_LOG(LS_INFO) << "FileVideoCapturer " << uri ; } FileVideoCapturer::~FileVideoCapturer() { } #endif
2301_81045437/webrtc-streamer
src/filevideocapturer.cpp
C++
unlicense
793
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** main.cpp ** ** -------------------------------------------------------------------------*/ #include <signal.h> #include <iostream> #include <fstream> #include "rtc_base/ssl_adapter.h" #include "rtc_base/thread.h" #include "p2p/base/stun_server.h" #include "p2p/base/basic_packet_socket_factory.h" #include "p2p/base/turn_server.h" #include "system_wrappers/include/field_trial.h" #include "PeerConnectionManager.h" #include "HttpServerRequestHandler.h" #if WIN32 #include "getopt.h" #endif PeerConnectionManager* webRtcServer = NULL; void sighandler(int n) { printf("SIGINT\n"); // delete need thread still running delete webRtcServer; webRtcServer = NULL; rtc::Thread::Current()->Quit(); } class TurnAuth : public cricket::TurnAuthInterface { public: virtual bool GetKey(absl::string_view username,absl::string_view realm, std::string* key) { return cricket::ComputeStunCredentialHash(std::string(username), std::string(realm), std::string(username), key); } }; class TurnRedirector : public cricket::TurnRedirectInterface { public: explicit TurnRedirector() {} virtual bool ShouldRedirect(const rtc::SocketAddress &, rtc::SocketAddress *out) { return true; } }; /* --------------------------------------------------------------------------- ** main ** -------------------------------------------------------------------------*/ int main(int argc, char* argv[]) { const char* turnurl = ""; const char* defaultlocalstunurl = "0.0.0.0:3478"; const char* localstunurl = NULL; const char* defaultlocalturnurl = "turn:turn@0.0.0.0:3478"; const char* localturnurl = NULL; const char* stunurl = "stun.l.google.com:19302"; std::string localWebrtcUdpPortRange = "0:65535"; int logLevel = rtc::LS_NONE; const char* webroot = "./html"; std::string basePath; std::string sslCertificate; webrtc::AudioDeviceModule::AudioLayer audioLayer = webrtc::AudioDeviceModule::kPlatformDefaultAudio; std::string nbthreads; std::string passwdFile; std::string authDomain = "mydomain.com"; bool disableXframeOptions = false; std::string publishFilter(".*"); Json::Value config; bool useNullCodec = false; bool usePlanB = false; int maxpc = 0; webrtc::PeerConnectionInterface::IceTransportsType transportType = webrtc::PeerConnectionInterface::IceTransportsType::kAll; std::string webrtcTrialsFields = "WebRTC-FrameDropper/Disabled/"; TurnAuth turnAuth; TurnRedirector turnRedirector; std::string httpAddress("0.0.0.0:"); std::string httpPort = "8000"; const char * port = getenv("PORT"); if (port) { httpPort = port; } httpAddress.append(httpPort); std::string streamName; int c = 0; while ((c = getopt (argc, argv, "hVv::C:" "c:H:w:N:A:D:XB:" "m:I:" "T::t:S::s::R:W:" "a::q:ob" "n:u:U:")) != -1) { switch (c) { case 'H': httpAddress = optarg; break; case 'c': sslCertificate = optarg; break; case 'w': webroot = optarg; break; case 'N': nbthreads = optarg; break; case 'A': passwdFile = optarg; break; case 'D': authDomain = optarg; break; case 'X': disableXframeOptions = true; break; case 'B': basePath = optarg; break; case 'm': maxpc = atoi(optarg); break; case 'I': transportType = (webrtc::PeerConnectionInterface::IceTransportsType)atoi(optarg);break; case 'T': localturnurl = optarg ? optarg : defaultlocalturnurl; turnurl = localturnurl; break; case 't': turnurl = optarg; break; case 'S': localstunurl = optarg ? optarg : defaultlocalstunurl; stunurl = localstunurl; break; case 's': stunurl = optarg ? optarg : defaultlocalstunurl; break; case 'R': localWebrtcUdpPortRange = optarg; break; case 'W': webrtcTrialsFields = optarg; break; case 'a': audioLayer = optarg ? (webrtc::AudioDeviceModule::AudioLayer)atoi(optarg) : webrtc::AudioDeviceModule::kDummyAudio; break; case 'q': publishFilter = optarg ; break; case 'o': useNullCodec = true; break; case 'b': usePlanB = true; break; case 'C': { std::ifstream stream(optarg); stream >> config; break; } case 'n': streamName = optarg; break; case 'u': { if (!streamName.empty()) { config["urls"][streamName]["video"] = optarg; } } break; case 'U': { if (!streamName.empty()) { config["urls"][streamName]["audio"] = optarg; } } break; case 'v': logLevel--; if (optarg) { logLevel-=strlen(optarg); } break; case 'V': std::cout << VERSION << std::endl; exit(0); break; case 'h': default: std::cout << argv[0] << std::endl; std::cout << " General options" << std::endl; std::cout << "\t -v[v[v]] : verbosity" << std::endl; std::cout << "\t -V : print version" << std::endl; std::cout << "\t -C config.json : load urls from JSON config file" << std::endl; std::cout << "\t -n name -u videourl -U audiourl : register a stream with name using url" << std::endl; std::cout << "\t [url] : url to register in the source list" << std::endl; std::cout << std::endl << " HTTP options" << std::endl; std::cout << "\t -H hostname:port : HTTP server binding (default " << httpAddress << ")" << std::endl; std::cout << "\t -w webroot : path to get static files" << std::endl; std::cout << "\t -c sslkeycert : path to private key and certificate for HTTPS" << std::endl; std::cout << "\t -N nbthreads : number of threads for HTTP server" << std::endl; std::cout << "\t -A passwd : password file for HTTP server access" << std::endl; std::cout << "\t -D authDomain : authentication domain for HTTP server access (default:mydomain.com)" << std::endl; std::cout << std::endl << " WebRTC options" << std::endl; std::cout << "\t -S[stun_address] : start embeded STUN server bind to address (default " << defaultlocalstunurl << ")" << std::endl; std::cout << "\t -s[stun_address] : use an external STUN server (default:" << stunurl << " , -:means no STUN)" << std::endl; std::cout << "\t -t[username:password@]turn_address : use an external TURN relay server (default:disabled)" << std::endl; std::cout << "\t -T[username:password@]turn_address : start embeded TURN server (default:disabled)" << std::endl; std::cout << "\t -R Udp_port_min:Udp_port_min : Set the webrtc udp port range (default:" << localWebrtcUdpPortRange << ")" << std::endl; std::cout << "\t -W webrtc_trials_fields : Set the webrtc trials fields (default:" << webrtcTrialsFields << ")" << std::endl; std::cout << "\t -I icetransport : Set ice transport type (default:" << transportType << ")" << std::endl; #ifdef HAVE_SOUND std::cout << "\t -a[audio layer] : spefify audio capture layer to use (default:" << audioLayer << ")" << std::endl; #endif std::cout << "\t -q[filter] : spefify publish filter (default:" << publishFilter << ")" << std::endl; std::cout << "\t -o : use null codec (keep frame encoded)" << std::endl; std::cout << "\t -b : use sdp plan-B (default use unifiedPlan)" << std::endl; exit(0); } } while (optind<argc) { std::string url(argv[optind]); config["urls"][url]["video"] = url; optind++; } std::cout << "Version:" << VERSION << std::endl; std::cout << config; rtc::LogMessage::LogToDebug((rtc::LoggingSeverity)logLevel); rtc::LogMessage::LogTimestamps(); rtc::LogMessage::LogThreads(); std::cout << "Logger level:" << rtc::LogMessage::GetLogToDebug() << std::endl; rtc::ThreadManager::Instance()->WrapCurrentThread(); rtc::Thread* thread = rtc::Thread::Current(); rtc::InitializeSSL(); // webrtc server std::list<std::string> iceServerList; if ((strlen(stunurl) != 0) && (strcmp(stunurl,"-") != 0)) { iceServerList.push_back(std::string("stun:")+stunurl); } if (strlen(turnurl)) { iceServerList.push_back(std::string("turn:")+turnurl); } // init trials fields webrtc::field_trial::InitFieldTrialsFromString(webrtcTrialsFields.c_str()); webRtcServer = new PeerConnectionManager(iceServerList, config["urls"], audioLayer, publishFilter, localWebrtcUdpPortRange, useNullCodec, usePlanB, maxpc, transportType, basePath); if (!webRtcServer->InitializePeerConnection()) { std::cout << "Cannot Initialize WebRTC server" << std::endl; } else { // http server std::vector<std::string> options; options.push_back("document_root"); options.push_back(webroot); options.push_back("enable_directory_listing"); options.push_back("no"); if (!disableXframeOptions) { options.push_back("additional_header"); options.push_back("X-Frame-Options: SAMEORIGIN"); } options.push_back("access_control_allow_origin"); options.push_back("*"); options.push_back("listening_ports"); options.push_back(httpAddress); options.push_back("enable_keep_alive"); options.push_back("yes"); options.push_back("keep_alive_timeout_ms"); options.push_back("1000"); options.push_back("decode_url"); options.push_back("no"); if (!sslCertificate.empty()) { options.push_back("ssl_certificate"); options.push_back(sslCertificate); } if (!nbthreads.empty()) { options.push_back("num_threads"); options.push_back(nbthreads); } if (!passwdFile.empty()) { options.push_back("global_auth_file"); options.push_back(passwdFile); options.push_back("authentication_domain"); options.push_back(authDomain); } try { std::map<std::string,HttpServerRequestHandler::httpFunction> func = webRtcServer->getHttpApi(); std::cout << "HTTP Listen at " << httpAddress << std::endl; HttpServerRequestHandler httpServer(func, options); // start STUN server if needed std::unique_ptr<cricket::StunServer> stunserver; if (localstunurl != NULL) { rtc::SocketAddress server_addr; server_addr.FromString(localstunurl); rtc::AsyncUDPSocket* server_socket = rtc::AsyncUDPSocket::Create(thread->socketserver(), server_addr); if (server_socket) { stunserver.reset(new cricket::StunServer(server_socket)); std::cout << "STUN Listening at " << server_addr.ToString() << std::endl; } } // start TRUN server if needed std::unique_ptr<cricket::TurnServer> turnserver; if (localturnurl != NULL) { std::istringstream is(localturnurl); std::string addr; std::getline(is, addr, '@'); std::getline(is, addr, '@'); rtc::SocketAddress server_addr; server_addr.FromString(addr); turnserver.reset(new cricket::TurnServer(rtc::Thread::Current())); turnserver->set_auth_hook(&turnAuth); turnserver->set_redirect_hook(&turnRedirector); rtc::Socket* tcp_server_socket = thread->socketserver()->CreateSocket(AF_INET, SOCK_STREAM); if (tcp_server_socket) { std::cout << "TURN Listening TCP at " << server_addr.ToString() << std::endl; tcp_server_socket->Bind(server_addr); tcp_server_socket->Listen(5); turnserver->AddInternalServerSocket(tcp_server_socket, cricket::PROTO_TCP); } else { std::cout << "Failed to create TURN TCP server socket" << std::endl; } rtc::AsyncUDPSocket* udp_server_socket = rtc::AsyncUDPSocket::Create(thread->socketserver(), server_addr); if (udp_server_socket) { std::cout << "TURN Listening UDP at " << server_addr.ToString() << std::endl; turnserver->AddInternalSocket(udp_server_socket, cricket::PROTO_UDP); } else { std::cout << "Failed to create TURN UDP server socket" << std::endl; } is.clear(); is.str(turnurl); std::getline(is, addr, '@'); std::getline(is, addr, '@'); rtc::SocketAddress external_server_addr; external_server_addr.FromString(addr); std::cout << "TURN external addr:" << external_server_addr.ToString() << std::endl; turnserver->SetExternalSocketFactory(new rtc::BasicPacketSocketFactory(thread->socketserver()), rtc::SocketAddress(external_server_addr.ipaddr(), 0)); } // mainloop signal(SIGINT,sighandler); thread->Run(); } catch (const CivetException & ex) { std::cout << "Cannot Initialize start HTTP server exception:" << ex.what() << std::endl; } } rtc::CleanupSSL(); std::cout << "Exit" << std::endl; return 0; }
2301_81045437/webrtc-streamer
src/main.cpp
C++
unlicense
13,808
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** rtpvideocapturer.cpp ** ** -------------------------------------------------------------------------*/ #ifdef HAVE_LIVE555 #include "rtc_base/logging.h" #include "rtpvideocapturer.h" RTPVideoCapturer::RTPVideoCapturer(const std::string & uri, const std::map<std::string,std::string> & opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory) : LiveVideoSource(uri, opts, videoDecoderFactory, false) { RTC_LOG(LS_INFO) << "RTSPVideoCapturer " << uri ; } RTPVideoCapturer::~RTPVideoCapturer() { } void RTPVideoCapturer::onError(SDPClient& connection, const char* error) { RTC_LOG(LS_ERROR) << "RTPVideoCapturer:onError error:" << error; } #endif
2301_81045437/webrtc-streamer
src/rtpvideocapturer.cpp
C++
unlicense
935
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** rtspaudiocapturer.cpp ** ** -------------------------------------------------------------------------*/ #ifdef HAVE_LIVE555 #include "rtc_base/logging.h" #include "rtspaudiocapturer.h" RTSPAudioSource::RTSPAudioSource(rtc::scoped_refptr<webrtc::AudioDecoderFactory> audioDecoderFactory, const std::string & uri, const std::map<std::string,std::string> & opts) : LiveAudioSource(audioDecoderFactory, uri, opts, false) { } RTSPAudioSource::~RTSPAudioSource() { } #endif
2301_81045437/webrtc-streamer
src/rtspaudiocapturer.cpp
C++
unlicense
744
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** rtspvideocapturer.cpp ** ** -------------------------------------------------------------------------*/ #ifdef HAVE_LIVE555 #include "rtc_base/logging.h" #include "rtspvideocapturer.h" RTSPVideoCapturer::RTSPVideoCapturer(const std::string & uri, const std::map<std::string,std::string> & opts, std::unique_ptr<webrtc::VideoDecoderFactory>& videoDecoderFactory) : LiveVideoSource(uri, opts, videoDecoderFactory, false) { RTC_LOG(LS_INFO) << "RTSPVideoCapturer " << uri ; } RTSPVideoCapturer::~RTSPVideoCapturer() { } void RTSPVideoCapturer::onError(RTSPConnection& connection, const char* error) { RTC_LOG(LS_ERROR) << "RTSPVideoCapturer:onError url:" << m_liveclient.getUrl() << " error:" << error; connection.start(1); } #endif
2301_81045437/webrtc-streamer
src/rtspvideocapturer.cpp
C++
unlicense
1,007
package controller.academy; import entity.AcademyEntity; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.AcademyService; import service.impl.AcademyServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet(urlPatterns = "/addAcademyInfo") public class AddAcademyInfoServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {}); AcademyEntity academy = new AcademyEntity(); academy.setAcademyName((String) body.get("academyName")); academy.setAcademyCode((String) body.get("academyCode")); AcademyService academyService = new AcademyServiceImpl(); academyService.addAcademyInfo(academy); BaseResult<Void> result = BaseResult.success(); resp.setContentType("application/json;charset=UTF-8"); String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("新增学院信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "新增学院信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/academy/AddAcademyInfoServlet.java
Java
unknown
2,394
package controller.academy; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.AcademyService; import service.impl.AcademyServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; @WebServlet(urlPatterns = "/batchDeleteAcademy") public class BatchDeleteAcademyServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {}); List<String> ids = (List<String>) body.get("ids"); AcademyService service = new AcademyServiceImpl(); service.batchDeleteAcademy(ids); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("删除学院信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "删除学院信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/academy/BatchDeleteAcademyServlet.java
Java
unknown
2,249
package controller.academy; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.AcademyService; import service.impl.AcademyServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet(urlPatterns = "/deleteAcademy") public class DeleteAcademyServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() { }); String academyId = (String) body.get("academyId"); AcademyService service = new AcademyServiceImpl(); service.deleteAcademy(academyId); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); // 序列化并写入响应 String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("删除学院信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "删除学院信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/academy/DeleteAcademyServlet.java
Java
unknown
2,268
package controller.academy; import entity.AcademyEntity; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.AcademyService; import service.impl.AcademyServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.IOException; import java.util.List; @WebServlet(urlPatterns = "/getAcademyInfo") public class GetAcademyInfoServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String name = request.getParameter("name"); AcademyService academyService = new AcademyServiceImpl(); List<AcademyEntity> academyList = academyService.getAcademyInfo(name); BaseResult<List<AcademyEntity>> result = BaseResult.success(academyList); response.setContentType("application/json;charset=UTF-8"); String jsonResponse = objectMapper.writeValueAsString(result); response.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("获取学院信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "加载学院信息失败: " + e.getMessage()); response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); response.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/academy/GetAcademyInfoServlet.java
Java
unknown
2,039
package controller.academy; import entity.AcademyEntity; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.AcademyService; import service.impl.AcademyServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet(urlPatterns = "/updateAcademy") public class UpdateAcademyServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() { }); AcademyEntity academy = new AcademyEntity(); academy.setId((String) body.get("id")); academy.setAcademyName((String) body.get("academyName")); academy.setAcademyCode((String) body.get("academyCode")); AcademyService academyService = new AcademyServiceImpl(); academyService.updateAcademyInfo(academy); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); // 序列化并写入响应 String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("修改学院信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "修改学院信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/academy/UpdateAcademyServlet.java
Java
unknown
2,497
package controller.classServlet; import entity.ClassEntity; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.ClassService; import service.impl.ClassServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet(urlPatterns = "/addClassInfo") public class AddClassInfoServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {}); ClassEntity classEntity = new ClassEntity(); classEntity.setSpecialtyId((String) body.get("specialtyId")); classEntity.setTeacherId((String) body.get("teacherId")); classEntity.setClassName((String) body.get("className")); classEntity.setClassCode((String) body.get("classCode")); classEntity.setGrade((String) body.get("grade")); ClassService classService = new ClassServiceImpl(); classService.addClassInfo(classEntity); BaseResult<Void> result = BaseResult.success(); resp.setContentType("application/json;charset=UTF-8"); String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("新增班级信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "新增班级信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/classServlet/AddClassInfoServlet.java
Java
unknown
2,590
package controller.classServlet; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.ClassService; import service.impl.ClassServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; @WebServlet(urlPatterns = "/batchDeleteClass") public class BatchDeleteClassServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {}); List<String> ids = (List<String>) body.get("ids"); ClassService classService = new ClassServiceImpl(); classService.batchDeleteClass(ids); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("删除班级信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "删除班级信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/classServlet/BatchDeleteClassServlet.java
Java
unknown
2,250
package controller.classServlet; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.ClassService; import service.impl.ClassServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet(urlPatterns = "/deleteClass") public class DeleteClassServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() { }); String classId = (String) body.get("classId"); ClassService classService = new ClassServiceImpl(); classService.deleteClass(classId); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); // 序列化并写入响应 String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("删除班级信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "删除班级信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/classServlet/DeleteClassServlet.java
Java
unknown
2,263
package controller.classServlet; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.ClassService; import service.impl.ClassServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import vo.GetClassInfoVO; import java.io.IOException; import java.util.List; @WebServlet(urlPatterns = "/getClassInfoBySpecialtyId") public class GetClassInfoBySpecialtyIdServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String specialtyId = request.getParameter("specialtyId"); String grade = request.getParameter("grade"); ClassService classService = new ClassServiceImpl(); List<GetClassInfoVO> voList = classService.getClassInfoBySpecialtyId(specialtyId, grade); BaseResult<List<GetClassInfoVO>> result = BaseResult.success(voList); response.setContentType("application/json;charset=UTF-8"); String jsonResponse = objectMapper.writeValueAsString(result); response.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("获取班级信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "加载班级信息失败: " + e.getMessage()); response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); response.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/classServlet/GetClassInfoBySpecialtyIdServlet.java
Java
unknown
2,140
package controller.classServlet; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.ClassService; import service.impl.ClassServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import vo.GetClassInfoVO; import java.io.IOException; import java.util.List; @WebServlet(urlPatterns = "/getClassInfo") public class GetClassInfoServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String name = request.getParameter("name"); ClassService classService = new ClassServiceImpl(); List<GetClassInfoVO> voList = classService.getClassInfo(name); BaseResult<List<GetClassInfoVO>> result = BaseResult.success(voList); response.setContentType("application/json;charset=UTF-8"); String jsonResponse = objectMapper.writeValueAsString(result); response.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("获取班级信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "加载班级信息失败: " + e.getMessage()); response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); response.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/classServlet/GetClassInfoServlet.java
Java
unknown
2,015
package controller.classServlet; import entity.StudentEntity; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.ClassService; import service.impl.ClassServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.IOException; import java.util.List; @WebServlet(urlPatterns = "/getClassStudentInfo") public class GetClassStudentInfoServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); String classId = req.getParameter("classId"); ClassService service = new ClassServiceImpl(); List<StudentEntity> list = service.getClassStudentInfo(classId); BaseResult<List<StudentEntity>> result = BaseResult.success(list); String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("获取学生信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "加载学生信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/classServlet/GetClassStudentInfoServlet.java
Java
unknown
1,995
package controller.classServlet; import com.fasterxml.jackson.databind.ObjectMapper; import dto.GetSameGradeClassDTO; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.ClassService; import service.impl.ClassServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import vo.GetSameGradeClassVO; import java.io.BufferedReader; import java.io.IOException; import java.util.List; @WebServlet(urlPatterns = "/getSameGradeClass") public class GetSameGradeClassServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); GetSameGradeClassDTO dto = objectMapper.readValue(reader, GetSameGradeClassDTO.class); ClassService classService = new ClassServiceImpl(); List<GetSameGradeClassVO> voList = classService.getSameGradeClass(dto); BaseResult<List<GetSameGradeClassVO>> result = BaseResult.success(voList); resp.setContentType("application/json;charset=UTF-8"); String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("获取班级信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "获取班级信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/classServlet/GetSameGradeClassServlet.java
Java
unknown
2,191
package controller.classServlet; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.ClassService; import service.impl.ClassServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet(urlPatterns = "/removeClassStudent") public class RemoveClassStudentServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {}); String studentId = (String) body.get("studentId"); ClassService classService = new ClassServiceImpl(); classService.removeClassStudent(studentId); BaseResult<Void> result = BaseResult.success(); resp.setContentType("application/json;charset=UTF-8"); String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("移出学生错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "移出学生失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/classServlet/RemoveClassStudentServlet.java
Java
unknown
2,227
package controller.classServlet; import entity.ClassEntity; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.ClassService; import service.impl.ClassServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet(urlPatterns = "/updateClass") public class UpdateClassServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() { }); ClassEntity classEntity = new ClassEntity(); classEntity.setId((String) body.get("classId")); classEntity.setSpecialtyId((String) body.get("specialtyId")); classEntity.setTeacherId((String) body.get("teacherId")); classEntity.setClassName((String) body.get("className")); classEntity.setClassCode((String) body.get("classCode")); ClassService classService = new ClassServiceImpl(); classService.updateClassInfo(classEntity); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); // 序列化并写入响应 String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("修改班级信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "修改班级信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/classServlet/UpdateClassServlet.java
Java
unknown
2,639
package controller.login; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.impl.UserServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet("/login") public class LoginServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {}); String username = (String) body.get("username"); String password = (String) body.get("password"); UserServiceImpl service = new UserServiceImpl(); boolean sign = service.getUserInfo(username,password); BaseResult<String> result; if (sign) { result = BaseResult.success("登录成功"); } else { result = BaseResult.success("账号或密码错误"); } resp.setContentType("application/json;charset=UTF-8"); // 序列化并写入响应 String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("登录失败", e); BaseResult<Void> errorResult = BaseResult.failed(500, "登录失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/login/LoginServlet.java
Java
unknown
2,411
package controller.login; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.impl.UserServiceImpl; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet("/registered") public class RegisteredServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(RegisteredServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {}); String username = (String) body.get("username"); String password = (String) body.get("password"); String confirm = (String) body.get("confirm"); if (username == null || username.trim().isEmpty()) { sendError(resp, "用户名不能为空", HttpServletResponse.SC_BAD_REQUEST); return; } if (password == null || password.length() < 6) { sendError(resp, "密码不能少于6位", HttpServletResponse.SC_BAD_REQUEST); return; } if (!password.equals(confirm)) { sendError(resp, "两次输入密码不一致", HttpServletResponse.SC_BAD_REQUEST); return; } UserServiceImpl service = new UserServiceImpl(); boolean sign = service.registered(username, password); BaseResult<String> result; if (sign) { result = BaseResult.success("注册成功"); resp.setStatus(HttpServletResponse.SC_OK); } else { result = BaseResult.success("该用户名已存在"); resp.setStatus(HttpServletResponse.SC_OK); } String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("注册失败", e); sendError(resp, "服务器内部错误: " + e.getMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } private void sendError(HttpServletResponse resp, String message, int statusCode) throws IOException { resp.setStatus(statusCode); BaseResult<Void> errorResult = BaseResult.failed(statusCode, message); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } }
2301_81295389/student-java-web-backend
src/main/java/controller/login/RegisteredServlet.java
Java
unknown
3,119
package controller.specialty; import entity.SpecialtyEntity; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.SpecialtyService; import service.impl.SpecialtyServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet(urlPatterns = "/addSpecialtyInfo") public class AddSpecialtyInfoServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {}); SpecialtyEntity specialty = new SpecialtyEntity(); specialty.setAcademyId((String) body.get("academyId")); specialty.setSpecialtyName((String) body.get("specialtyName")); specialty.setSpecialtyCode((String) body.get("specialtyCode")); SpecialtyService specialtyService = new SpecialtyServiceImpl(); specialtyService.addSpecialtyInfo(specialty); BaseResult<Void> result = BaseResult.success(); resp.setContentType("application/json;charset=UTF-8"); String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("新增专业信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "新增专业信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/specialty/AddSpecialtyInfoServlet.java
Java
unknown
2,504
package controller.specialty; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.SpecialtyService; import service.impl.SpecialtyServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; @WebServlet(urlPatterns = "/batchDeleteSpecialty") public class BatchDeleteSpecialtyServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {}); List<String> ids = (List<String>) body.get("ids"); SpecialtyService service = new SpecialtyServiceImpl(); service.batchDeleteSpecialty(ids); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("删除专业信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "删除专业信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/specialty/BatchDeleteSpecialtyServlet.java
Java
unknown
2,265
package controller.specialty; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.SpecialtyService; import service.impl.SpecialtyServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet(urlPatterns = "/deleteSpecialty") public class DeleteSpecialtyServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() { }); String specialtyId = (String) body.get("specialtyId"); SpecialtyService service = new SpecialtyServiceImpl(); service.deleteSpecialty(specialtyId); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); // 序列化并写入响应 String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("删除专业信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "删除专业信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/specialty/DeleteSpecialtyServlet.java
Java
unknown
2,290
package controller.specialty; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.SpecialtyService; import service.impl.SpecialtyServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import vo.GetSpecialtyAndMaxCodeVO; import java.io.IOException; import java.util.List; @WebServlet(urlPatterns = "/getSpecialtyByAcademyId") public class GetSpecialtyByAcademyId extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String academyId = request.getParameter("academyId"); SpecialtyService specialtyService = new SpecialtyServiceImpl(); List<GetSpecialtyAndMaxCodeVO> voList = specialtyService.getSpecialtyByAcademyId(academyId); BaseResult<List<GetSpecialtyAndMaxCodeVO>> result = BaseResult.success(voList); response.setContentType("application/json;charset=UTF-8"); String jsonResponse = objectMapper.writeValueAsString(result); response.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("获取专业信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "加载专业信息失败: " + e.getMessage()); response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); response.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/specialty/GetSpecialtyByAcademyId.java
Java
unknown
2,107
package controller.specialty; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.SpecialtyService; import service.impl.SpecialtyServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import vo.GetSpecialtyVO; import java.io.IOException; import java.util.List; @WebServlet(urlPatterns = "/getSpecialtyInfo") public class GetSpecialtyInfoServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String name = request.getParameter("name"); SpecialtyService specialtyService = new SpecialtyServiceImpl(); List<GetSpecialtyVO> voList = specialtyService.getSpecialtyInfo(name); BaseResult<List<GetSpecialtyVO>> result = BaseResult.success(voList); response.setContentType("application/json;charset=UTF-8"); String jsonResponse = objectMapper.writeValueAsString(result); response.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("获取专业信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "加载专业信息失败: " + e.getMessage()); response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); response.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/specialty/GetSpecialtyInfoServlet.java
Java
unknown
2,048
package controller.specialty; import entity.SpecialtyEntity; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.SpecialtyService; import service.impl.SpecialtyServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet(urlPatterns = "/updateSpecialty") public class UpdateSpecialtyServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() { }); SpecialtyEntity specialty = new SpecialtyEntity(); specialty.setId((String) body.get("id")); specialty.setAcademyId((String) body.get("academyId")); specialty.setSpecialtyName((String) body.get("specialtyName")); specialty.setSpecialtyCode((String) body.get("specialtyCode")); SpecialtyService specialtyService = new SpecialtyServiceImpl(); specialtyService.updateSpecialtyInfo(specialty); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); // 序列化并写入响应 String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("修改专业信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "修改专业信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/specialty/UpdateSpecialtyServlet.java
Java
unknown
2,609
package controller.student; import entity.StudentEntity; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.impl.StudentServiceImpl; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; @WebServlet("/addStudent") public class AddStudentServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); StudentEntity student = objectMapper.readValue(reader, StudentEntity.class); StudentServiceImpl service = new StudentServiceImpl(); service.addStudent(student); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); // 序列化并写入响应 String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("新增学生信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "新增学生信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/student/AddStudentServlet.java
Java
unknown
2,051
package controller.student; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.impl.StudentServiceImpl; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; @WebServlet("/batchDeleteStudent") public class BatchDeleteStudentServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {}); List<String> ids = (List<String>) body.get("ids"); StudentServiceImpl service = new StudentServiceImpl(); service.batchDeleteStudent(ids); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("删除学生信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "删除学生信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/student/BatchDeleteStudentServlet.java
Java
unknown
2,167
package controller.student; import com.fasterxml.jackson.databind.ObjectMapper; import dto.ChooseClassDTO; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.impl.StudentServiceImpl; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; @WebServlet(urlPatterns = "/chooseClass") public class ChooseClassServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); ChooseClassDTO dto = objectMapper.readValue(reader, ChooseClassDTO.class); StudentServiceImpl service = new StudentServiceImpl(); service.chooseClass(dto); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); // 序列化并写入响应 String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("添加学生班级错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "添加学生班级失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/student/ChooseClassServlet.java
Java
unknown
2,060
package controller.student; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.impl.StudentServiceImpl; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet("/deleteStudent") public class DeleteStudentServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {}); String id = (String) body.get("id"); StudentServiceImpl service = new StudentServiceImpl(); service.deleteStudent(id); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); // 序列化并写入响应 String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("删除学生信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "删除学生信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/student/DeleteStudentServlet.java
Java
unknown
2,153
package controller.student; import service.impl.StudentServiceImpl; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import util.BaseResult; import vo.GetStudentVO; @WebServlet(urlPatterns = "/getStudent") public class StudentServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); String name = req.getParameter("name"); StudentServiceImpl service = new StudentServiceImpl(); List<GetStudentVO> list = service.getAll(name); BaseResult<List<GetStudentVO>> result = BaseResult.success(list); String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("获取学生信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "加载学生信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/student/StudentServlet.java
Java
unknown
1,882
package controller.student; import entity.StudentEntity; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.impl.StudentServiceImpl; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; @WebServlet("/updateStudent") public class UpdateStudentServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); StudentEntity student = objectMapper.readValue(reader, StudentEntity.class); StudentServiceImpl service = new StudentServiceImpl(); service.updateStudent(student); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); // 序列化并写入响应 String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("修改学生信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "修改学生信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/student/UpdateStudentServlet.java
Java
unknown
2,002
package controller.teacher; import entity.TeacherEntity; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.TeacherService; import service.impl.TeacherServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet(urlPatterns = "/addTeacherInfo") public class AddTeacherInfoServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() { }); TeacherEntity teacher = new TeacherEntity(); teacher.setAcademyId((String) body.get("academyId")); teacher.setTeacherName((String) body.get("teacherName")); teacher.setAge((Integer) (body.get("age"))); teacher.setGender((Integer) (body.get("gender"))); teacher.setPhoneNumber((String) body.get("phoneNumber")); teacher.setDegree((String) body.get("degree")); TeacherService teacherService = new TeacherServiceImpl(); teacherService.addTeacherInfo(teacher); BaseResult<Void> result = BaseResult.success(); resp.setContentType("application/json;charset=UTF-8"); String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("新增教师信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "新增教师信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/teacher/AddTeacherInfoServlet.java
Java
unknown
2,653
package controller.teacher; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.TeacherService; import service.impl.TeacherServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; @WebServlet(urlPatterns = "/batchDeleteTeacher") public class BatchDeleteTeacherServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {}); List<String> ids = (List<String>) body.get("ids"); TeacherService service = new TeacherServiceImpl(); service.batchDeleteTeacher(ids); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("删除教师信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "删除教师信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/teacher/BatchDeleteTeacherServlet.java
Java
unknown
2,249
package controller.teacher; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.TeacherService; import service.impl.TeacherServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet(urlPatterns = "/deleteTeacher") public class DeleteTeacherServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() { }); String teacherId = (String) body.get("teacherId"); TeacherService service = new TeacherServiceImpl(); service.deleteTeacher(teacherId); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); // 序列化并写入响应 String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("删除教师信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "删除教师信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/teacher/DeleteTeacherServlet.java
Java
unknown
2,268
package controller.teacher; import entity.TeacherEntity; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.TeacherService; import service.impl.TeacherServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.IOException; import java.util.List; @WebServlet(urlPatterns = "/getInfoByAcademyId") public class GetInfoByAcademyIdServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String academyId = request.getParameter("academyId"); TeacherService teacherService = new TeacherServiceImpl(); List<TeacherEntity> teacherEntityList = teacherService.getTeacherInfoByAcademyId(academyId); BaseResult<List<TeacherEntity>> result = BaseResult.success(teacherEntityList); response.setContentType("application/json;charset=UTF-8"); String jsonResponse = objectMapper.writeValueAsString(result); response.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("获取教师信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "加载教师信息失败: " + e.getMessage()); response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); response.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/teacher/GetInfoByAcademyIdServlet.java
Java
unknown
2,085
package controller.teacher; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.TeacherService; import service.impl.TeacherServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import vo.GetTeacherVO; import java.io.IOException; import java.util.List; @WebServlet(urlPatterns = "/getTeacherInfo") public class GetTeacherInfoServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String name = request.getParameter("name"); TeacherService teacherService = new TeacherServiceImpl(); List<GetTeacherVO> teacherEntityList = teacherService.getTeacherInfo(name); BaseResult<List<GetTeacherVO>> result = BaseResult.success(teacherEntityList); response.setContentType("application/json;charset=UTF-8"); String jsonResponse = objectMapper.writeValueAsString(result); response.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("获取教师信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "加载教师信息失败: " + e.getMessage()); response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); response.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/teacher/GetTeacherInfoServlet.java
Java
unknown
2,044
package controller.teacher; import entity.TeacherEntity; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.TeacherService; import service.impl.TeacherServiceImpl; import controller.student.StudentServlet; import util.BaseResult; import java.io.BufferedReader; import java.io.IOException; @WebServlet(urlPatterns = "/updateTeacher") public class UpdateTeacherServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class); private static final ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); BufferedReader reader = req.getReader(); // Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() { // }); TeacherEntity teacher = objectMapper.readValue(req.getReader(), TeacherEntity.class); // teacher.setId((String) body.get("teacherId")); // teacher.setAcademyId((String) body.get("academyId")); // teacher.setTeacherName((String) body.get("teacherName")); // teacher.setAge((Integer) body.get("age")); // teacher.setGender((Integer) body.get("gender")); // teacher.setPhoneNumber((String) body.get("phoneNumber")); // teacher.setDegree((String) body.get("degree")); TeacherService teacherService = new TeacherServiceImpl(); teacherService.updateTeacherInfo(teacher); resp.setContentType("application/json;charset=UTF-8"); BaseResult<Void> result = BaseResult.success(); // 序列化并写入响应 String jsonResponse = objectMapper.writeValueAsString(result); resp.getWriter().write(jsonResponse); } catch (Exception e) { logger.error("修改教师信息错误", e); BaseResult<Void> errorResult = BaseResult.failed(500, "修改教师信息失败: " + e.getMessage()); resp.setContentType("application/json;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String jsonError = objectMapper.writeValueAsString(errorResult); resp.getWriter().write(jsonError); } } }
2301_81295389/student-java-web-backend
src/main/java/controller/teacher/UpdateTeacherServlet.java
Java
unknown
2,703
package dao; import entity.AcademyEntity; import java.util.List; import java.util.Map; public interface AcademyDao { List<Map<String,Object>> getAcademyInfo(String name); int addAcademyInfo(AcademyEntity academy); int updateAcademyInfo(AcademyEntity academy); int deleteAcademy(String academyId); int batchDeleteAcademy(List<String> ids); Map<String,Object> getAcademyInfoById(String id); }
2301_81295389/student-java-web-backend
src/main/java/dao/AcademyDao.java
Java
unknown
423
package dao; import entity.ClassEntity; import dto.GetSameGradeClassDTO; import java.util.List; import java.util.Map; public interface ClassDao { List<Map<String, Object>> getClassInfo(String name); int addClassInfo(ClassEntity classEntity); int updateClassInfo(ClassEntity classEntity); int deleteClass(String classId); int batchDeleteClass(List<String> ids); List<Map<String, Object>> getClassInfoBySpecialtyId(String specialtyId, String grade); List<Map<String, Object>> getClassStudentInfo(String classId); Map<String, Object> getClassInfoById(String classId); int removeClassStudent(String studentId); List<Map<String, Object>> getSameGradeClass(GetSameGradeClassDTO dto); }
2301_81295389/student-java-web-backend
src/main/java/dao/ClassDao.java
Java
unknown
733
package dao; import entity.SpecialtyEntity; import java.util.List; import java.util.Map; public interface SpecialtyDao { List<Map<String,Object>> getSpecialtyInfo(String name); int addSpecialtyInfo(SpecialtyEntity specialty); int updateSpecialtyInfo(SpecialtyEntity specialty); int deleteSpecialty(String specialtyId); int batchDeleteSpecialty(List<String> ids); Map<String,Object> getSpecialtyInfoById(String id); List<Map<String,Object>> getSpecialtyByAcademyId(String academyId); String getMaxClassCodeBySpecialtyId(String specialtyId); }
2301_81295389/student-java-web-backend
src/main/java/dao/SpecialtyDao.java
Java
unknown
583
package dao; import entity.StudentEntity; import dto.ChooseClassDTO; import java.util.List; import java.util.Map; public interface StudentDao { List<Map<String,Object>> getAll(String name); int addStudent(StudentEntity student); int deleteStudent(String id); int updateStudent(StudentEntity student); int batchDeleteStudent(List<String> ids); int chooseClass(ChooseClassDTO dto); }
2301_81295389/student-java-web-backend
src/main/java/dao/StudentDao.java
Java
unknown
415
package dao; import entity.TeacherEntity; import java.util.List; import java.util.Map; public interface TeacherDao { List<Map<String,Object>> getTeacherInfo(String name); int addTeacherInfo(TeacherEntity teacher); int updateTeacherInfo(TeacherEntity teacher); int deleteTeacher(String teacherId); int batchDeleteTeacher(List<String> ids); List<Map<String,Object>> getTeacherInfoByAcademyId(String academyId); Map<String,Object> getTeacherInfoById(String id); }
2301_81295389/student-java-web-backend
src/main/java/dao/TeacherDao.java
Java
unknown
499
package dao; import entity.UserEntity; public interface UserDao { int insert(UserEntity user); UserEntity findByUsername(String username); }
2301_81295389/student-java-web-backend
src/main/java/dao/UserDao.java
Java
unknown
151
package dao.impl; import entity.AcademyEntity; import dao.AcademyDao; import util.JDBCUtil; import java.util.List; import java.util.Map; public class AcademyDaoImpl extends JDBCUtil implements AcademyDao { @Override public List<Map<String, Object>> getAcademyInfo(String name) { String sql; List<Map<String, Object>> mapList; if ("null".equalsIgnoreCase(name)) { sql = "select * from academy_info"; mapList = queryForList(sql); } else if (name != null && !name.trim().isEmpty()) { sql = "select * from academy_info where academy_name like ?"; String academyName = "%" + name + "%"; mapList = queryForList(sql, academyName); } else { sql = "select * from academy_info"; mapList = queryForList(sql); } return mapList; } @Override public int addAcademyInfo(AcademyEntity academy) { String sql = "insert into academy_info (id,academy_name,academy_code) values (?,?,?)"; return insert(sql, academy.getId(), academy.getAcademyName(), academy.getAcademyCode()); } @Override public int updateAcademyInfo(AcademyEntity academy) { String sql = "update academy_info set academy_name = ?,academy_code = ? where id = ?"; return update(sql,academy.getAcademyName(),academy.getAcademyCode(),academy.getId()); } @Override public int deleteAcademy(String academyId) { String sql = "delete academy_info from academy_info where id = ?"; return delete(sql,academyId); } @Override public int batchDeleteAcademy(List<String> ids) { if (ids == null || ids.isEmpty()) { throw new IllegalArgumentException("ID列表不能为空"); } StringBuilder placeholders = new StringBuilder(); for (int i = 0; i < ids.size(); i++) { placeholders.append("?"); if (i < ids.size() - 1) { placeholders.append(","); } } String sql = "delete from academy_info where id in (" + placeholders + ")"; return delete(sql, ids.toArray()); } @Override public Map<String, Object> getAcademyInfoById(String id) { String sql = "select * from academy_info where id = ?"; return queryForList(sql,id).get(0); } }
2301_81295389/student-java-web-backend
src/main/java/dao/impl/AcademyDaoImpl.java
Java
unknown
2,364
package dao.impl; import entity.ClassEntity; import dao.ClassDao; import dto.GetSameGradeClassDTO; import util.JDBCUtil; import java.util.List; import java.util.Map; public class ClassDaoImpl extends JDBCUtil implements ClassDao { @Override public List<Map<String, Object>> getClassInfo(String name) { String sql; List<Map<String, Object>> mapList; if ("null".equalsIgnoreCase(name)) { sql = "select * from class_info"; mapList = queryForList(sql); } else if (name != null && !name.trim().isEmpty()) { sql = "select * from class_info where class_name like ?"; String className = "%" + name + "%"; mapList = queryForList(sql, className); } else { sql = "select * from class_info"; mapList = queryForList(sql); } return mapList; } @Override public int addClassInfo(ClassEntity classEntity) { String sql = "insert into class_info (id,specialty_id,teacher_id,class_name,class_code,grade) values (?,?,?,?,?,?)"; return insert(sql, classEntity.getId(), classEntity.getSpecialtyId(), classEntity.getTeacherId(), classEntity.getClassName(), classEntity.getClassCode(), classEntity.getGrade()); } @Override public int updateClassInfo(ClassEntity classEntity) { String sql = "update class_info set specialty_id = ?,teacher_id = ?,class_name = ?,class_code = ? where id = ?"; return update(sql, classEntity.getSpecialtyId(), classEntity.getTeacherId(), classEntity.getClassName(), classEntity.getClassCode(), classEntity.getId()); } @Override public int deleteClass(String classId) { String sql = "delete class_info from class_info where id = ?"; return delete(sql, classId); } @Override public int batchDeleteClass(List<String> ids) { if (ids == null || ids.isEmpty()) { throw new IllegalArgumentException("ID列表不能为空"); } StringBuilder placeholders = new StringBuilder(); for (int i = 0; i < ids.size(); i++) { placeholders.append("?"); if (i < ids.size() - 1) { placeholders.append(","); } } String sql = "delete from class_info where id in (" + placeholders + ")"; return delete(sql, ids.toArray()); } @Override public List<Map<String, Object>> getClassInfoBySpecialtyId(String specialtyId, String grade) { String sql = "select * from class_info where specialty_id = ? and grade = ?"; return queryForList(sql, specialtyId, grade); } @Override public List<Map<String, Object>> getClassStudentInfo(String classId) { String sql = "select * from student_info where class_id = ?"; return queryForList(sql, classId); } @Override public Map<String, Object> getClassInfoById(String classId) { String sql = "select * from class_info where id = ?"; List<Map<String, Object>> mapList = queryForList(sql, classId); if (mapList.isEmpty()) { return null; } return mapList.get(0); } @Override public int removeClassStudent(String studentId) { String sql = "update student_info set class_id = NULL where id = ?"; return update(sql, studentId); } @Override public List<Map<String, Object>> getSameGradeClass(GetSameGradeClassDTO dto) { String sql = "select class_name,id from class_info where grade = ? and specialty_id = ?"; return queryForList(sql, dto.getGrade(), dto.getSpecialtyId()); } }
2301_81295389/student-java-web-backend
src/main/java/dao/impl/ClassDaoImpl.java
Java
unknown
3,638
package dao.impl; import entity.SpecialtyEntity; import dao.SpecialtyDao; import util.JDBCUtil; import java.util.List; import java.util.Map; public class SpecialtyDaoImpl extends JDBCUtil implements SpecialtyDao { @Override public List<Map<String, Object>> getSpecialtyInfo(String name) { String sql; List<Map<String, Object>> mapList; if ("null".equalsIgnoreCase(name)) { sql = "select * from specialty_info"; mapList = queryForList(sql); } else if (name != null && !name.trim().isEmpty()) { sql = "select * from specialty_info where specialty_name like ?"; String specialtyName = "%" + name + "%"; mapList = queryForList(sql, specialtyName); } else { sql = "select * from specialty_info"; mapList = queryForList(sql); } return mapList; } @Override public int addSpecialtyInfo(SpecialtyEntity specialty) { String sql = "insert into specialty_info (id,academy_id,specialty_name,specialty_code) values (?,?,?,?)"; return insert(sql, specialty.getId(), specialty.getAcademyId(), specialty.getSpecialtyName(), specialty.getSpecialtyCode()); } @Override public int updateSpecialtyInfo(SpecialtyEntity specialty) { String sql = "update specialty_info set academy_id = ?,specialty_name = ?,specialty_code = ? where id = ?"; return update(sql, specialty.getAcademyId(), specialty.getSpecialtyName(), specialty.getSpecialtyCode(), specialty.getId()); } @Override public int deleteSpecialty(String specialtyId) { String sql = "delete specialty_info from specialty_info where id = ?"; return delete(sql, specialtyId); } @Override public int batchDeleteSpecialty(List<String> ids) { if (ids == null || ids.isEmpty()) { throw new IllegalArgumentException("ID列表不能为空"); } StringBuilder placeholders = new StringBuilder(); for (int i = 0; i < ids.size(); i++) { placeholders.append("?"); if (i < ids.size() - 1) { placeholders.append(","); } } String sql = "delete from specialty_info where id in (" + placeholders + ")"; return delete(sql, ids.toArray()); } @Override public Map<String, Object> getSpecialtyInfoById(String id) { String sql = "select * from specialty_info where id = ?"; return queryForList(sql, id).get(0); } @Override public List<Map<String, Object>> getSpecialtyByAcademyId(String academyId) { String sql = "select * from specialty_info where academy_id = ?"; return queryForList(sql, academyId); } @Override public String getMaxClassCodeBySpecialtyId(String specialtyId) { String sql = "select class_code from class_info where specialty_id = ? order by class_code Desc"; List<Map<String, Object>> result = queryForList(sql, specialtyId); if (result.isEmpty()) { return null; } return (String) result.get(0).get("class_code"); } }
2301_81295389/student-java-web-backend
src/main/java/dao/impl/SpecialtyDaoImpl.java
Java
unknown
3,150
package dao.impl; import entity.StudentEntity; import dao.StudentDao; import dto.ChooseClassDTO; import util.JDBCUtil; import java.util.List; import java.util.Map; public class StudentDaoImpl extends JDBCUtil implements StudentDao { @Override public List<Map<String, Object>> getAll(String name) { String sql; List<Map<String, Object>> mapList; if ("null".equalsIgnoreCase(name)) { sql = "select * from student_info"; mapList = queryForList(sql); } else if (name != null && !name.trim().isEmpty()) { sql = "select * from student_info where name like ?"; String studentName = "%" + name + "%"; mapList = queryForList(sql, studentName); } else { sql = "select * from student_info"; mapList = queryForList(sql); } return mapList; } @Override public int addStudent(StudentEntity student) { String sql = "insert into student_info(id, student_id, academy_id, specialty_id, class_id, name, gender, age, grade, degree) values (?,?,?,?,?,?,?,?,?,?)"; return insert(sql, student.getId(), student.getStudentId(), student.getAcademyId(), student.getSpecialtyId(), student.getClassId(), student.getName(), student.getGender(), student.getAge(), student.getGrade(), student.getDegree()); } @Override public int deleteStudent(String id) { String sql = "delete student_info from student_info where id = ?"; return delete(sql, id); } @Override public int updateStudent(StudentEntity student) { String sql = "update student_info set student_id = ?, academy_id = ?, specialty_id = ?, class_id = ?,name = ?,gender = ?,age = ?,grade = ?,degree = ? where id = ?"; return update(sql, student.getStudentId(), student.getAcademyId(), student.getSpecialtyId(), student.getClassId(), student.getName(), student.getGender(), student.getAge(), student.getGrade(), student.getDegree(), student.getId()); } @Override public int batchDeleteStudent(List<String> ids) { if (ids == null || ids.isEmpty()) { throw new IllegalArgumentException("ID列表不能为空"); } StringBuilder placeholders = new StringBuilder(); for (int i = 0; i < ids.size(); i++) { placeholders.append("?"); if (i < ids.size() - 1) { placeholders.append(","); } } String sql = "delete from student_info where id in (" + placeholders + ")"; return delete(sql, ids.toArray()); } @Override public int chooseClass(ChooseClassDTO dto) { String sql = "update student_info set class_id = ? where id = ?"; return update(sql,dto.getClassId(),dto.getStudentId()); } }
2301_81295389/student-java-web-backend
src/main/java/dao/impl/StudentDaoImpl.java
Java
unknown
2,805
package dao.impl; import entity.TeacherEntity; import dao.TeacherDao; import util.JDBCUtil; import java.util.List; import java.util.Map; public class TeacherDaoImpl extends JDBCUtil implements TeacherDao { @Override public List<Map<String, Object>> getTeacherInfo(String name) { String sql; List<Map<String, Object>> mapList; if ("null".equalsIgnoreCase(name)) { sql = "select * from teacher_info"; mapList = queryForList(sql); } else if (name != null && !name.trim().isEmpty()) { sql = "select * from teacher_info where teacher_name like ?"; String teacherName = "%" + name + "%"; mapList = queryForList(sql, teacherName); } else { sql = "select * from teacher_info"; mapList = queryForList(sql); } return mapList; } @Override public int addTeacherInfo(TeacherEntity teacher) { String sql = "insert into teacher_info (id,academy_id,teacher_name,age,gender,phone_number,degree) values (?,?,?,?,?,?,?)"; return insert(sql, teacher.getId(), teacher.getAcademyId(), teacher.getTeacherName(), teacher.getAge(), teacher.getGender(), teacher.getPhoneNumber(), teacher.getDegree()); } @Override public int updateTeacherInfo(TeacherEntity teacher) { String sql = "update teacher_info set academy_id = ?,teacher_name = ?,age = ?,gender = ?,phone_number = ?,degree = ? where id = ?"; return update(sql, teacher.getAcademyId(), teacher.getTeacherName(), teacher.getAge(), teacher.getGender(), teacher.getPhoneNumber(), teacher.getDegree(), teacher.getId()); } @Override public int deleteTeacher(String teacherId) { String sql = "delete teacher_info from teacher_info where id = ?"; return delete(sql, teacherId); } @Override public int batchDeleteTeacher(List<String> ids) { if (ids == null || ids.isEmpty()) { throw new IllegalArgumentException("ID列表不能为空"); } StringBuilder placeholders = new StringBuilder(); for (int i = 0; i < ids.size(); i++) { placeholders.append("?"); if (i < ids.size() - 1) { placeholders.append(","); } } String sql = "delete from teacher_info where id in (" + placeholders + ")"; return delete(sql, ids.toArray()); } @Override public List<Map<String, Object>> getTeacherInfoByAcademyId(String academyId) { String sql = "select * from teacher_info where academy_id = ?"; return queryForList(sql,academyId); } @Override public Map<String, Object> getTeacherInfoById(String id) { String sql = "select * from teacher_info where id = ?"; return queryForList(sql,id).get(0); } }
2301_81295389/student-java-web-backend
src/main/java/dao/impl/TeacherDaoImpl.java
Java
unknown
2,838
package dao.impl; import entity.UserEntity; import dao.UserDao; import util.JDBCUtil; import java.util.List; import java.util.Map; public class UserDaoImpl extends JDBCUtil implements UserDao { @Override public int insert(UserEntity user) { String sql = "INSERT INTO user_info (id,username, password) VALUES (?,?,?)"; return insert(sql, user.getId(), user.getUsername(), user.getPassword()); } @Override public UserEntity findByUsername(String username) { String sql = "SELECT * FROM user_info WHERE username = ?"; List<Map<String, Object>> queryForList = queryForList(sql, username); if (queryForList.isEmpty()) { return null; } Map<String, Object> objectMap = queryForList.get(0); return UserEntity.mapToEntity(objectMap); } }
2301_81295389/student-java-web-backend
src/main/java/dao/impl/UserDaoImpl.java
Java
unknown
833
package dto; import lombok.Data; @Data public class ChooseClassDTO { private String studentId; private String classId; }
2301_81295389/student-java-web-backend
src/main/java/dto/ChooseClassDTO.java
Java
unknown
131
package dto; import lombok.Data; @Data public class GetSameGradeClassDTO { private String grade; private String specialtyId; }
2301_81295389/student-java-web-backend
src/main/java/dto/GetSameGradeClassDTO.java
Java
unknown
137
package dto; import lombok.Data; @Data public class UpdateTeacherDTO { private String teacherId; private String academyId; private String teacherName; private Integer age; private Integer gender; private String phoneNumber; private String degree; }
2301_81295389/student-java-web-backend
src/main/java/dto/UpdateTeacherDTO.java
Java
unknown
279