<commit_before>//
//	@file	http_protocol_module_base.cpp
//	@brief	shared object http protocol module absctract class
//
//	Distributed under the Boost Software License, Version 1.0.(See accompanying
//	file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt
//
#include <boost/xpressive/xpressive.hpp>

#include "http_protocol_module_base.h"

using namespace boost::xpressive;

l7vs::http_protocol_module_base::CHECK_RESULT_TAG	l7vs::http_protocol_module_base::check_http_method(	const char* buffer,
													const size_t buffer_len ) const {

	l7vs::http_protocol_module_base::CHECK_RESULT_TAG	check_result = CHECK_OK;

	char*	check_string	= NULL;
	size_t	line_length		= 0;

	cregex	method_regex
		= (	as_xpr("GET")		| as_xpr("HEAD")		| as_xpr("POST")		|
			as_xpr("PUT")		| as_xpr("PROPFIND")	| as_xpr("PROPPATCH")	|
			as_xpr("OPTIONS")	| as_xpr("CONNECT")		| as_xpr("COPY")		|
			as_xpr("TRACE")		| as_xpr("DELETE")		| as_xpr("LOCK")		|
			as_xpr("UNLOCK")	| as_xpr("MOVE")		| as_xpr("MKCOL")) >> _s >>
			+~_s >> _s >>
			"HTTP/" >> _d >> "." >> _d;

	if( buffer != NULL ){

		for( line_length = 0; line_length < buffer_len; line_length++ ){

			if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){

				break;

			}

		}

		if( line_length < buffer_len ){

			check_string = (char*)malloc( line_length + 1 );

			if( check_string != NULL ){
				memcpy( check_string, buffer, line_length );

				check_string[line_length] = '\0';

				if( !regex_match( check_string, method_regex )){

					check_result = CHECK_NG;

				}

				free( check_string );
			}
			else{

				check_result = CHECK_NG;

			}

		}
		else{

			check_result = CHECK_INPOSSIBLE;

		}

	}
	else{

		check_result = CHECK_NG;

	}

	return check_result;

}

l7vs::http_protocol_module_base::CHECK_RESULT_TAG	l7vs::http_protocol_module_base::check_http_version(	const char* buffer,
														const size_t buffer_len ) const {

	l7vs::http_protocol_module_base::CHECK_RESULT_TAG	check_result = CHECK_OK;

	char*	check_string	= NULL;
	size_t	line_length		= 0;

	cregex	version_regex_request
		=	+alpha >> _s >>
			+~_s >> _s >>
			"HTTP/" >> (as_xpr("1.0")|as_xpr("1.1"));

	cregex	version_regex_response
		=	"HTTP/" >> (as_xpr("1.0")|as_xpr("1.1")) >> _s >>
			repeat<3>(_d) >> _s >>
			*_;

	if( buffer != NULL ){

		for( line_length = 0; line_length < buffer_len; line_length++ ){

			if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){

				break;

			}

		}

		if( line_length < buffer_len ){

			check_string = (char*)malloc( line_length + 1 );

			if( check_string != NULL ){

				memcpy( check_string, buffer, line_length );

				check_string[line_length] = '\0';

				if( !regex_match( check_string, version_regex_request ) &&
					!regex_match( check_string, version_regex_response ) ){

					check_result = CHECK_NG;

				}

				free( check_string );

			}
			else{

				check_result = CHECK_NG;

			}

		}
		else{

			check_result = CHECK_INPOSSIBLE;

		}

	}
	else{

		check_result = CHECK_NG;

	}

	return check_result;

}

l7vs::http_protocol_module_base::CHECK_RESULT_TAG	l7vs::http_protocol_module_base::check_status_code(	const char* buffer,
													const size_t buffer_len ) const {

	l7vs::http_protocol_module_base::CHECK_RESULT_TAG	check_result = CHECK_OK;

	char*	check_string	= NULL;
	size_t	line_length		= 0;

	cregex	status_code_regex
 		=	"HTTP/" >> _d >> "." >> _d >> _s >>
			range('1', '3') >> repeat<2>(_d) >> _s >>
			*_;

	if( buffer != NULL ){

		for( line_length = 0; line_length < buffer_len; line_length++ ){

			if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){

				break;

			}

		}

		if( line_length < buffer_len ){

			check_string = (char*)malloc( line_length + 1 );

			if( check_string != NULL ){

				memcpy( check_string, buffer, line_length );

				check_string[line_length] = '\0';

				if( !regex_match( check_string, status_code_regex )){

					check_result = CHECK_NG;

				}

				free( check_string );

			}
			else{

				check_result = CHECK_NG;

			}

		}
		else{

			check_result = CHECK_INPOSSIBLE;

		}

	}
	else{

		check_result = CHECK_NG;

	}

	return check_result;

}

bool	l7vs::http_protocol_module_base::find_uri(	const char* buffer,
													const size_t buffer_len,
													size_t& uri_offset,
													size_t& uri_len){

	bool	find_result	= true;

	char*	find_string	= NULL;
	size_t	line_length	= 0;

	match_results< const char* >	result;

	cregex	uri_regex
		=	+alpha >> _s >>
			(s1 = +~_s) >> _s >>
			"HTTP/" >> _d >> "." >> _d;

	if( buffer != NULL ){

		for( line_length = 0; line_length < buffer_len; line_length++ ){

			if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){

				break;

			}

		}

		if( line_length < buffer_len ){

			find_string = (char*)malloc( line_length + 1 );

			if( find_string != NULL ){

				memcpy( find_string, buffer, line_length );

				find_string[line_length] = '\0';

				find_result = regex_search( find_string, result, uri_regex );

				if( find_result == true ){

					uri_offset	= result.position(1);

					uri_len		= result.length(1);

				}

				free( find_string );

			}
			else{

				find_result = false;

			}

		}
		else{

			find_result = false;

		}

	}
	else{

		find_result = false;

	}

	return find_result;

}

bool	l7vs::http_protocol_module_base::find_status_code(	const char* buffer,
															const size_t buffer_len,
															size_t& status_code_offset,
															size_t& status_code_len){

	bool	find_result	= true;

	char*	find_string	= NULL;
	size_t	line_length	= 0;

	match_results< const char* >	result;

	cregex	status_code_regex
		=	"HTTP/" >> _d >> "." >> _d >> _s >>
			(s1 = repeat<3>(_d)) >> _s >>
			*_;

	if( buffer != NULL ){

		for( line_length = 0; line_length < buffer_len; line_length++ ){

			if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){

				break;

			}

		}

		if( line_length < buffer_len ){

			find_string = (char*)malloc( line_length + 1 );

			if( find_string != NULL ){

				memcpy( find_string, buffer, line_length );

				find_string[line_length] = '\0';

				find_result = regex_search( find_string, result, status_code_regex );

				if( find_result == true ){

					status_code_offset	= result.position(1);

					status_code_len		= result.length(1);

				}

				free( find_string );

			}
			else{

				find_result = false;

			}

		}
		else{

			find_result = false;

		}

	}
	else{

		find_result = false;

	}

	return find_result;

}

bool	l7vs::http_protocol_module_base::find_http_header(	const char* buffer,
															const size_t buffer_len,
															const std::string& http_header_name,
															size_t& http_header_offset,
															size_t& http_header_len ){

	bool	find_result			= true;

	char*	find_string			= NULL;
	size_t	count				= 0;
	size_t	header_begin		= 0;
	size_t	header_end			= 0;
	size_t	header_length		= 0;

	int		header_begin_flag	= 0;
	int		header_end_flag		= 0;

	match_results< const char* >	result;

	cregex	http_header_regex;

	if( buffer != NULL ){

		for( count = 0; count < buffer_len; count++ ){

			if( buffer[count] == '\r' || buffer[count] == '\n' ){

				if( header_begin_flag == 0 ){

					header_begin = count;
					header_begin_flag = 1;

				}

				if( count > 0 ){

					if(	( buffer[count-1] == '\r' && buffer[count] == '\r' ) ||
						( buffer[count-1] == '\n' && buffer[count] == '\n' )	){

						header_end = count;
						header_end_flag = 1;
						break;

					}
				}

				if( count > 2 ){

					if(	buffer[count-3] == '\r' && buffer[count-2] == '\n' &&
						buffer[count-1] == '\r' && buffer[count] == '\n'	){

						header_end = count;
						header_end_flag = 1;
						break;

					}
				}
			}
		}

		if( header_begin_flag == 1 && header_end_flag == 1 ){

			header_length = header_end - header_begin + 1;

			find_string = (char*)malloc( header_length + 1 );

			if( find_string != NULL ){

				memcpy( find_string, buffer + header_begin, header_length );

				find_string[header_length] = '\0';

				if( http_header_name.length() > 0 ){

					http_header_regex = _ln >> (s1 = http_header_name >> _ >> _s >> *~_ln);

					find_result = regex_search( find_string, result, http_header_regex );

					if( find_result == true ){

						http_header_offset	= result.position(1) + header_begin;
						http_header_len		= result.length(1);

					}
				}
				else{

					http_header_regex = _ln >> (s1 = *_ >> ~_ln) >> repeat<2>(_ln);

					find_result = regex_search( find_string, result, http_header_regex );

					if( find_result == true ){

						http_header_offset	= result.position(1) + header_begin;
						http_header_len		= result.length(1);

					}
					else{

						http_header_regex = _ln >> (s1 = _ln);

						find_result = regex_search( find_string, result, http_header_regex );

						if( find_result == true ){

							http_header_offset	= result.position(1) + header_begin;
							http_header_len		= 0;

						}
					}
				}

				free( find_string );

			}
			else{

				find_result	= false;

			}

		}
		else{

			find_result	= false;

		}
	}
	else{

		find_result	= false;

	}

	return find_result;

}
<commit_msg>大文字小文字検索追加<commit_after>//
//	@file	http_protocol_module_base.cpp
//	@brief	shared object http protocol module absctract class
//
//	Distributed under the Boost Software License, Version 1.0.(See accompanying
//	file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt
//
#include <boost/xpressive/xpressive.hpp>

#include "http_protocol_module_base.h"

using namespace boost::xpressive;

l7vs::http_protocol_module_base::CHECK_RESULT_TAG	l7vs::http_protocol_module_base::check_http_method(	const char* buffer,
													const size_t buffer_len ) const {

	l7vs::http_protocol_module_base::CHECK_RESULT_TAG	check_result = CHECK_OK;

	char*	check_string	= NULL;
	size_t	line_length		= 0;

	cregex	method_regex
		= (	as_xpr("GET")		| as_xpr("HEAD")		| as_xpr("POST")		|
			as_xpr("PUT")		| as_xpr("PROPFIND")	| as_xpr("PROPPATCH")	|
			as_xpr("OPTIONS")	| as_xpr("CONNECT")		| as_xpr("COPY")		|
			as_xpr("TRACE")		| as_xpr("DELETE")		| as_xpr("LOCK")		|
			as_xpr("UNLOCK")	| as_xpr("MOVE")		| as_xpr("MKCOL")) >> _s >>
			+~_s >> _s >>
			"HTTP/" >> _d >> "." >> _d;

	if( buffer != NULL ){

		for( line_length = 0; line_length < buffer_len; line_length++ ){

			if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){

				break;

			}

		}

		if( line_length < buffer_len ){

			check_string = (char*)malloc( line_length + 1 );

			if( check_string != NULL ){
				memcpy( check_string, buffer, line_length );

				check_string[line_length] = '\0';

				if( !regex_match( check_string, method_regex )){

					check_result = CHECK_NG;

				}

				free( check_string );
			}
			else{

				check_result = CHECK_NG;

			}

		}
		else{

			check_result = CHECK_INPOSSIBLE;

		}

	}
	else{

		check_result = CHECK_NG;

	}

	return check_result;

}

l7vs::http_protocol_module_base::CHECK_RESULT_TAG	l7vs::http_protocol_module_base::check_http_version(	const char* buffer,
														const size_t buffer_len ) const {

	l7vs::http_protocol_module_base::CHECK_RESULT_TAG	check_result = CHECK_OK;

	char*	check_string	= NULL;
	size_t	line_length		= 0;

	cregex	version_regex_request
		=	+alpha >> _s >>
			+~_s >> _s >>
			"HTTP/" >> (as_xpr("1.0")|as_xpr("1.1"));

	cregex	version_regex_response
		=	"HTTP/" >> (as_xpr("1.0")|as_xpr("1.1")) >> _s >>
			repeat<3>(_d) >> _s >>
			*_;

	if( buffer != NULL ){

		for( line_length = 0; line_length < buffer_len; line_length++ ){

			if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){

				break;

			}

		}

		if( line_length < buffer_len ){

			check_string = (char*)malloc( line_length + 1 );

			if( check_string != NULL ){

				memcpy( check_string, buffer, line_length );

				check_string[line_length] = '\0';

				if( !regex_match( check_string, version_regex_request ) &&
					!regex_match( check_string, version_regex_response ) ){

					check_result = CHECK_NG;

				}

				free( check_string );

			}
			else{

				check_result = CHECK_NG;

			}

		}
		else{

			check_result = CHECK_INPOSSIBLE;

		}

	}
	else{

		check_result = CHECK_NG;

	}

	return check_result;

}

l7vs::http_protocol_module_base::CHECK_RESULT_TAG	l7vs::http_protocol_module_base::check_status_code(	const char* buffer,
													const size_t buffer_len ) const {

	l7vs::http_protocol_module_base::CHECK_RESULT_TAG	check_result = CHECK_OK;

	char*	check_string	= NULL;
	size_t	line_length		= 0;

	cregex	status_code_regex
 		=	"HTTP/" >> _d >> "." >> _d >> _s >>
			range('1', '3') >> repeat<2>(_d) >> _s >>
			*_;

	if( buffer != NULL ){

		for( line_length = 0; line_length < buffer_len; line_length++ ){

			if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){

				break;

			}

		}

		if( line_length < buffer_len ){

			check_string = (char*)malloc( line_length + 1 );

			if( check_string != NULL ){

				memcpy( check_string, buffer, line_length );

				check_string[line_length] = '\0';

				if( !regex_match( check_string, status_code_regex )){

					check_result = CHECK_NG;

				}

				free( check_string );

			}
			else{

				check_result = CHECK_NG;

			}

		}
		else{

			check_result = CHECK_INPOSSIBLE;

		}

	}
	else{

		check_result = CHECK_NG;

	}

	return check_result;

}

bool	l7vs::http_protocol_module_base::find_uri(	const char* buffer,
													const size_t buffer_len,
													size_t& uri_offset,
													size_t& uri_len){

	bool	find_result	= true;

	char*	find_string	= NULL;
	size_t	line_length	= 0;

	match_results< const char* >	result;

	cregex	uri_regex
		=	+alpha >> _s >>
			(s1 = +~_s) >> _s >>
			"HTTP/" >> _d >> "." >> _d;

	if( buffer != NULL ){

		for( line_length = 0; line_length < buffer_len; line_length++ ){

			if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){

				break;

			}

		}

		if( line_length < buffer_len ){

			find_string = (char*)malloc( line_length + 1 );

			if( find_string != NULL ){

				memcpy( find_string, buffer, line_length );

				find_string[line_length] = '\0';

				find_result = regex_search( find_string, result, uri_regex );

				if( find_result == true ){

					uri_offset	= result.position(1);

					uri_len		= result.length(1);

				}

				free( find_string );

			}
			else{

				find_result = false;

			}

		}
		else{

			find_result = false;

		}

	}
	else{

		find_result = false;

	}

	return find_result;

}

bool	l7vs::http_protocol_module_base::find_status_code(	const char* buffer,
															const size_t buffer_len,
															size_t& status_code_offset,
															size_t& status_code_len){

	bool	find_result	= true;

	char*	find_string	= NULL;
	size_t	line_length	= 0;

	match_results< const char* >	result;

	cregex	status_code_regex
		=	"HTTP/" >> _d >> "." >> _d >> _s >>
			(s1 = repeat<3>(_d)) >> _s >>
			*_;

	if( buffer != NULL ){

		for( line_length = 0; line_length < buffer_len; line_length++ ){

			if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){

				break;

			}

		}

		if( line_length < buffer_len ){

			find_string = (char*)malloc( line_length + 1 );

			if( find_string != NULL ){

				memcpy( find_string, buffer, line_length );

				find_string[line_length] = '\0';

				find_result = regex_search( find_string, result, status_code_regex );

				if( find_result == true ){

					status_code_offset	= result.position(1);

					status_code_len		= result.length(1);

				}

				free( find_string );

			}
			else{

				find_result = false;

			}

		}
		else{

			find_result = false;

		}

	}
	else{

		find_result = false;

	}

	return find_result;

}

bool	l7vs::http_protocol_module_base::find_http_header(	const char* buffer,
															const size_t buffer_len,
															const std::string& http_header_name,
															size_t& http_header_offset,
															size_t& http_header_len ){

	bool	find_result			= true;

	char*	find_string			= NULL;
	size_t	count				= 0;
	size_t	header_begin		= 0;
	size_t	header_end			= 0;
	size_t	header_length		= 0;

	int		header_begin_flag	= 0;
	int		header_end_flag		= 0;

	match_results< const char* >	result;

	cregex	http_header_regex;

	if( buffer != NULL ){

		for( count = 0; count < buffer_len; count++ ){

			if( buffer[count] == '\r' || buffer[count] == '\n' ){

				if( header_begin_flag == 0 ){

					header_begin = count;
					header_begin_flag = 1;

				}

				if( count > 0 ){

					if(	( buffer[count-1] == '\r' && buffer[count] == '\r' ) ||
						( buffer[count-1] == '\n' && buffer[count] == '\n' )	){

						header_end = count;
						header_end_flag = 1;
						break;

					}
				}

				if( count > 2 ){

					if(	buffer[count-3] == '\r' && buffer[count-2] == '\n' &&
						buffer[count-1] == '\r' && buffer[count] == '\n'	){

						header_end = count;
						header_end_flag = 1;
						break;

					}
				}
			}
		}

		if( header_begin_flag == 1 && header_end_flag == 1 ){

			header_length = header_end - header_begin + 1;

			find_string = (char*)malloc( header_length + 1 );

			if( find_string != NULL ){

				memcpy( find_string, buffer + header_begin, header_length );

				find_string[header_length] = '\0';

				if( http_header_name.length() > 0 ){

					http_header_regex = _ln >> (s1 = icase(http_header_name) >> ":" >> *~_ln);

					find_result = regex_search( find_string, result, http_header_regex );

					if( find_result == true ){

						http_header_offset	= result.position(1) + header_begin;
						http_header_len		= result.length(1);

					}
				}
				else{

					http_header_regex = _ln >> (s1 = *_ >> ~_ln) >> repeat<2>(_ln);

					find_result = regex_search( find_string, result, http_header_regex );

					if( find_result == true ){

						http_header_offset	= result.position(1) + header_begin;
						http_header_len		= result.length(1);

					}
					else{

						http_header_regex = _ln >> (s1 = _ln);

						find_result = regex_search( find_string, result, http_header_regex );

						if( find_result == true ){

							http_header_offset	= result.position(1) + header_begin;
							http_header_len		= 0;

						}
					}
				}

				free( find_string );

			}
			else{

				find_result	= false;

			}

		}
		else{

			find_result	= false;

		}
	}
	else{

		find_result	= false;

	}

	return find_result;

}
<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetTaskIO.cpp
 */

#include "JPetTaskIO.h"
#include <cassert>
#include "../JPetReader/JPetReader.h"
#include "../JPetTreeHeader/JPetTreeHeader.h"
#include "../JPetTask/JPetTask.h"
#include "../JPetHLDReader/JPetHLDReader.h"
#include "../CommonTools/CommonTools.h"

#include "../JPetLoggerInclude.h"

JPetTaskIO::JPetTaskIO():
  fTask(0),
  fEventNb(-1),
  fWriter(0),
  fReader(0),
  fHeader(0),
  fStatistics(0),
  fParamManager(0)
{
}

void JPetTaskIO::init(const JPetOptions::Options& opts)
{
  setOptions(JPetOptions(opts));
  auto inputFilename = fOptions.getInputFile();
  auto outputFilename = fOptions.getOutputFile();
  createInputObjects(inputFilename);
  createOutputObjects(outputFilename);
}

void JPetTaskIO::exec()
{
  assert(fTask);
  assert(fReader);
  assert(fParamManager);
  fTask->setParamManager(fParamManager);
  JPetTaskInterface::Options emptyOpts;
  fTask->init(emptyOpts); //prepare current task for file
  auto totalEvents = 0ll;
  if (fReader) {
    totalEvents = fReader->getNbOfAllEvents();
  } else {
    WARNING("no JPETReader set totalEvents set to -1");
    totalEvents - 1;
  }
  auto firstEvent = 0ll;
  auto lastEvent = 0ll;
  setUserLimits(fOptions, totalEvents,  firstEvent, lastEvent);
  assert(lastEvent >= 0);
  for (auto i = firstEvent; i <= lastEvent; i++) {
    fTask->setEvent(&(static_cast<TNamed&>(fReader->getCurrentEvent())));
    if (fOptions.isProgressBar()) {
      manageProgressBar(i, lastEvent);
    }
    fTask->exec();
    fReader->nextEvent();
  }
  fTask->terminate();
}

void JPetTaskIO::terminate()
{
  assert(fReader);
  assert(fWriter);
  assert(fHeader);
  assert(fStatistics);

  fWriter->writeHeader(fHeader);

  fWriter->writeObject(fStatistics->getHistogramsTable(), "Stats");

  // store the parametric objects in the ouptut ROOT file
  getParamManager().saveParametersToFile(
    fWriter);
  getParamManager().clearParameters();

  fWriter->closeFile();
  fReader->closeFile();

}
void JPetTaskIO::addSubTask(JPetTaskInterface* subtask) {
	fTask = dynamic_cast<JPetTask*>(subtask);
}
JPetTask* JPetTaskIO::getSubTask() const {
	return fTask;
}

void JPetTaskIO::setOptions(const JPetOptions& opts) {
	fOptions = opts;
}
void JPetTaskIO::setParamManager(JPetParamManager* paramManager) {
	fParamManager = paramManager;
}
JPetParamManager& JPetTaskIO::getParamManager() {
	return *fParamManager;
}

void JPetTaskIO::createInputObjects(const char* inputFilename)
{
  auto treeName = "";
  if (fOptions.getInputFileType() == JPetOptions::kHld ) {
    fReader = new JPetHLDReader;
    treeName = "T";
  } else {
    fReader = new JPetReader;
    treeName = "tree";
  }
  if ( fReader->openFileAndLoadData( inputFilename, treeName )) {
    if (fOptions.getInputFileType() == JPetOptions::kHld ) {
      // create a header to be stored along with the output tree
      fHeader = new JPetTreeHeader(fOptions.getRunNumber());

      // add general info to the Tree header
      fHeader->setBaseFileName(fOptions.getInputFile());

    } else {
      assert(fParamManager);
      fParamManager->readParametersFromFile(dynamic_cast<JPetReader*> (fReader));
      // read the header from the previous analysis stage
      //
      fHeader = dynamic_cast<JPetReader*>(fReader)->getHeaderClone();
      //fParamManager.readParametersFromFile( fReader );
    }
    // create an object for storing histograms and counters during processing
    fStatistics = new JPetStatistics();

    // add info about this module to the processing stages' history in Tree header
    fHeader->addStageInfo(fTask->GetName(), fTask->GetTitle(), 0,
			  CommonTools::getTimeString());

  } else {
    ERROR(inputFilename + std::string(": Unable to open the input file or load the tree"));
    exit(-1);
  }
}

void JPetTaskIO::createOutputObjects(const char* outputFilename)
{
  fWriter = new JPetWriter( outputFilename );
  assert(fWriter);
  if (fTask) {
    fTask->setWriter(fWriter);
    fTask->setStatistics(fStatistics);
  } else {
    WARNING("the subTask does not exist, so Write was not passed to it");
  }
}

void JPetTaskIO::manageProgressBar(long long done, long long end)
{
  printf("\r[%6.4f%% %%]", setProgressBar(done, end));
}

float JPetTaskIO::setProgressBar(int currentEventNumber, int numberOfEvents)
{
  return ( ((float)currentEventNumber) / numberOfEvents ) * 100;
}

const JPetParamBank& JPetTaskIO::getParamBank()
{
  return fParamManager->getParamBank();
}

JPetTaskIO::~JPetTaskIO()
{
  if (fTask) delete fTask;
  if (fWriter) delete fWriter;
  if (fReader) delete fReader;
}

/// Sets values of firstEvent and lastEvent based on user options opts and total number of events from JPetReader
// if the totEventsFromReader is less than 0, than first and last are set to -1.
void JPetTaskIO::setUserLimits(const JPetOptions& opts, const long long kTotEventsFromReader, long long& first, long long& last) const
{
  const auto kLastEvent = opts.getLastEvent();
  const auto kFirstEvent = opts.getFirstEvent();
  if ( kTotEventsFromReader < 1) {
    WARNING("kTotEvetnsFromReader < 1, first and last set to -1");
    first = last = -1;
  } else {
    if ( kFirstEvent < 0) {
      first = 0;
    } else {
      first = kFirstEvent < kTotEventsFromReader ? kFirstEvent : kTotEventsFromReader - 1;
    }
    if (kLastEvent < 0)  {
      last = kTotEventsFromReader - 1;
    } else {
      last = kLastEvent < kTotEventsFromReader ? kLastEvent : kTotEventsFromReader - 1;
    }
  }
  assert(first >= 0);
  assert(last >= 0);
  assert(first <= last);
}
<commit_msg>Set totalEvents to -1. Remove bug.<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetTaskIO.cpp
 */

#include "JPetTaskIO.h"
#include <cassert>
#include "../JPetReader/JPetReader.h"
#include "../JPetTreeHeader/JPetTreeHeader.h"
#include "../JPetTask/JPetTask.h"
#include "../JPetHLDReader/JPetHLDReader.h"
#include "../CommonTools/CommonTools.h"

#include "../JPetLoggerInclude.h"

JPetTaskIO::JPetTaskIO():
  fTask(0),
  fEventNb(-1),
  fWriter(0),
  fReader(0),
  fHeader(0),
  fStatistics(0),
  fParamManager(0)
{
}

void JPetTaskIO::init(const JPetOptions::Options& opts)
{
  setOptions(JPetOptions(opts));
  auto inputFilename = fOptions.getInputFile();
  auto outputFilename = fOptions.getOutputFile();
  createInputObjects(inputFilename);
  createOutputObjects(outputFilename);
}

void JPetTaskIO::exec()
{
  assert(fTask);
  assert(fReader);
  assert(fParamManager);
  fTask->setParamManager(fParamManager);
  JPetTaskInterface::Options emptyOpts;
  fTask->init(emptyOpts); //prepare current task for file
  auto totalEvents = 0ll;
  if (fReader) {
    totalEvents = fReader->getNbOfAllEvents();
  } else {
    WARNING("no JPETReader set totalEvents set to -1");
    totalEvents = -1;
  }
  auto firstEvent = 0ll;
  auto lastEvent = 0ll;
  setUserLimits(fOptions, totalEvents,  firstEvent, lastEvent);
  assert(lastEvent >= 0);
  for (auto i = firstEvent; i <= lastEvent; i++) {
    fTask->setEvent(&(static_cast<TNamed&>(fReader->getCurrentEvent())));
    if (fOptions.isProgressBar()) {
      manageProgressBar(i, lastEvent);
    }
    fTask->exec();
    fReader->nextEvent();
  }
  fTask->terminate();
}

void JPetTaskIO::terminate()
{
  assert(fReader);
  assert(fWriter);
  assert(fHeader);
  assert(fStatistics);

  fWriter->writeHeader(fHeader);

  fWriter->writeObject(fStatistics->getHistogramsTable(), "Stats");

  // store the parametric objects in the ouptut ROOT file
  getParamManager().saveParametersToFile(
    fWriter);
  getParamManager().clearParameters();

  fWriter->closeFile();
  fReader->closeFile();

}
void JPetTaskIO::addSubTask(JPetTaskInterface* subtask) {
	fTask = dynamic_cast<JPetTask*>(subtask);
}
JPetTask* JPetTaskIO::getSubTask() const {
	return fTask;
}

void JPetTaskIO::setOptions(const JPetOptions& opts) {
	fOptions = opts;
}
void JPetTaskIO::setParamManager(JPetParamManager* paramManager) {
	fParamManager = paramManager;
}
JPetParamManager& JPetTaskIO::getParamManager() {
	return *fParamManager;
}

void JPetTaskIO::createInputObjects(const char* inputFilename)
{
  auto treeName = "";
  if (fOptions.getInputFileType() == JPetOptions::kHld ) {
    fReader = new JPetHLDReader;
    treeName = "T";
  } else {
    fReader = new JPetReader;
    treeName = "tree";
  }
  if ( fReader->openFileAndLoadData( inputFilename, treeName )) {
    if (fOptions.getInputFileType() == JPetOptions::kHld ) {
      // create a header to be stored along with the output tree
      fHeader = new JPetTreeHeader(fOptions.getRunNumber());

      // add general info to the Tree header
      fHeader->setBaseFileName(fOptions.getInputFile());

    } else {
      assert(fParamManager);
      fParamManager->readParametersFromFile(dynamic_cast<JPetReader*> (fReader));
      // read the header from the previous analysis stage
      //
      fHeader = dynamic_cast<JPetReader*>(fReader)->getHeaderClone();
      //fParamManager.readParametersFromFile( fReader );
    }
    // create an object for storing histograms and counters during processing
    fStatistics = new JPetStatistics();

    // add info about this module to the processing stages' history in Tree header
    fHeader->addStageInfo(fTask->GetName(), fTask->GetTitle(), 0,
			  CommonTools::getTimeString());

  } else {
    ERROR(inputFilename + std::string(": Unable to open the input file or load the tree"));
    exit(-1);
  }
}

void JPetTaskIO::createOutputObjects(const char* outputFilename)
{
  fWriter = new JPetWriter( outputFilename );
  assert(fWriter);
  if (fTask) {
    fTask->setWriter(fWriter);
    fTask->setStatistics(fStatistics);
  } else {
    WARNING("the subTask does not exist, so Write was not passed to it");
  }
}

void JPetTaskIO::manageProgressBar(long long done, long long end)
{
  printf("\r[%6.4f%% %%]", setProgressBar(done, end));
}

float JPetTaskIO::setProgressBar(int currentEventNumber, int numberOfEvents)
{
  return ( ((float)currentEventNumber) / numberOfEvents ) * 100;
}

const JPetParamBank& JPetTaskIO::getParamBank()
{
  return fParamManager->getParamBank();
}

JPetTaskIO::~JPetTaskIO()
{
  if (fTask) delete fTask;
  if (fWriter) delete fWriter;
  if (fReader) delete fReader;
}

/// Sets values of firstEvent and lastEvent based on user options opts and total number of events from JPetReader
// if the totEventsFromReader is less than 0, than first and last are set to -1.
void JPetTaskIO::setUserLimits(const JPetOptions& opts, const long long kTotEventsFromReader, long long& first, long long& last) const
{
  const auto kLastEvent = opts.getLastEvent();
  const auto kFirstEvent = opts.getFirstEvent();
  if ( kTotEventsFromReader < 1) {
    WARNING("kTotEvetnsFromReader < 1, first and last set to -1");
    first = last = -1;
  } else {
    if ( kFirstEvent < 0) {
      first = 0;
    } else {
      first = kFirstEvent < kTotEventsFromReader ? kFirstEvent : kTotEventsFromReader - 1;
    }
    if (kLastEvent < 0)  {
      last = kTotEventsFromReader - 1;
    } else {
      last = kLastEvent < kTotEventsFromReader ? kLastEvent : kTotEventsFromReader - 1;
    }
  }
  assert(first >= 0);
  assert(last >= 0);
  assert(first <= last);
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/audio_coding/main/acm2/codec_owner.h"

#include "webrtc/base/checks.h"
#include "webrtc/engine_configurations.h"
#include "webrtc/modules/audio_coding/codecs/cng/include/audio_encoder_cng.h"
#include "webrtc/modules/audio_coding/codecs/g711/include/audio_encoder_pcm.h"
#include "webrtc/modules/audio_coding/codecs/g722/include/audio_encoder_g722.h"
#include "webrtc/modules/audio_coding/codecs/ilbc/interface/audio_encoder_ilbc.h"
#include "webrtc/modules/audio_coding/codecs/isac/fix/interface/audio_encoder_isacfix.h"
#include "webrtc/modules/audio_coding/codecs/isac/main/interface/audio_encoder_isac.h"
#include "webrtc/modules/audio_coding/codecs/opus/interface/audio_encoder_opus.h"
#include "webrtc/modules/audio_coding/codecs/pcm16b/include/audio_encoder_pcm16b.h"
#include "webrtc/modules/audio_coding/codecs/red/audio_encoder_copy_red.h"

namespace webrtc {
namespace acm2 {

namespace {
bool IsIsac(const CodecInst& codec) {
  return
#if (defined(WEBRTC_CODEC_ISAC) || defined(WEBRTC_CODEC_ISACFX))
      !STR_CASE_CMP(codec.plname, "isac") ||
#endif
      false;
}

bool IsOpus(const CodecInst& codec) {
  return
#ifdef WEBRTC_CODEC_OPUS
      !STR_CASE_CMP(codec.plname, "opus") ||
#endif
      false;
}

bool IsPcmU(const CodecInst& codec) {
  return !STR_CASE_CMP(codec.plname, "pcmu");
}

bool IsPcmA(const CodecInst& codec) {
  return !STR_CASE_CMP(codec.plname, "pcma");
}

bool IsPcm16B(const CodecInst& codec) {
  return
#ifdef WEBRTC_CODEC_PCM16
      !STR_CASE_CMP(codec.plname, "l16") ||
#endif
      false;
}

bool IsIlbc(const CodecInst& codec) {
  return
#ifdef WEBRTC_CODEC_ILBC
      !STR_CASE_CMP(codec.plname, "ilbc") ||
#endif
      false;
}

bool IsG722(const CodecInst& codec) {
  return
#ifdef WEBRTC_CODEC_G722
      !STR_CASE_CMP(codec.plname, "g722") ||
#endif
      false;
}
}  // namespace

CodecOwner::CodecOwner()
    : isac_is_encoder_(false), external_speech_encoder_(nullptr) {
}

CodecOwner::~CodecOwner() = default;

namespace {
AudioEncoderDecoderMutableIsac* CreateIsacCodec(const CodecInst& speech_inst) {
#if defined(WEBRTC_CODEC_ISACFX)
  return new AudioEncoderDecoderMutableIsacFix(speech_inst);
#elif defined(WEBRTC_CODEC_ISAC)
  return new AudioEncoderDecoderMutableIsacFloat(speech_inst);
#else
  FATAL() << "iSAC is not supported.";
  return nullptr;
#endif
}

void CreateSpeechEncoder(
    const CodecInst& speech_inst,
    rtc::scoped_ptr<AudioEncoderMutable>* speech_encoder,
    rtc::scoped_ptr<AudioEncoderDecoderMutableIsac>* isac_codec,
    bool* isac_is_encoder) {
  if (IsIsac(speech_inst)) {
    if (*isac_codec) {
      (*isac_codec)->UpdateSettings(speech_inst);
    } else {
      isac_codec->reset(CreateIsacCodec(speech_inst));
    }
    *isac_is_encoder = true;
    speech_encoder->reset();
    return;
  }
  if (IsOpus(speech_inst)) {
    speech_encoder->reset(new AudioEncoderMutableOpus(speech_inst));
  } else if (IsPcmU(speech_inst)) {
    speech_encoder->reset(new AudioEncoderMutablePcmU(speech_inst));
  } else if (IsPcmA(speech_inst)) {
    speech_encoder->reset(new AudioEncoderMutablePcmA(speech_inst));
  } else if (IsPcm16B(speech_inst)) {
    speech_encoder->reset(new AudioEncoderMutablePcm16B(speech_inst));
  } else if (IsIlbc(speech_inst)) {
    speech_encoder->reset(new AudioEncoderMutableIlbc(speech_inst));
  } else if (IsG722(speech_inst)) {
    speech_encoder->reset(new AudioEncoderMutableG722(speech_inst));
  } else {
    FATAL();
  }
  *isac_is_encoder = false;
}

AudioEncoder* CreateRedEncoder(int red_payload_type,
                               AudioEncoder* encoder,
                               rtc::scoped_ptr<AudioEncoder>* red_encoder) {
  if (red_payload_type == -1) {
    red_encoder->reset();
    return encoder;
  }
  AudioEncoderCopyRed::Config config;
  config.payload_type = red_payload_type;
  config.speech_encoder = encoder;
  red_encoder->reset(new AudioEncoderCopyRed(config));
  return red_encoder->get();
}

void CreateCngEncoder(int cng_payload_type,
                      ACMVADMode vad_mode,
                      AudioEncoder* encoder,
                      rtc::scoped_ptr<AudioEncoder>* cng_encoder) {
  if (cng_payload_type == -1) {
    cng_encoder->reset();
    return;
  }
  AudioEncoderCng::Config config;
  config.num_channels = encoder->NumChannels();
  config.payload_type = cng_payload_type;
  config.speech_encoder = encoder;
  switch (vad_mode) {
    case VADNormal:
      config.vad_mode = Vad::kVadNormal;
      break;
    case VADLowBitrate:
      config.vad_mode = Vad::kVadLowBitrate;
      break;
    case VADAggr:
      config.vad_mode = Vad::kVadAggressive;
      break;
    case VADVeryAggr:
      config.vad_mode = Vad::kVadVeryAggressive;
      break;
    default:
      FATAL();
  }
  cng_encoder->reset(new AudioEncoderCng(config));
}
}  // namespace

void CodecOwner::SetEncoders(const CodecInst& speech_inst,
                             int cng_payload_type,
                             ACMVADMode vad_mode,
                             int red_payload_type) {
  CreateSpeechEncoder(speech_inst, &speech_encoder_, &isac_codec_,
                      &isac_is_encoder_);
  external_speech_encoder_ = nullptr;
  ChangeCngAndRed(cng_payload_type, vad_mode, red_payload_type);
}

void CodecOwner::SetEncoders(AudioEncoderMutable* external_speech_encoder,
                             int cng_payload_type,
                             ACMVADMode vad_mode,
                             int red_payload_type) {
  external_speech_encoder_ = external_speech_encoder;
  speech_encoder_.reset();
  isac_is_encoder_ = false;
  ChangeCngAndRed(cng_payload_type, vad_mode, red_payload_type);
}

void CodecOwner::ChangeCngAndRed(int cng_payload_type,
                                 ACMVADMode vad_mode,
                                 int red_payload_type) {
  AudioEncoder* encoder =
      CreateRedEncoder(red_payload_type, SpeechEncoder(), &red_encoder_);
  CreateCngEncoder(cng_payload_type, vad_mode, encoder, &cng_encoder_);
  int num_true =
      !!speech_encoder_ + !!external_speech_encoder_ + isac_is_encoder_;
  DCHECK_EQ(num_true, 1);
  DCHECK(!isac_is_encoder_ || isac_codec_);
}

AudioDecoder* CodecOwner::GetIsacDecoder() {
  if (!isac_codec_) {
    DCHECK(!isac_is_encoder_);
    // None of the parameter values in |speech_inst| matter when the codec is
    // used only as a decoder.
    CodecInst speech_inst;
    speech_inst.plfreq = 16000;
    speech_inst.rate = -1;
    speech_inst.pacsize = 480;
    isac_codec_.reset(CreateIsacCodec(speech_inst));
  }
  return isac_codec_.get();
}

AudioEncoder* CodecOwner::Encoder() {
  const auto& const_this = *this;
  return const_cast<AudioEncoder*>(const_this.Encoder());
}

const AudioEncoder* CodecOwner::Encoder() const {
  if (cng_encoder_)
    return cng_encoder_.get();
  if (red_encoder_)
    return red_encoder_.get();
  return SpeechEncoder();
}

AudioEncoderMutable* CodecOwner::SpeechEncoder() {
  const auto& const_this = *this;
  return const_cast<AudioEncoderMutable*>(const_this.SpeechEncoder());
}

const AudioEncoderMutable* CodecOwner::SpeechEncoder() const {
  int num_true =
      !!speech_encoder_ + !!external_speech_encoder_ + isac_is_encoder_;
  DCHECK_GE(num_true, 0);
  DCHECK_LE(num_true, 1);
  if (external_speech_encoder_)
    return external_speech_encoder_;
  if (speech_encoder_)
    return speech_encoder_.get();
  return isac_is_encoder_ ? isac_codec_.get() : nullptr;
}

}  // namespace acm2
}  // namespace webrtc
<commit_msg>Reset speech encoder before hooking it up to RED or CNG<commit_after>/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/audio_coding/main/acm2/codec_owner.h"

#include "webrtc/base/checks.h"
#include "webrtc/engine_configurations.h"
#include "webrtc/modules/audio_coding/codecs/cng/include/audio_encoder_cng.h"
#include "webrtc/modules/audio_coding/codecs/g711/include/audio_encoder_pcm.h"
#include "webrtc/modules/audio_coding/codecs/g722/include/audio_encoder_g722.h"
#include "webrtc/modules/audio_coding/codecs/ilbc/interface/audio_encoder_ilbc.h"
#include "webrtc/modules/audio_coding/codecs/isac/fix/interface/audio_encoder_isacfix.h"
#include "webrtc/modules/audio_coding/codecs/isac/main/interface/audio_encoder_isac.h"
#include "webrtc/modules/audio_coding/codecs/opus/interface/audio_encoder_opus.h"
#include "webrtc/modules/audio_coding/codecs/pcm16b/include/audio_encoder_pcm16b.h"
#include "webrtc/modules/audio_coding/codecs/red/audio_encoder_copy_red.h"

namespace webrtc {
namespace acm2 {

namespace {
bool IsIsac(const CodecInst& codec) {
  return
#if (defined(WEBRTC_CODEC_ISAC) || defined(WEBRTC_CODEC_ISACFX))
      !STR_CASE_CMP(codec.plname, "isac") ||
#endif
      false;
}

bool IsOpus(const CodecInst& codec) {
  return
#ifdef WEBRTC_CODEC_OPUS
      !STR_CASE_CMP(codec.plname, "opus") ||
#endif
      false;
}

bool IsPcmU(const CodecInst& codec) {
  return !STR_CASE_CMP(codec.plname, "pcmu");
}

bool IsPcmA(const CodecInst& codec) {
  return !STR_CASE_CMP(codec.plname, "pcma");
}

bool IsPcm16B(const CodecInst& codec) {
  return
#ifdef WEBRTC_CODEC_PCM16
      !STR_CASE_CMP(codec.plname, "l16") ||
#endif
      false;
}

bool IsIlbc(const CodecInst& codec) {
  return
#ifdef WEBRTC_CODEC_ILBC
      !STR_CASE_CMP(codec.plname, "ilbc") ||
#endif
      false;
}

bool IsG722(const CodecInst& codec) {
  return
#ifdef WEBRTC_CODEC_G722
      !STR_CASE_CMP(codec.plname, "g722") ||
#endif
      false;
}
}  // namespace

CodecOwner::CodecOwner()
    : isac_is_encoder_(false), external_speech_encoder_(nullptr) {
}

CodecOwner::~CodecOwner() = default;

namespace {
AudioEncoderDecoderMutableIsac* CreateIsacCodec(const CodecInst& speech_inst) {
#if defined(WEBRTC_CODEC_ISACFX)
  return new AudioEncoderDecoderMutableIsacFix(speech_inst);
#elif defined(WEBRTC_CODEC_ISAC)
  return new AudioEncoderDecoderMutableIsacFloat(speech_inst);
#else
  FATAL() << "iSAC is not supported.";
  return nullptr;
#endif
}

void CreateSpeechEncoder(
    const CodecInst& speech_inst,
    rtc::scoped_ptr<AudioEncoderMutable>* speech_encoder,
    rtc::scoped_ptr<AudioEncoderDecoderMutableIsac>* isac_codec,
    bool* isac_is_encoder) {
  if (IsIsac(speech_inst)) {
    if (*isac_codec) {
      (*isac_codec)->UpdateSettings(speech_inst);
    } else {
      isac_codec->reset(CreateIsacCodec(speech_inst));
    }
    *isac_is_encoder = true;
    speech_encoder->reset();
    return;
  }
  if (IsOpus(speech_inst)) {
    speech_encoder->reset(new AudioEncoderMutableOpus(speech_inst));
  } else if (IsPcmU(speech_inst)) {
    speech_encoder->reset(new AudioEncoderMutablePcmU(speech_inst));
  } else if (IsPcmA(speech_inst)) {
    speech_encoder->reset(new AudioEncoderMutablePcmA(speech_inst));
  } else if (IsPcm16B(speech_inst)) {
    speech_encoder->reset(new AudioEncoderMutablePcm16B(speech_inst));
  } else if (IsIlbc(speech_inst)) {
    speech_encoder->reset(new AudioEncoderMutableIlbc(speech_inst));
  } else if (IsG722(speech_inst)) {
    speech_encoder->reset(new AudioEncoderMutableG722(speech_inst));
  } else {
    FATAL();
  }
  *isac_is_encoder = false;
}

AudioEncoder* CreateRedEncoder(int red_payload_type,
                               AudioEncoder* encoder,
                               rtc::scoped_ptr<AudioEncoder>* red_encoder) {
  if (red_payload_type == -1) {
    red_encoder->reset();
    return encoder;
  }
  AudioEncoderCopyRed::Config config;
  config.payload_type = red_payload_type;
  config.speech_encoder = encoder;
  red_encoder->reset(new AudioEncoderCopyRed(config));
  return red_encoder->get();
}

void CreateCngEncoder(int cng_payload_type,
                      ACMVADMode vad_mode,
                      AudioEncoder* encoder,
                      rtc::scoped_ptr<AudioEncoder>* cng_encoder) {
  if (cng_payload_type == -1) {
    cng_encoder->reset();
    return;
  }
  AudioEncoderCng::Config config;
  config.num_channels = encoder->NumChannels();
  config.payload_type = cng_payload_type;
  config.speech_encoder = encoder;
  switch (vad_mode) {
    case VADNormal:
      config.vad_mode = Vad::kVadNormal;
      break;
    case VADLowBitrate:
      config.vad_mode = Vad::kVadLowBitrate;
      break;
    case VADAggr:
      config.vad_mode = Vad::kVadAggressive;
      break;
    case VADVeryAggr:
      config.vad_mode = Vad::kVadVeryAggressive;
      break;
    default:
      FATAL();
  }
  cng_encoder->reset(new AudioEncoderCng(config));
}
}  // namespace

void CodecOwner::SetEncoders(const CodecInst& speech_inst,
                             int cng_payload_type,
                             ACMVADMode vad_mode,
                             int red_payload_type) {
  CreateSpeechEncoder(speech_inst, &speech_encoder_, &isac_codec_,
                      &isac_is_encoder_);
  external_speech_encoder_ = nullptr;
  ChangeCngAndRed(cng_payload_type, vad_mode, red_payload_type);
}

void CodecOwner::SetEncoders(AudioEncoderMutable* external_speech_encoder,
                             int cng_payload_type,
                             ACMVADMode vad_mode,
                             int red_payload_type) {
  external_speech_encoder_ = external_speech_encoder;
  speech_encoder_.reset();
  isac_is_encoder_ = false;
  ChangeCngAndRed(cng_payload_type, vad_mode, red_payload_type);
}

void CodecOwner::ChangeCngAndRed(int cng_payload_type,
                                 ACMVADMode vad_mode,
                                 int red_payload_type) {
  AudioEncoderMutable* speech_encoder = SpeechEncoder();
  if (cng_payload_type != -1 || red_payload_type != -1) {
    // The RED and CNG encoders need to be in sync with the speech encoder, so
    // reset the latter to ensure its buffer is empty.
    speech_encoder->Reset();
  }
  AudioEncoder* encoder =
      CreateRedEncoder(red_payload_type, speech_encoder, &red_encoder_);
  CreateCngEncoder(cng_payload_type, vad_mode, encoder, &cng_encoder_);
  int num_true =
      !!speech_encoder_ + !!external_speech_encoder_ + isac_is_encoder_;
  DCHECK_EQ(num_true, 1);
  DCHECK(!isac_is_encoder_ || isac_codec_);
}

AudioDecoder* CodecOwner::GetIsacDecoder() {
  if (!isac_codec_) {
    DCHECK(!isac_is_encoder_);
    // None of the parameter values in |speech_inst| matter when the codec is
    // used only as a decoder.
    CodecInst speech_inst;
    speech_inst.plfreq = 16000;
    speech_inst.rate = -1;
    speech_inst.pacsize = 480;
    isac_codec_.reset(CreateIsacCodec(speech_inst));
  }
  return isac_codec_.get();
}

AudioEncoder* CodecOwner::Encoder() {
  const auto& const_this = *this;
  return const_cast<AudioEncoder*>(const_this.Encoder());
}

const AudioEncoder* CodecOwner::Encoder() const {
  if (cng_encoder_)
    return cng_encoder_.get();
  if (red_encoder_)
    return red_encoder_.get();
  return SpeechEncoder();
}

AudioEncoderMutable* CodecOwner::SpeechEncoder() {
  const auto& const_this = *this;
  return const_cast<AudioEncoderMutable*>(const_this.SpeechEncoder());
}

const AudioEncoderMutable* CodecOwner::SpeechEncoder() const {
  int num_true =
      !!speech_encoder_ + !!external_speech_encoder_ + isac_is_encoder_;
  DCHECK_GE(num_true, 0);
  DCHECK_LE(num_true, 1);
  if (external_speech_encoder_)
    return external_speech_encoder_;
  if (speech_encoder_)
    return speech_encoder_.get();
  return isac_is_encoder_ ? isac_codec_.get() : nullptr;
}

}  // namespace acm2
}  // namespace webrtc
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright( C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
//(including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort(including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

/*
  definition of the current version of OpenCV
  Usefull to test in user programs
*/

#ifndef __OPENCV_VERSION_HPP__
#define __OPENCV_VERSION_HPP__

#define CV_MAJOR_VERSION    2
#define CV_MINOR_VERSION    4
#define CV_SUBMINOR_VERSION 0

#define CVAUX_STR_EXP(__A)  #__A
#define CVAUX_STR(__A)      CVAUX_STR_EXP(__A)
#define CV_VERSION          CVAUX_STR(CV_MAJOR_VERSION) "." CVAUX_STR(CV_MINOR_VERSION) "." CVAUX_STR(CV_SUBMINOR_VERSION)

#endif
<commit_msg>Version of 2.4 branch is adjusted to 2.4.1<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright( C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
//(including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort(including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

/*
  definition of the current version of OpenCV
  Usefull to test in user programs
*/

#ifndef __OPENCV_VERSION_HPP__
#define __OPENCV_VERSION_HPP__

#define CV_MAJOR_VERSION    2
#define CV_MINOR_VERSION    4
#define CV_SUBMINOR_VERSION 1

#define CVAUX_STR_EXP(__A)  #__A
#define CVAUX_STR(__A)      CVAUX_STR_EXP(__A)
#define CV_VERSION          CVAUX_STR(CV_MAJOR_VERSION) "." CVAUX_STR(CV_MINOR_VERSION) "." CVAUX_STR(CV_SUBMINOR_VERSION)

#endif
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2013 IIT - Istituto Italiano di Tecnologia - http://www.iit.it
 * Author: Silvio Traversaro
 * CopyPolicy: Released under the terms of the GNU LGPL v2.0 (or any later version)
 *
 * The development of this software was supported by the FP7 EU project
 * CoDyCo (No. 600716 ICT 2011.2.1 Cognitive Systems and Robotics (b))
 * http://www.codyco.eu
 */

#include "kdl_codyco/regressors/torqueRegressor.hpp"

#include "kdl_codyco/regressor_utils.hpp"

#include "iDynTree/Sensors/Sensors.h"
#include "iDynTree/Sensors/SixAxisFTSensor.h"
#include "kdl_codyco/KDLConversions.h"
#include "iDynTree/Core/Transform.h"
#include "iDynTree/Core/Wrench.h"

#include "dirl_utils.hpp"

#include <iostream>

using namespace KDL::CoDyCo;

namespace KDL {
namespace CoDyCo {
namespace Regressors {

bool torqueRegressor::isActiveFTSensor(const int ft_sensor_id) const
{
    unsigned int NrOfFTSensors = p_sensors_tree->getNrOfSensors(iDynTree::SIX_AXIS_FORCE_TORQUE);
    if( activated_ft_sensors.size() !=  NrOfFTSensors)
    {
        return false;
    }

    if( ft_sensor_id < 0 ||
        ft_sensor_id >= NrOfFTSensors )
    {
        return false;
    }

    return activated_ft_sensors[ft_sensor_id];
}

int torqueRegressor::configure()
{
    const KDL::CoDyCo::UndirectedTree & undirected_tree = *p_undirected_tree;
    const iDynTree::SensorsList  & sensors_tree = *p_sensors_tree;

    //Now store all the links that belong to the subtree
    //We first compute the spanning starting at one (the first) of the leafs
    KDL::CoDyCo::Traversal subtree_traversal;

    JunctionMap::const_iterator torque_jnt = undirected_tree.getJunction(torque_dof);
    if( torque_jnt == undirected_tree.getInvalidJunctionIterator() ) {
        if(verbose) { std::cerr << "torqueRegressor error: specified joint " << torque_dof << " not found " << std::endl; }
        return -1;
    }

    torque_dof_index = torque_jnt->getJunctionIndex();

    relative_junction.resize(1);
    relative_junction[0] = torque_dof_index;

    if( torque_dof_index < 0 || torque_dof_index >= (int)undirected_tree.getNrOfDOFs() ) {
         if(verbose) { std::cerr << "torqueRegressor error: specified joint " << torque_dof << " has no degrees of freedom " << std::endl; }
        return -1;
    }

    int link_parent_id = torque_jnt->getParentLink()->getLinkIndex();
    int link_child_id = torque_jnt->getChildLink()->getLinkIndex();

    if( !reverse_direction )
    {
        subtree_root_link_id = link_child_id;
    }
    else
    {
        subtree_root_link_id = link_parent_id;
    }

    undirected_tree.compute_traversal(subtree_traversal,subtree_root_link_id);

    //Then we color the nodes: if white (true) the links belongs to the subtree
    //if black (false) it does not belongs to the node
    std::vector<bool> is_link_in_subtree(undirected_tree.getNrOfLinks(),false);

    //the leaf that we chose as starting link clearly belongs to the subtree
    is_link_in_subtree[subtree_root_link_id] = true;

    //then, all the other links can be classified using the following rules:
    for(int i=1; i < (int)subtree_traversal.getNrOfVisitedLinks(); i++ )
    {
        int link_id = subtree_traversal.getOrderedLink(i)->getLinkIndex();
        int parent_id = subtree_traversal.getParentLink(link_id)->getLinkIndex();

        if( is_link_in_subtree[parent_id] == false )
        {
            //if the parent is not in the subtree (false/black) then the link is not in the subtree (false/black)
            is_link_in_subtree[link_id] = false;
        }
        else
        {
            int junction_index = undirected_tree.getLink(link_id)->getAdjacentJoint(undirected_tree.getLink(parent_id))->getJunctionIndex();

            int ft_sensor_index = getFTIndexFromJunctionIndex(*p_sensors_tree,junction_index);
            if( ft_sensor_index >= 0 && isActiveFTSensor(ft_sensor_index) )
            {
                //if the parent is in the subtree (true/white) but it is connected to the link by an activated FT sensor
                is_link_in_subtree[link_id] = false;
                //In this case we have to add the parent to subtree_leaf_links_indeces
                subtree_leaf_links_indeces.push_back(parent_id);

            }
            else if ( junction_index == torque_dof_index )
            {
                //or if the parent is connected trought the torque regressor dof
                is_link_in_subtree[link_id] = false;
            }
            else
            {
                //otherwise the link is in the subtree (true/white)
                is_link_in_subtree[link_id] = true;
            }
        }
    }

    //after all the links belonging to the subtree have been identified, it is possible to save only the id of the one in the subtree
    assert( subtree_links_indices.size() == 0 );
    for( int i=0; i < (int)is_link_in_subtree.size(); i++ )
    {
        if( is_link_in_subtree[i] ) {
            subtree_links_indices.push_back(i);
        }
    }

    iDynTree::Regressors::DynamicsRegressorParametersList localSerialization = getLegacyUsedParameters(linkIndeces2regrCols,
                                p_sensors_tree->getNrOfSensors(iDynTree::SIX_AXIS_FORCE_TORQUE),
                                this->consider_ft_offset);

    regressor_local_parametrization.resize(getNrOfOutputs(),localSerialization.parameters.size());

    return 0;
}

int torqueRegressor::getNrOfOutputs()
{
    return 1;
}

std::vector<int> torqueRegressor::getRelativeJunctions()
{
    return relative_junction;
}

iDynTree::Regressors::DynamicsRegressorParametersList torqueRegressor::getUsedParameters()
{
    assert(p_undirected_tree->getNrOfLinks() == linkIndeces2regrCols.size());

    return getLegacyUsedParameters(linkIndeces2regrCols,
                                   activated_ft_sensors.size(),
                                   this->consider_ft_offset);
}

int torqueRegressor::computeRegressor(const KDL::JntArray &q,
                                      const KDL::JntArray &/*q_dot*/,
                                      const KDL::JntArray &/*q_dotdot*/,
                                      const std::vector<KDL::Frame> & X_dynamic_base,
                                      const std::vector<KDL::Twist> & v,
                                      const std::vector<KDL::Twist> & a,
                                      const iDynTree::SensorsMeasurements & measured_wrenches,
                                      const KDL::JntArray & measured_torques,
                                      Eigen::MatrixXd & regressor_matrix_global_column_serialization,
                                      Eigen::VectorXd & known_terms)
{
#ifdef NDEBUG
    if( verbose ) std::cerr << "Called torqueRegressor::computeRegressor " << std::endl;
#endif
    //const KDL::CoDyCo::UndirectedTree &  = *p_undirected_tree;
    //const KDL::CoDyCo::FTSensorList & ft_list = *p_ft_list;

    assert( regressor_local_parametrization.rows() == getNrOfOutputs() );

     /**
     * \todo move this stuff in UndirectedTree
     *
     */
    JunctionMap::const_iterator torque_dof_it = p_undirected_tree->getJunction(torque_dof_index);
    LinkMap::const_iterator parent_root_it;
    if( torque_dof_it->getChildLink() == p_undirected_tree->getLink(subtree_root_link_id) ) {
        parent_root_it = torque_dof_it->getParentLink();
    } else {
        parent_root_it = torque_dof_it->getChildLink();
    }
    assert(torque_dof_it->getJunctionIndex() < (int)p_undirected_tree->getNrOfDOFs());
    KDL::Twist S = parent_root_it->S(p_undirected_tree->getLink(subtree_root_link_id),q(torque_dof_it->getJunctionIndex()));

    //all other columns, beside the one relative to the inertial parameters of the links of the subtree, are zero
    regressor_local_parametrization.setZero();

    for(int i =0; i < (int)subtree_links_indices.size(); i++ ) {
        int link_id = subtree_links_indices[i];

        if( linkIndeces2regrCols[link_id] != -1 ) {
            #ifdef NDEBUG
            if( verbose ) std::cerr << "Adding to the torque regressor of joint " << torque_dof_it->getName() << " the regressor relative to link " << p_undirected_tree->getLink(link_id)->getName() << std::endl;
            #endif

            Eigen::Matrix<double,6,10> netWrenchRegressor_i = netWrenchRegressor(v[link_id],a[link_id]);
            regressor_local_parametrization.block(0,(int)(10*linkIndeces2regrCols[link_id]),getNrOfOutputs(),10)
                = toEigen(S).transpose()*WrenchTransformationMatrix(X_dynamic_base[subtree_root_link_id].Inverse()*X_dynamic_base[link_id])*netWrenchRegressor_i;
        }
    }

#ifdef NDEBUG
    if( consider_ft_offset ) {
        if( verbose ) std::cerr << "considering ft offset" << std::endl;
    } else {
        if( verbose ) std::cerr << "not considering ft offset" << std::endl;
    }
#endif
    // if the ft offset is condidered, we have to set also the columns relative to the offset
    // For each subgraph, we consider the measured wrenches as the one excerted from the rest of the
    // tree to the considered subtree
    // So the sign of the offset should be consistent with the other place where it is defined.
    // In particular, the offset of a sensor is considered
    // as an addictive on the measured wrench, so f_s = f_sr + f_o, where the frame of expression
    // and the sign of f_s are defined in the SensorsTree structure
    for(int leaf_id = 0; leaf_id < (int) subtree_leaf_links_indeces.size(); leaf_id++ ) {
        if( consider_ft_offset ) {
            int leaf_link_id = subtree_leaf_links_indeces[leaf_id];

            // for now we are supporting just one six axis FT sensor for link
            //std::vector< FTSensor> fts_link = ft_list.getFTSensorsOnLink(leaf_link_id);
            //assert(fts_link.size()==1);
            //int ft_id = fts_link[0].getID();
            int ft_id = getFirstFTSensorOnLink(*p_sensors_tree,leaf_link_id);
            assert( ft_id >= 0 );

            iDynTree::SixAxisForceTorqueSensor * sens
                = (iDynTree::SixAxisForceTorqueSensor *) p_sensors_tree->getSensor(iDynTree::SIX_AXIS_FORCE_TORQUE,ft_id);

            assert( sens->isLinkAttachedToSensor(leaf_link_id) );

            #ifndef NDEBUG
            if( verbose ) std::cerr << "Adding to the torque regressor of joint " << torque_dof_it->getName()
                                    << " the columns relative to offset of ft sensor "
                                    << sens->getName() << std::endl;
            #endif

            /** \todo find a more robust way to get columns indeces relative to a given parameters */
            assert(ft_id >= 0 && ft_id < 100);
            assert(10*NrOfRealLinks_subtree+6*ft_id+5 < regressor_local_parametrization.cols());

            double sign;
            if( sens->getAppliedWrenchLink() == leaf_link_id ) {
                sign = 1.0;
            } else {
                sign = -1.0;
            }

            iDynTree::Transform leaf_link_H_sensor;

            bool ok = sens->getLinkSensorTransform(leaf_link_id,leaf_link_H_sensor);

            assert(ok);

            regressor_local_parametrization.block(0,(int)(10*NrOfRealLinks_subtree+6*ft_id),getNrOfOutputs(),6)
                = sign*toEigen(S).transpose()*regressor_local_parametrization*WrenchTransformationMatrix(X_dynamic_base[subtree_root_link_id].Inverse()*X_dynamic_base[leaf_link_id]*iDynTree::ToKDL(leaf_link_H_sensor));

        }
    }

    //The known terms are simply all the measured wrenches acting on the subtree
    // projected on the axis plus the measured torque
    known_terms(0) = measured_torques(torque_dof_index);

    #ifndef NDEBUG
    //std::cerr << "computing kt " << std::endl;
    //std::cerr << (ft_list).toString();
#endif
    for(int leaf_id = 0; leaf_id < (int) subtree_leaf_links_indeces.size(); leaf_id++ ) {
        int leaf_link_id = subtree_leaf_links_indeces[leaf_id];

        int ft_id = getFirstFTSensorOnLink(*p_sensors_tree,leaf_link_id);
        assert( ft_id >= 0 );

        iDynTree::SixAxisForceTorqueSensor * sens
            = (iDynTree::SixAxisForceTorqueSensor *) p_sensors_tree->getSensor(iDynTree::SIX_AXIS_FORCE_TORQUE,ft_id);

#ifndef NDEBUG
        //std::cerr << "For leaf " << leaf_link_id << " found ft sensor " << ft_id << " that connects " << fts_link[0].getParent() << " and " << fts_link[0].getChild() << std::endl;
#endif
        iDynTree::Wrench sensor_measured_wrench, link_measured_branch;

        bool ok = measured_wrenches.getMeasurement(iDynTree::SIX_AXIS_FORCE_TORQUE,ft_id,sensor_measured_wrench);

        ok = ok && sens->getWrenchAppliedOnLink(leaf_link_id,sensor_measured_wrench,link_measured_branch);

        assert(ok);

        known_terms(0) +=  dot(S,X_dynamic_base[subtree_root_link_id].Inverse()*X_dynamic_base[leaf_link_id]*iDynTree::ToKDL(link_measured_branch));
    }

#ifndef NDEBUG
/*
std::cout << "Returning from computeRegressor (subtree):" << std::endl;
std::cout << "Regressor " << std::endl;
std::cout << regressor_matrix << std::endl;
std::cout << "known terms" << std::endl;
std::cout << known_terms << std::endl;
*/
#endif

    convertLocalRegressorToGlobalRegressor(regressor_local_parametrization,regressor_matrix_global_column_serialization,this->localParametersIndexToOutputParametersIndex);

    return 0;
}

bool torqueRegressor::setGlobalParameters(const iDynTree::Regressors::DynamicsRegressorParametersList& globalParameters)
{
    iDynTree::Regressors::DynamicsRegressorParametersList localSerialiaziation =
        getLegacyUsedParameters(linkIndeces2regrCols,
                                p_sensors_tree->getNrOfSensors(iDynTree::SIX_AXIS_FORCE_TORQUE),
                                this->consider_ft_offset);

    buildParametersMapping(localSerialiaziation,globalParameters,this->localParametersIndexToOutputParametersIndex);

    return true;
}

}

}

}
<commit_msg>Fix regression in torque regressor computation<commit_after>/**
 * Copyright (C) 2013 IIT - Istituto Italiano di Tecnologia - http://www.iit.it
 * Author: Silvio Traversaro
 * CopyPolicy: Released under the terms of the GNU LGPL v2.0 (or any later version)
 *
 * The development of this software was supported by the FP7 EU project
 * CoDyCo (No. 600716 ICT 2011.2.1 Cognitive Systems and Robotics (b))
 * http://www.codyco.eu
 */

#include "kdl_codyco/regressors/torqueRegressor.hpp"

#include "kdl_codyco/regressor_utils.hpp"

#include "iDynTree/Sensors/Sensors.h"
#include "iDynTree/Sensors/SixAxisFTSensor.h"
#include "kdl_codyco/KDLConversions.h"
#include "iDynTree/Core/Transform.h"
#include "iDynTree/Core/Wrench.h"

#include "dirl_utils.hpp"

#include <iostream>

using namespace KDL::CoDyCo;

namespace KDL {
namespace CoDyCo {
namespace Regressors {

bool torqueRegressor::isActiveFTSensor(const int ft_sensor_id) const
{
    unsigned int NrOfFTSensors = p_sensors_tree->getNrOfSensors(iDynTree::SIX_AXIS_FORCE_TORQUE);
    if( activated_ft_sensors.size() !=  NrOfFTSensors)
    {
        return false;
    }

    if( ft_sensor_id < 0 ||
        ft_sensor_id >= NrOfFTSensors )
    {
        return false;
    }

    return activated_ft_sensors[ft_sensor_id];
}

int torqueRegressor::configure()
{
    const KDL::CoDyCo::UndirectedTree & undirected_tree = *p_undirected_tree;
    const iDynTree::SensorsList  & sensors_tree = *p_sensors_tree;

    //Now store all the links that belong to the subtree
    //We first compute the spanning starting at one (the first) of the leafs
    KDL::CoDyCo::Traversal subtree_traversal;

    JunctionMap::const_iterator torque_jnt = undirected_tree.getJunction(torque_dof);
    if( torque_jnt == undirected_tree.getInvalidJunctionIterator() ) {
        if(verbose) { std::cerr << "torqueRegressor error: specified joint " << torque_dof << " not found " << std::endl; }
        return -1;
    }

    torque_dof_index = torque_jnt->getJunctionIndex();

    relative_junction.resize(1);
    relative_junction[0] = torque_dof_index;

    if( torque_dof_index < 0 || torque_dof_index >= (int)undirected_tree.getNrOfDOFs() ) {
         if(verbose) { std::cerr << "torqueRegressor error: specified joint " << torque_dof << " has no degrees of freedom " << std::endl; }
        return -1;
    }

    int link_parent_id = torque_jnt->getParentLink()->getLinkIndex();
    int link_child_id = torque_jnt->getChildLink()->getLinkIndex();

    if( !reverse_direction )
    {
        subtree_root_link_id = link_child_id;
    }
    else
    {
        subtree_root_link_id = link_parent_id;
    }

    undirected_tree.compute_traversal(subtree_traversal,subtree_root_link_id);

    //Then we color the nodes: if white (true) the links belongs to the subtree
    //if black (false) it does not belongs to the node
    std::vector<bool> is_link_in_subtree(undirected_tree.getNrOfLinks(),false);

    //the leaf that we chose as starting link clearly belongs to the subtree
    is_link_in_subtree[subtree_root_link_id] = true;

    //then, all the other links can be classified using the following rules:
    for(int i=1; i < (int)subtree_traversal.getNrOfVisitedLinks(); i++ )
    {
        int link_id = subtree_traversal.getOrderedLink(i)->getLinkIndex();
        int parent_id = subtree_traversal.getParentLink(link_id)->getLinkIndex();

        if( is_link_in_subtree[parent_id] == false )
        {
            //if the parent is not in the subtree (false/black) then the link is not in the subtree (false/black)
            is_link_in_subtree[link_id] = false;
        }
        else
        {
            int junction_index = undirected_tree.getLink(link_id)->getAdjacentJoint(undirected_tree.getLink(parent_id))->getJunctionIndex();

            int ft_sensor_index = getFTIndexFromJunctionIndex(*p_sensors_tree,junction_index);
            if( ft_sensor_index >= 0 && isActiveFTSensor(ft_sensor_index) )
            {
                //if the parent is in the subtree (true/white) but it is connected to the link by an activated FT sensor
                is_link_in_subtree[link_id] = false;
                //In this case we have to add the parent to subtree_leaf_links_indeces
                subtree_leaf_links_indeces.push_back(parent_id);

            }
            else if ( junction_index == torque_dof_index )
            {
                //or if the parent is connected trought the torque regressor dof
                is_link_in_subtree[link_id] = false;
            }
            else
            {
                //otherwise the link is in the subtree (true/white)
                is_link_in_subtree[link_id] = true;
            }
        }
    }

    //after all the links belonging to the subtree have been identified, it is possible to save only the id of the one in the subtree
    assert( subtree_links_indices.size() == 0 );
    for( int i=0; i < (int)is_link_in_subtree.size(); i++ )
    {
        if( is_link_in_subtree[i] ) {
            subtree_links_indices.push_back(i);
        }
    }

    iDynTree::Regressors::DynamicsRegressorParametersList localSerialization = getLegacyUsedParameters(linkIndeces2regrCols,
                                p_sensors_tree->getNrOfSensors(iDynTree::SIX_AXIS_FORCE_TORQUE),
                                this->consider_ft_offset);

    regressor_local_parametrization.resize(getNrOfOutputs(),localSerialization.parameters.size());

    return 0;
}

int torqueRegressor::getNrOfOutputs()
{
    return 1;
}

std::vector<int> torqueRegressor::getRelativeJunctions()
{
    return relative_junction;
}

iDynTree::Regressors::DynamicsRegressorParametersList torqueRegressor::getUsedParameters()
{
    assert(p_undirected_tree->getNrOfLinks() == linkIndeces2regrCols.size());

    return getLegacyUsedParameters(linkIndeces2regrCols,
                                   activated_ft_sensors.size(),
                                   this->consider_ft_offset);
}

int torqueRegressor::computeRegressor(const KDL::JntArray &q,
                                      const KDL::JntArray &/*q_dot*/,
                                      const KDL::JntArray &/*q_dotdot*/,
                                      const std::vector<KDL::Frame> & X_dynamic_base,
                                      const std::vector<KDL::Twist> & v,
                                      const std::vector<KDL::Twist> & a,
                                      const iDynTree::SensorsMeasurements & measured_wrenches,
                                      const KDL::JntArray & measured_torques,
                                      Eigen::MatrixXd & regressor_matrix_global_column_serialization,
                                      Eigen::VectorXd & known_terms)
{
#ifdef NDEBUG
    if( verbose ) std::cerr << "Called torqueRegressor::computeRegressor " << std::endl;
#endif
    //const KDL::CoDyCo::UndirectedTree &  = *p_undirected_tree;
    //const KDL::CoDyCo::FTSensorList & ft_list = *p_ft_list;

    assert( regressor_local_parametrization.rows() == getNrOfOutputs() );

     /**
     * \todo move this stuff in UndirectedTree
     *
     */
    JunctionMap::const_iterator torque_dof_it = p_undirected_tree->getJunction(torque_dof_index);
    LinkMap::const_iterator parent_root_it;
    if( torque_dof_it->getChildLink() == p_undirected_tree->getLink(subtree_root_link_id) ) {
        parent_root_it = torque_dof_it->getParentLink();
    } else {
        parent_root_it = torque_dof_it->getChildLink();
    }
    assert(torque_dof_it->getJunctionIndex() < (int)p_undirected_tree->getNrOfDOFs());
    KDL::Twist S = parent_root_it->S(p_undirected_tree->getLink(subtree_root_link_id),q(torque_dof_it->getJunctionIndex()));

    //all other columns, beside the one relative to the inertial parameters of the links of the subtree, are zero
    regressor_local_parametrization.setZero();

    for(int i =0; i < (int)subtree_links_indices.size(); i++ ) {
        int link_id = subtree_links_indices[i];

        if( linkIndeces2regrCols[link_id] != -1 ) {
            #ifdef NDEBUG
            if( verbose ) std::cerr << "Adding to the torque regressor of joint " << torque_dof_it->getName() << " the regressor relative to link " << p_undirected_tree->getLink(link_id)->getName() << std::endl;
            #endif

            Eigen::Matrix<double,6,10> netWrenchRegressor_i = netWrenchRegressor(v[link_id],a[link_id]);
            regressor_local_parametrization.block(0,(int)(10*linkIndeces2regrCols[link_id]),getNrOfOutputs(),10)
                = toEigen(S).transpose()*WrenchTransformationMatrix(X_dynamic_base[subtree_root_link_id].Inverse()*X_dynamic_base[link_id])*netWrenchRegressor_i;
        }
    }

#ifdef NDEBUG
    if( consider_ft_offset ) {
        if( verbose ) std::cerr << "considering ft offset" << std::endl;
    } else {
        if( verbose ) std::cerr << "not considering ft offset" << std::endl;
    }
#endif
    // if the ft offset is condidered, we have to set also the columns relative to the offset
    // For each subgraph, we consider the measured wrenches as the one excerted from the rest of the
    // tree to the considered subtree
    // So the sign of the offset should be consistent with the other place where it is defined.
    // In particular, the offset of a sensor is considered
    // as an addictive on the measured wrench, so f_s = f_sr + f_o, where the frame of expression
    // and the sign of f_s are defined in the SensorsTree structure
    for(int leaf_id = 0; leaf_id < (int) subtree_leaf_links_indeces.size(); leaf_id++ ) {
        if( consider_ft_offset ) {
            int leaf_link_id = subtree_leaf_links_indeces[leaf_id];

            // for now we are supporting just one six axis FT sensor for link
            //std::vector< FTSensor> fts_link = ft_list.getFTSensorsOnLink(leaf_link_id);
            //assert(fts_link.size()==1);
            //int ft_id = fts_link[0].getID();
            int ft_id = getFirstFTSensorOnLink(*p_sensors_tree,leaf_link_id);
            assert( ft_id >= 0 );

            iDynTree::SixAxisForceTorqueSensor * sens
                = (iDynTree::SixAxisForceTorqueSensor *) p_sensors_tree->getSensor(iDynTree::SIX_AXIS_FORCE_TORQUE,ft_id);

            assert( sens->isLinkAttachedToSensor(leaf_link_id) );

            #ifndef NDEBUG
            if( verbose ) std::cerr << "Adding to the torque regressor of joint " << torque_dof_it->getName()
                                    << " the columns relative to offset of ft sensor "
                                    << sens->getName() << std::endl;
            #endif

            /** \todo find a more robust way to get columns indeces relative to a given parameters */
            assert(ft_id >= 0 && ft_id < 100);
            assert(10*NrOfRealLinks_subtree+6*ft_id+5 < regressor_local_parametrization.cols());

            double sign;
            if( sens->getAppliedWrenchLink() == leaf_link_id ) {
                sign = 1.0;
            } else {
                sign = -1.0;
            }

            iDynTree::Transform leaf_link_H_sensor;

            bool ok = sens->getLinkSensorTransform(leaf_link_id,leaf_link_H_sensor);

            assert(ok);

            regressor_local_parametrization.block(0,(int)(10*NrOfRealLinks_subtree+6*ft_id),getNrOfOutputs(),6)
                = sign*toEigen(S).transpose()*WrenchTransformationMatrix(X_dynamic_base[subtree_root_link_id].Inverse()*X_dynamic_base[leaf_link_id]*iDynTree::ToKDL(leaf_link_H_sensor));

        }
    }

    //The known terms are simply all the measured wrenches acting on the subtree
    // projected on the axis plus the measured torque
    known_terms(0) = measured_torques(torque_dof_index);

    #ifndef NDEBUG
    //std::cerr << "computing kt " << std::endl;
    //std::cerr << (ft_list).toString();
#endif
    for(int leaf_id = 0; leaf_id < (int) subtree_leaf_links_indeces.size(); leaf_id++ ) {
        int leaf_link_id = subtree_leaf_links_indeces[leaf_id];

        int ft_id = getFirstFTSensorOnLink(*p_sensors_tree,leaf_link_id);
        assert( ft_id >= 0 );

        iDynTree::SixAxisForceTorqueSensor * sens
            = (iDynTree::SixAxisForceTorqueSensor *) p_sensors_tree->getSensor(iDynTree::SIX_AXIS_FORCE_TORQUE,ft_id);

#ifndef NDEBUG
        //std::cerr << "For leaf " << leaf_link_id << " found ft sensor " << ft_id << " that connects " << fts_link[0].getParent() << " and " << fts_link[0].getChild() << std::endl;
#endif
        iDynTree::Wrench sensor_measured_wrench, link_measured_branch;

        bool ok = measured_wrenches.getMeasurement(iDynTree::SIX_AXIS_FORCE_TORQUE,ft_id,sensor_measured_wrench);

        ok = ok && sens->getWrenchAppliedOnLink(leaf_link_id,sensor_measured_wrench,link_measured_branch);

        assert(ok);

        known_terms(0) +=  dot(S,X_dynamic_base[subtree_root_link_id].Inverse()*X_dynamic_base[leaf_link_id]*iDynTree::ToKDL(link_measured_branch));
    }

#ifndef NDEBUG
/*
std::cout << "Returning from computeRegressor (subtree):" << std::endl;
std::cout << "Regressor " << std::endl;
std::cout << regressor_matrix << std::endl;
std::cout << "known terms" << std::endl;
std::cout << known_terms << std::endl;
*/
#endif

    convertLocalRegressorToGlobalRegressor(regressor_local_parametrization,regressor_matrix_global_column_serialization,this->localParametersIndexToOutputParametersIndex);

    return 0;
}

bool torqueRegressor::setGlobalParameters(const iDynTree::Regressors::DynamicsRegressorParametersList& globalParameters)
{
    iDynTree::Regressors::DynamicsRegressorParametersList localSerialiaziation =
        getLegacyUsedParameters(linkIndeces2regrCols,
                                p_sensors_tree->getNrOfSensors(iDynTree::SIX_AXIS_FORCE_TORQUE),
                                this->consider_ft_offset);

    buildParametersMapping(localSerialiaziation,globalParameters,this->localParametersIndexToOutputParametersIndex);

    return true;
}

}

}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: printerjob.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:35:45 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _PSPRINT_PRINTERJOB_HXX_
#define _PSPRINT_PRINTERJOB_HXX_

#ifndef __SGI_STL_LIST
#include <list>
#endif
#ifndef _PSPRINT_JOBDATA_HXX_
#include <psprint/jobdata.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif

namespace psp {

// forward declarations
class PrinterGfx;

class PrinterJob
{
private:            // private data

    rtl::OUString           maSpoolDirName;
    rtl::OUString           maFileName; // empty: spool to command, else spool to named file
    rtl::OUString           maJobTitle;
    int                     mnFileMode;

    osl::File*              mpJobHeader;
    osl::File*              mpJobTrailer;

    std::list< osl::File* > maPageList;
    std::list< osl::File* > maHeaderList;

    JobData                 m_aDocumentJobData;
    JobData                 m_aLastJobData;
    PrinterGfx*             m_pGraphics;

    sal_uInt32      mnResolution;

    sal_uInt32      mnWidthPt;
    sal_uInt32      mnHeightPt;
    sal_uInt32      mnMaxWidthPt;
    sal_uInt32      mnMaxHeightPt;

    sal_uInt32      mnLMarginPt;
    sal_uInt32      mnRMarginPt;
    sal_uInt32      mnTMarginPt;
    sal_uInt32      mnBMarginPt;

    double          mfXScale;
    double          mfYScale;

    sal_Int32       mnErrorCode;

private:            // private methods

    osl::File*      CreateSpoolFile (const rtl::OUString& rName,
                                     const rtl::OUString& rExtension);
    void            InitPaperSize (const JobData& rJobSetup);

    bool            writeFeatureList( osl::File* pFile, const JobData&, bool bDocumentSetup );
    bool            writeSetup( osl::File* pFile, const JobData& );
    bool            writePageSetup( osl::File* pFile, const JobData& );
    void            writeJobPatch( osl::File* File, const JobData& );
    bool            writeProlog (osl::File* pFile, const JobData& );

public:             // for usage in PrinterGfx

    sal_uInt32      GetResolution () const { return mnResolution; }
    void            GetScale (double &rXScale, double &rYScale) const;
    sal_uInt16      GetDepth () const;
    sal_uInt16      GetPostscriptLevel (const JobData *pJobData = NULL) const;
    sal_Bool        IsColorPrinter () const;

    osl::File*      GetDocumentHeader ();
    osl::File*      GetDocumentTrailer ();
    osl::File*      GetCurrentPageHeader ();
    osl::File*      GetCurrentPageBody ();

    const ::rtl::OUString& GetPrinterName() const { return m_aLastJobData.m_aPrinterName; }

public:
    PrinterJob ();
    ~PrinterJob ();

    /*  rFileName: if length is greater than 0 save resulting PostScript
     *  to named file.
     *  nMode: only meaningful when saving to file: if nonzero, try
     *  to impose the mode on the resulting file's inode; for nonexistant
     *  files use open, for existant files try a chmod
     *  rJobName: text to appear in the %%Title comment
     *  rAppName: text to appear in the %%Creator comment
     *  rSetupData: JobData that apply to this job
     *  pGraphics: the graphics used to print this job;
     *             this graphics must live until End/AbortJob has returned
     */
    sal_Bool        StartJob (const rtl::OUString& rFileName,
                              int nMode,
                              const rtl::OUString& rJobName,
                              const rtl::OUString& rAppName,
                              const JobData& rSetupData,
                              PrinterGfx* pGraphics
                              );
    sal_Bool        EndJob ();

    sal_Bool        AbortJob ();

    sal_Bool        StartPage (const JobData& rJobSetup, sal_Bool bNewJobData);
    sal_Bool        EndPage ();

    sal_uInt32      GetErrorCode ();
};

}  /* namespace psp */

#endif /* _PSPRINT_PRINTERJOB_HXX_ */

<commit_msg>INTEGRATION: CWS warnings01 (1.8.10); FILE MERGED 2005/10/28 10:53:36 pl 1.8.10.1: #i55991# removed warnings for solaris platform<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: printerjob.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 10:23:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _PSPRINT_PRINTERJOB_HXX_
#define _PSPRINT_PRINTERJOB_HXX_

#ifndef __SGI_STL_LIST
#include <list>
#endif
#ifndef _PSPRINT_JOBDATA_HXX_
#include <psprint/jobdata.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif

namespace psp {

// forward declarations
class PrinterGfx;

class PrinterJob
{
private:            // private data

    rtl::OUString           maSpoolDirName;
    rtl::OUString           maFileName; // empty: spool to command, else spool to named file
    rtl::OUString           maJobTitle;
    int                     mnFileMode;

    osl::File*              mpJobHeader;
    osl::File*              mpJobTrailer;

    std::list< osl::File* > maPageList;
    std::list< osl::File* > maHeaderList;

    JobData                 m_aDocumentJobData;
    JobData                 m_aLastJobData;
    PrinterGfx*             m_pGraphics;

    sal_uInt32      mnResolution;

    sal_uInt32      mnWidthPt;
    sal_uInt32      mnHeightPt;
    sal_uInt32      mnMaxWidthPt;
    sal_uInt32      mnMaxHeightPt;

    sal_uInt32      mnLMarginPt;
    sal_uInt32      mnRMarginPt;
    sal_uInt32      mnTMarginPt;
    sal_uInt32      mnBMarginPt;

    double          mfXScale;
    double          mfYScale;

    sal_Int32       mnErrorCode;

private:            // private methods

    osl::File*      CreateSpoolFile (const rtl::OUString& rName,
                                     const rtl::OUString& rExtension);
    void            InitPaperSize (const JobData& rJobSetup);

    bool            writeFeatureList( osl::File* pFile, const JobData&, bool bDocumentSetup );
    bool            writeSetup( osl::File* pFile, const JobData& );
    bool            writePageSetup( osl::File* pFile, const JobData& );
    void            writeJobPatch( osl::File* File, const JobData& );
    bool            writeProlog (osl::File* pFile, const JobData& );

public:             // for usage in PrinterGfx

    sal_uInt32      GetResolution () const { return mnResolution; }
    void            GetScale (double &rXScale, double &rYScale) const;
    sal_uInt16      GetDepth () const;
    sal_uInt16      GetPostscriptLevel (const JobData *pJobData = NULL) const;
    sal_Bool        IsColorPrinter () const;

    osl::File*      GetDocumentHeader ();
    osl::File*      GetDocumentTrailer ();
    osl::File*      GetCurrentPageHeader ();
    osl::File*      GetCurrentPageBody ();

    const ::rtl::OUString& GetPrinterName() const { return m_aLastJobData.m_aPrinterName; }

public:
    PrinterJob ();
    ~PrinterJob ();

    /*  rFileName: if length is greater than 0 save resulting PostScript
     *  to named file.
     *  nMode: only meaningful when saving to file: if nonzero, try
     *  to impose the mode on the resulting file's inode; for nonexistant
     *  files use open, for existant files try a chmod
     *  rJobName: text to appear in the %%Title comment
     *  rAppName: text to appear in the %%Creator comment
     *  rSetupData: JobData that apply to this job
     *  pGraphics: the graphics used to print this job;
     *             this graphics must live until End/AbortJob has returned
     */
    sal_Bool        StartJob (const rtl::OUString& rFileName,
                              int nMode,
                              const rtl::OUString& rJobName,
                              const rtl::OUString& rAppName,
                              const JobData& rSetupData,
                              PrinterGfx* pGraphics
                              );
    sal_Bool        EndJob ();

    sal_Bool        AbortJob ();

    sal_Bool        StartPage (const JobData& rJobSetup);
    sal_Bool        EndPage ();

    sal_uInt32      GetErrorCode ();
};

}  /* namespace psp */

#endif /* _PSPRINT_PRINTERJOB_HXX_ */

<|endoftext|>