<commit_before>#include "ServiceDiscovery.h"
#include "ServerPeer.h"
#include <iostream>
#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include "DatabaseLinker.h"
using namespace std;

ServiceDiscovery::ServiceDiscovery(char* _listen_hostname, int _listen_port):Server(_listen_hostname, _listen_port){
    startListen();
}

bool ServiceDiscovery::auth(string username, string token){
	cout << "SERVICEDISCOVERY::AUTH!";
    if(token_user[token]==username)
        return true;
    return false;
} //check if in token_user? true: false;

string ServiceDiscovery::signUp(string username, string password, string addr){
	cout << "SERVICEDISCOVERY::SIGNUP!";
    srand(time(NULL));
    string token;
    users[username] = password;
    do{
        token = to_string(rand()%10000);
    }while(token_user.count(token)>0);

    token_user[token] = username;
    online_users[username]=addr;
    // pending_requests needs username or token?
    return token;
}

string ServiceDiscovery::signIn(string username, string password, string addr){
	cout << "SERVICEDISCOVERY::SIGNIN!";
    srand(time(NULL));
    string token;
    if(users[username]==password){
        do{
            token = to_string(rand()%10000);
        }while(token_user.count(token)>0);

        token_user[token] = username;
        online_users[username]=addr;
        // pending_requests needs username or token?
        return token;
    }
    token = "";
    return token;
}  //check if in (users)?generate random token..add to token_user..check if he has pending requests..receive ack...return token: return error.

map<string, string> ServiceDiscovery::getListOfOnlineUsers(string username, string token){
	cout << "SERVICEDISCOVERY::getListofOnlineUsers!";
    if(auth(username,token)){
    	return online_users;
    }
    std::map<string, string> mss;
    return mss;
}

void ServiceDiscovery::stillUp(string username, string token, string addr){
	cout << "SERVICEDISCOVERY::stillUp!";
    if(auth(username,token)){
        token_time[token]++;
    }
    online_users[username]=addr;
} //auth()? update time_cnt in token_time: ignore

void ServiceDiscovery::down(string username, string token){
	cout << "SERVICEDISCOVERY::DOWN!";
    if(auth(username,token)){
        token_time.erase(token);
        online_users.erase(username);
    }
}

//TODO: Handle Pending Requests
 void ServiceDiscovery::pendingRequest(string username, string token, string to_user, string imageID){
     if(auth(username,token)){

      }
 }

Message* ServiceDiscovery::doOperation(Message* _message){
	cout << "SERVICEDISCOVERY::doOperation!";
	_message->print();
	Message* reply_message = new Message(Reply);

    vector<Parameter> args;
    vector<Parameter> reply_args;

    int operation = _message->getOperation();

    MessageDecoder::decode(_message, args);

    switch(operation){
    case 1:{
    	string token = signUp(args[0].getString(), args[1].getString(), args[2].getString());
    	Parameter arg1;
    	arg1.setString(token);
    	reply_args.push_back(arg1);
    }
    	break;
    case 2:{
    	string token = signIn(args[0].getString(), args[1].getString(), args[2].getString());
    	Parameter arg1;
    	arg1.setString(token);
    	reply_args.push_back(arg1);
    }
    	break;
    case 3:{
    	stillUp(args[0].getString(), args[1].getString(), args[2].getString());
    }
    	break;
    case 4:{
    	down(args[0].getString(), args[1].getString());
    }
    	break;
    case 5:{
    	//pendingrequest
    }
    	break;
    case 6:{
    	//GetListofOnlineUsers
    	map<string, string> _mss = getListOfOnlineUsers(args[0].getString(), args[1].getString());
    	Parameter arg1;
    	arg1.setMapSS(_mss);
    	cout << arg1.getMapSS()["3wais"] << endl;
    	reply_args.push_back(arg1);
    }
    	break;
    case 10:{
    	//Auth
    	bool _auth = auth(args[0].getString(), args[1].getString());
    	Parameter arg1;
    	arg1.setBoolean(_auth);
    	reply_args.push_back(arg1);
    }
    	break;
    }

	MessageDecoder::encode(*reply_message, reply_args, operation, Reply);
	reply_message->print();
	cout << "SERVICE DISCOVERY OUT!" << endl;
    return reply_message;
}
ServiceDiscovery:: ~ServiceDiscovery(){

}//destructor
<commit_msg>fixes<commit_after>#include "ServiceDiscovery.h"
#include "ServerPeer.h"
#include <iostream>
#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include "DatabaseLinker.h"
using namespace std;

ServiceDiscovery::ServiceDiscovery(char* _listen_hostname, int _listen_port):Server(_listen_hostname, _listen_port){
    startListen();
}

bool ServiceDiscovery::auth(string username, string token){
	cout << "SERVICEDISCOVERY::AUTH!";
    if(token_user[token]==username)
        return true;
    return false;
} //check if in token_user? true: false;

string ServiceDiscovery::signUp(string username, string password, string addr){
	cout << "SERVICEDISCOVERY::SIGNUP!";
    srand(time(NULL));
    string token;
    users[username] = password;
    do{
        token = to_string(rand()%10000);
    }while(token_user.count(token)>0);

    token_user[token] = username;
    online_users[username]=addr;
    // pending_requests needs username or token?
    return token;
}

string ServiceDiscovery::signIn(string username, string password, string addr){
	cout << "SERVICEDISCOVERY::SIGNIN!";
    srand(time(NULL));
    string token;
    if(users[username]==password){
        do{
            token = to_string(rand()%10000);
        }while(token_user.count(token)>0);

        token_user[token] = username;
        online_users[username]=addr;
        // pending_requests needs username or token?
        return token;
    }
    token = "";
    return token;
}  //check if in (users)?generate random token..add to token_user..check if he has pending requests..receive ack...return token: return error.

map<string, string> ServiceDiscovery::getListOfOnlineUsers(string username, string token){
	cout << "SERVICEDISCOVERY::getListofOnlineUsers!";
    if(auth(username,token)){
    	return online_users;
    }
    std::map<string, string> mss;
    return mss;
}

void ServiceDiscovery::stillUp(string username, string token, string addr){
	cout << "SERVICEDISCOVERY::stillUp!";
    if(auth(username,token)){
        token_time[token]++;
    }
    online_users[username]=addr;
} //auth()? update time_cnt in token_time: ignore

void ServiceDiscovery::down(string username, string token){
	cout << "SERVICEDISCOVERY::DOWN!";
    if(auth(username,token)){
        token_time.erase(token);
        online_users.erase(username);
    }
}

//TODO: Handle Pending Requests
 void ServiceDiscovery::pendingRequest(string username, string token, string to_user, string imageID){
     if(auth(username,token)){

      }
 }

Message* ServiceDiscovery::doOperation(Message* _message){
	cout << "SERVICEDISCOVERY::doOperation!";
	_message->print();
	Message* reply_message = new Message(Reply);

    vector<Parameter> args;
    vector<Parameter> reply_args;

    int operation = _message->getOperation();

    MessageDecoder::decode(_message, args);

    switch(operation){
    case 1:{
    	string token = signUp(args[0].getString(), args[1].getString(), args[2].getString());
    	Parameter arg1;
    	arg1.setString(token);
    	reply_args.push_back(arg1);
    }
    	break;
    case 2:{
    	string token = signIn(args[0].getString(), args[1].getString(), args[2].getString());
    	Parameter arg1;
    	arg1.setString(token);
    	reply_args.push_back(arg1);
    }
    	break;
    case 3:{
    	stillUp(args[0].getString(), args[1].getString(), args[2].getString());
    }
    	break;
    case 4:{
    	down(args[0].getString(), args[1].getString());
    }
    	break;
    case 5:{
    	//pendingrequest
    }
    	break;
    case 6:{
    	//GetListofOnlineUsers
    	map<string, string> _mss = getListOfOnlineUsers(args[0].getString(), args[1].getString());
    	Parameter arg1;
    	arg1.setMapSS(_mss);
    	reply_args.push_back(arg1);
    }
    	break;
    case 10:{
    	//Auth
    	bool _auth = auth(args[0].getString(), args[1].getString());
    	Parameter arg1;
    	arg1.setBoolean(_auth);
    	reply_args.push_back(arg1);
    }
    	break;
    }

	MessageDecoder::encode(*reply_message, reply_args, operation, Reply);
	reply_message->print();
	cout << "SERVICE DISCOVERY OUT!" << endl;
    return reply_message;
}
ServiceDiscovery:: ~ServiceDiscovery(){

}//destructor
<|endoftext|>


<commit_before>#include "ExecutableLauncherUnix.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <cstdlib>

using namespace clt::filesystem::operations;

void ExecutableLauncherUnix::execute(const entities::Path & path)
{
	pid_t cpid;

	cpid = fork();

	switch (cpid) {
		case -1: perror("fork");
			break;

		case 0:
			execl(path.getValue().c_str(), ""); /* this is the child */
			_exit(EXIT_FAILURE);
			break;

		default: waitpid(cpid, NULL, 0);
	}
}<commit_msg>Add first parameter when launching executable for unix<commit_after>#include "ExecutableLauncherUnix.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <cstdlib>

using namespace clt::filesystem::operations;

void ExecutableLauncherUnix::execute(const entities::Path & path)
{
	pid_t cpid;

	cpid = fork();

	switch (cpid) {
		case -1: perror("fork");
			break;

		case 0:
			execl(path.getValue().c_str(), path.getValue().c_str(), NULL, NULL); /* this is the child */
			_exit(EXIT_FAILURE);
			break;

		default: waitpid(cpid, NULL, 0);
	}
}<|endoftext|>


<commit_before>// @(#)root/thread:$Id$
// Author: Fons Rademakers   02/07/97 (Revised: G Ganis, Nov 2015)

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TSemaphore                                                           //
//                                                                      //
// This class implements a counting semaphore. Use a semaphore          //
// to synchronize threads.                                              //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TSemaphore.h"

////////////////////////////////////////////////////////////////////////////////
/// Create counting semaphore.

TSemaphore::TSemaphore(Int_t initial) : fValue(initial), fWakeups(0)
{
}

////////////////////////////////////////////////////////////////////////////////
/// If the semaphore value is > 0 then decrement it and carry on, else block,
/// waiting on the condition until it is signaled.
/// Returns always 0, for backward compatibility with the first implementation.

Int_t TSemaphore::Wait()
{
   std::unique_lock<std::mutex> lk(fMutex);
   fValue--;

   if (fValue < 0) {
      do {
         fCond.wait(lk);
      } while (fWakeups < 1);
      // We have been waken-up: decrease the related counter
      fWakeups--;
   }
   return 0;
}

////////////////////////////////////////////////////////////////////////////////
/// If the semaphore value is > 0 then decrement it and carry on, else block.
/// If millisec > 0 then a relative timeout of millisec milliseconds is applied.
/// For backward compatibility with the first implementation, millisec == 0 means
/// no timeout.
/// Returns 1 if timed-out, 0 otherwise.

Int_t TSemaphore::Wait(Int_t millisec)
{
   // For backward compatibility with the first implementation
   if (millisec <= 0) return Wait();

   Int_t rc= 0;
   std::unique_lock<std::mutex> lk(fMutex);
   fValue--;

   if (fValue < 0) {
      std::cv_status cvs;
      do {
         cvs = fCond.wait_for(lk,std::chrono::milliseconds(millisec));
      } while (fWakeups < 1 && cvs != std::cv_status::timeout);
      if (cvs == std::cv_status::timeout) {
         // Give back the token ...
         fValue++;
         rc = 1;
      } else {
         // We have been waken-up: decrease the related counter
         fWakeups--;
      }
   }
   return rc;
}

////////////////////////////////////////////////////////////////////////////////
/// If the semaphore value is > 0 then decrement it and return 0. If it's
/// already 0 then return 1. This call never blocks.

Int_t TSemaphore::TryWait()
{
   std::unique_lock<std::mutex> lk(fMutex);
   if (fValue > 0) {
      fValue--;
   } else {
      return 1;
   }
   return 0;
}

////////////////////////////////////////////////////////////////////////////////
/// Increment the value of the semaphore. If any threads are blocked in Wait(),
/// wakeup one of them.
/// Returns always 0, for backward compatibility with the first implementation.

Int_t TSemaphore::Post()
{
   std::unique_lock<std::mutex> lk(fMutex);
   fValue++;

   if (fValue <= 0) {
      // There were threads waiting: wake up one
      fWakeups++;
      fCond.notify_one();
   }
   return 0;
}
<commit_msg>Initialize variable, fixes builds on 10.9 SDK or gcc6.<commit_after>// @(#)root/thread:$Id$
// Author: Fons Rademakers   02/07/97 (Revised: G Ganis, Nov 2015)

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TSemaphore                                                           //
//                                                                      //
// This class implements a counting semaphore. Use a semaphore          //
// to synchronize threads.                                              //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TSemaphore.h"

////////////////////////////////////////////////////////////////////////////////
/// Create counting semaphore.

TSemaphore::TSemaphore(Int_t initial) : fValue(initial), fWakeups(0)
{
}

////////////////////////////////////////////////////////////////////////////////
/// If the semaphore value is > 0 then decrement it and carry on, else block,
/// waiting on the condition until it is signaled.
/// Returns always 0, for backward compatibility with the first implementation.

Int_t TSemaphore::Wait()
{
   std::unique_lock<std::mutex> lk(fMutex);
   fValue--;

   if (fValue < 0) {
      do {
         fCond.wait(lk);
      } while (fWakeups < 1);
      // We have been waken-up: decrease the related counter
      fWakeups--;
   }
   return 0;
}

////////////////////////////////////////////////////////////////////////////////
/// If the semaphore value is > 0 then decrement it and carry on, else block.
/// If millisec > 0 then a relative timeout of millisec milliseconds is applied.
/// For backward compatibility with the first implementation, millisec == 0 means
/// no timeout.
/// Returns 1 if timed-out, 0 otherwise.

Int_t TSemaphore::Wait(Int_t millisec)
{
   // For backward compatibility with the first implementation
   if (millisec <= 0) return Wait();

   Int_t rc= 0;
   std::unique_lock<std::mutex> lk(fMutex);
   fValue--;

   if (fValue < 0) {
      std::cv_status cvs = std::cv_status::timeout;
      do {
         cvs = fCond.wait_for(lk,std::chrono::milliseconds(millisec));
      } while (fWakeups < 1 && cvs != std::cv_status::timeout);
      if (cvs == std::cv_status::timeout) {
         // Give back the token ...
         fValue++;
         rc = 1;
      } else {
         // We have been waken-up: decrease the related counter
         fWakeups--;
      }
   }
   return rc;
}

////////////////////////////////////////////////////////////////////////////////
/// If the semaphore value is > 0 then decrement it and return 0. If it's
/// already 0 then return 1. This call never blocks.

Int_t TSemaphore::TryWait()
{
   std::unique_lock<std::mutex> lk(fMutex);
   if (fValue > 0) {
      fValue--;
   } else {
      return 1;
   }
   return 0;
}

////////////////////////////////////////////////////////////////////////////////
/// Increment the value of the semaphore. If any threads are blocked in Wait(),
/// wakeup one of them.
/// Returns always 0, for backward compatibility with the first implementation.

Int_t TSemaphore::Post()
{
   std::unique_lock<std::mutex> lk(fMutex);
   fValue++;

   if (fValue <= 0) {
      // There were threads waiting: wake up one
      fWakeups++;
      fCond.notify_one();
   }
   return 0;
}
<|endoftext|>


<commit_before>//
//  reference.c
//  WhateverGreen
//  Explanation of how RadeonFramebuffer connectors are created
//
//  Copyright © 2017 vit9696. All rights reserved.
//
//  Reverse-engineered from AMDSupport.kext
//  Copyright © 2017 Apple Inc. All rights reserved.
//

/**
 *  Connectors from AMDSupport since 10.12
 */
struct ModernConnector {
  uint32_t type;
  uint32_t flags;
  uint16_t features;
  uint16_t priority;
  uint32_t reserved1;
  uint8_t transmitter;
  uint8_t encoder;
  uint8_t hotplug;
  uint8_t sense;
  uint32_t reserved2;
};

enum ConnectorType {
  ConnectorLVDS       = 0x2,
  ConnectorDigitalDVI = 0x4,
  ConnectorSVID       = 0x8,
  ConnectorVGA        = 0x10,
  ConnectorDP         = 0x400,
  ConnectorHDMI       = 0x800,
  ConnectorAnalogDVI  = 0x2000
};

/**
 *  Internal atom connector struct since 10.13
 */
struct AtomConnectorInfo {
  uint16_t *atomObject;
  uint16_t usConnObjectId;
  uint16_t usGraphicObjIds;
  uint8_t *hpdRecord;
  uint8_t *i2cRecord;
};

// Definitions taken from asic_reg/ObjectID.h
enum {
  /* External Third Party Encoders */
  ENCODER_OBJECT_ID_SI170B                  = 0x08,
  ENCODER_OBJECT_ID_CH7303                  = 0x09,
  ENCODER_OBJECT_ID_CH7301                  = 0x0A,
  ENCODER_OBJECT_ID_INTERNAL_DVO1           = 0x0B,    /* This belongs to Radeon Class Display Hardware */
  ENCODER_OBJECT_ID_EXTERNAL_SDVOA          = 0x0C,
  ENCODER_OBJECT_ID_EXTERNAL_SDVOB          = 0x0D,
  ENCODER_OBJECT_ID_TITFP513                = 0x0E,
  ENCODER_OBJECT_ID_INTERNAL_LVTM1          = 0x0F,    /* not used for Radeon */
  ENCODER_OBJECT_ID_VT1623                  = 0x10,
  ENCODER_OBJECT_ID_HDMI_SI1930             = 0x11,
  ENCODER_OBJECT_ID_HDMI_INTERNAL           = 0x12,
  /* Kaleidoscope (KLDSCP) Class Display Hardware (internal) */
  ENCODER_OBJECT_ID_INTERNAL_KLDSCP_TMDS1   = 0x13,
  ENCODER_OBJECT_ID_INTERNAL_KLDSCP_DVO1    = 0x14,
  ENCODER_OBJECT_ID_INTERNAL_KLDSCP_DAC1    = 0x15,
  ENCODER_OBJECT_ID_INTERNAL_KLDSCP_DAC2    = 0x16,  /* Shared with CV/TV and CRT */
  ENCODER_OBJECT_ID_SI178                   = 0X17,  /* External TMDS (dual link, no HDCP.) */
  ENCODER_OBJECT_ID_MVPU_FPGA               = 0x18,  /* MVPU FPGA chip */
  ENCODER_OBJECT_ID_INTERNAL_DDI            = 0x19,
  ENCODER_OBJECT_ID_VT1625                  = 0x1A,
  ENCODER_OBJECT_ID_HDMI_SI1932             = 0x1B,
  ENCODER_OBJECT_ID_DP_AN9801               = 0x1C,
  ENCODER_OBJECT_ID_DP_DP501                = 0x1D,
  ENCODER_OBJECT_ID_INTERNAL_UNIPHY         = 0x1E,
  ENCODER_OBJECT_ID_INTERNAL_KLDSCP_LVTMA   = 0x1F,
  ENCODER_OBJECT_ID_INTERNAL_UNIPHY1        = 0x20,
  ENCODER_OBJECT_ID_INTERNAL_UNIPHY2        = 0x21,
  ENCODER_OBJECT_ID_ALMOND                  = 0x22,
  ENCODER_OBJECT_ID_NUTMEG                  = 0x22,
  ENCODER_OBJECT_ID_TRAVIS                  = 0x23,
  ENCODER_OBJECT_ID_INTERNAL_VCE            = 0x24,
  ENCODER_OBJECT_ID_INTERNAL_UNIPHY3        = 0x25,
  ENCODER_OBJECT_ID_INTERNAL_AMCLK          = 0x27
};

enum {
  CONNECTOR_OBJECT_ID_NONE                = 0x00,
  CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_I   = 0x01,
  CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_I     = 0x02,
  CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_D   = 0x03,
  CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_D     = 0x04,
  CONNECTOR_OBJECT_ID_VGA                 = 0x05,
  CONNECTOR_OBJECT_ID_COMPOSITE           = 0x06,
  CONNECTOR_OBJECT_ID_SVIDEO              = 0x07,
  CONNECTOR_OBJECT_ID_YPbPr               = 0x08,
  CONNECTOR_OBJECT_ID_D_CONNECTOR         = 0x09,
  CONNECTOR_OBJECT_ID_9PIN_DIN            = 0x0A,  /* Supports both CV & TV */
  CONNECTOR_OBJECT_ID_SCART               = 0x0B,
  CONNECTOR_OBJECT_ID_HDMI_TYPE_A         = 0x0C,
  CONNECTOR_OBJECT_ID_HDMI_TYPE_B         = 0x0D,
  CONNECTOR_OBJECT_ID_LVDS                = 0x0E,
  CONNECTOR_OBJECT_ID_7PIN_DIN            = 0x0F,
  CONNECTOR_OBJECT_ID_PCIE_CONNECTOR      = 0x10,
  CONNECTOR_OBJECT_ID_CROSSFIRE           = 0x11,
  CONNECTOR_OBJECT_ID_HARDCODE_DVI        = 0x12,
  CONNECTOR_OBJECT_ID_DISPLAYPORT         = 0x13,
  CONNECTOR_OBJECT_ID_eDP                 = 0x14,
  CONNECTOR_OBJECT_ID_MXM                 = 0x15,
  CONNECTOR_OBJECT_ID_LVDS_eDP            = 0x16
};

// Initially applecon data is nulled.
IOReturn AtiBiosParser2::translateAtomConnectorInfo(AtiBiosParser2 *parser, AtomConnectorInfo *atomcon, ModernConnector *applecon) {
  if (((atomcon->usConnObjectId & OBJECT_TYPE_MASK) >> OBJECT_TYPE_SHIFT) != GRAPH_OBJECT_TYPE_CONNECTOR)
    return kIOReturnNotFound;

  uint8_t *i2cRecord = atomcon->i2cRecord;
  if (i2cRecord) {
    applecon->sense = (i2cRecord[2] & 0xF) + 1;
  } else {
    applecon->sense = 0;
    kprintf("ATOM: %s: ASSERT(NULL != i2cRecord)\n", "uint8_t AtiBiosParser2::getAuxDdcLine(atom_i2c_record *)");
  }

  uint8_t *hpdRecord = (uint8_t *)atomcon->hpdRecord;
  if (hpdRecord) {
    applecon->hotplug = hpdRecord[2];
  } else {
    applecon->hotplug = 0;
    kprintf("ATOM: %s: ASSERT(NULL != hpdRecord)\n", "uint8_t AtiBiosParser2::getHotPlugPin(atom_hpd_int_record *)");
  }

  AtiBiosParser2::getOutputInformation(parser, atomcon, applecon);
  AtiBiosParser2::getConnectorFeatures(parser, atomcon, applecon);

  if (applecon->flags) {
    if ((applecon->flags & 0x704) && applecon->hotplug)
      applecon->features |= 0x100;
    return kIOReturnSuccess;
  } else {
    kprintf("ATOM: %s: ASSERT(0 != drvInfo.connections)\n", "IOReturn AtiBiosParser2::translateAtomConnectorInfo(AtiObjectInfoTableInterface_V2::AtomConnectorInfo &, ConnectorInfo &)");
  }

  return kIOReturnNotFound;
}

IOReturn AtiBiosParser2::getOutputInformation(AtiBiosParser2 *parser, AtomConnectorInfo *atomcon, ModernConnector *applecon) {
  if (!atomcon->usGraphicObjIds) {
    kprintf("ATOM: %s: ASSERT(0 != objId.u16All)\n", "IOReturn AtiBiosParser2::getOutputInformation(AtiObjectInfoTableInterface_V2::AtomConnectorInfo &, ConnectorInfo &)");
    return kIOReturnBadArgument;
  }

  uint8_t encoder = (uint8_t)atomcon->usGraphicObjIds;
  bool one = ((atomcon->usGraphicObjIds & ENUM_ID_MASK) >> ENUM_ID_SHIFT) == 1;

  switch (encoder) {
    case ENCODER_OBJECT_ID_NUTMEG:
      applecon->flags |= 0x10;
      return kIOReturnSuccess;
    case ENCODER_OBJECT_ID_INTERNAL_UNIPHY:
      if (one) {
        applecon->transmitter |= 0x10;
      } else {
        applecon->transmitter |= 0x20;
        applecon->encoder |= 0x1;
      }
      return kIOReturnSuccess;
    case ENCODER_OBJECT_ID_INTERNAL_UNIPHY1:
      if (one) {
        applecon->transmitter |= 0x11;
        applecon->encoder |= 0x2;
      } else {
        applecon->transmitter |= 0x21;
        applecon->encoder |= 0x3;
      }
      return kIOReturnSuccess;
    case ENCODER_OBJECT_ID_INTERNAL_UNIPHY2:
      if (one) {
        applecon->transmitter |= 0x12;
        applecon->encoder |= 0x4;
      } else {
        applecon->transmitter |= 0x22;
        applecon->encoder |= 0x5;
      }
      return kIOReturnSuccess;
    case ENCODER_OBJECT_ID_INTERNAL_UNIPHY3:
      if (one) {
        applecon->transmitter |= 0x13;
        applecon->encoder |= 0x6;
      } else {
        applecon->transmitter |= 0x23;
        applecon->encoder |= 0x7;
      }
      return kIOReturnSuccess;
  }

  return kIOReturnInvalid;
}

IOReturn AtiBiosParser2::getConnectorFeatures(AtiBiosParser2 *parser, AtomConnectorInfo *atomcon, ModernConnector *applecon) {
  if (!atomcon->usConnObjectId) {
    kprintf("ATOM: %s: ASSERT(0 != objId.u16All)\n", "IOReturn AtiBiosParser2::getConnectorFeatures(AtiObjectInfoTableInterface_V2::AtomConnectorInfo &, ConnectorInfo &)");
    result = kIOReturnBadArgument;
  }

  uint8_t connector = (uint8_t)atomcon->usGraphicObjIds;

  switch (connector) {
    case CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_I:
    case CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_D:
      applecon->type = ConnectorDigitalDVI;
      applecon->flags |= 4;
      // unlock 2k res, causes crashes on R9 290X
      // undone by -raddvi
      applecon->transmitter &= 0xCF;
      return kIOReturnSuccess;
    case CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_I:
    case CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_D:
      applecon->type = ConnectorDigitalDVI;
      applecon->flags |= 4;
      return kIOReturnSuccess;
    case CONNECTOR_OBJECT_ID_HDMI_TYPE_A:
    case CONNECTOR_OBJECT_ID_HDMI_TYPE_B:
      applecon->type = ConnectorHDMI;
      applecon->flags |= 0x204;
      return kIOReturnSuccess;
    case CONNECTOR_OBJECT_ID_VGA:
      applecon->type = ConnectorVGA;
      applecon->flags |= 0x10;
      return kIOReturnSuccess;
    case CONNECTOR_OBJECT_ID_LVDS:
      applecon->type = ConnectorLVDS;
      applecon->flags |= 0x40;
      applecon->features |= 0x9;
      // unlock 2k res
      applecon->transmitter &= 0xCF;
      return kIOReturnSuccess;
    case CONNECTOR_OBJECT_ID_DISPLAYPORT:
      applecon->type = ConnectorDP;
      applecon->flags |= 0x304;
      return kIOReturnSuccess;
    case CONNECTOR_OBJECT_ID_eDP:
      applecon->type = ConnectorLVDS;
      applecon->flags |= 0x100;
      applecon->features |= 0x109;
      return kIOReturnSuccess;
  }

  return kIOReturnInvalid;
}
<commit_msg>Fixed a small typo in reference code<commit_after>//
//  reference.c
//  WhateverGreen
//  Explanation of how RadeonFramebuffer connectors are created
//
//  Copyright © 2017 vit9696. All rights reserved.
//
//  Reverse-engineered from AMDSupport.kext
//  Copyright © 2017 Apple Inc. All rights reserved.
//

/**
 *  Connectors from AMDSupport since 10.12
 */
struct ModernConnector {
  uint32_t type;
  uint32_t flags;
  uint16_t features;
  uint16_t priority;
  uint32_t reserved1;
  uint8_t transmitter;
  uint8_t encoder;
  uint8_t hotplug;
  uint8_t sense;
  uint32_t reserved2;
};

enum ConnectorType {
  ConnectorLVDS       = 0x2,
  ConnectorDigitalDVI = 0x4,
  ConnectorSVID       = 0x8,
  ConnectorVGA        = 0x10,
  ConnectorDP         = 0x400,
  ConnectorHDMI       = 0x800,
  ConnectorAnalogDVI  = 0x2000
};

/**
 *  Internal atom connector struct since 10.13
 */
struct AtomConnectorInfo {
  uint16_t *atomObject;
  uint16_t usConnObjectId;
  uint16_t usGraphicObjIds;
  uint8_t *hpdRecord;
  uint8_t *i2cRecord;
};

// Definitions taken from asic_reg/ObjectID.h
enum {
  /* External Third Party Encoders */
  ENCODER_OBJECT_ID_SI170B                  = 0x08,
  ENCODER_OBJECT_ID_CH7303                  = 0x09,
  ENCODER_OBJECT_ID_CH7301                  = 0x0A,
  ENCODER_OBJECT_ID_INTERNAL_DVO1           = 0x0B,    /* This belongs to Radeon Class Display Hardware */
  ENCODER_OBJECT_ID_EXTERNAL_SDVOA          = 0x0C,
  ENCODER_OBJECT_ID_EXTERNAL_SDVOB          = 0x0D,
  ENCODER_OBJECT_ID_TITFP513                = 0x0E,
  ENCODER_OBJECT_ID_INTERNAL_LVTM1          = 0x0F,    /* not used for Radeon */
  ENCODER_OBJECT_ID_VT1623                  = 0x10,
  ENCODER_OBJECT_ID_HDMI_SI1930             = 0x11,
  ENCODER_OBJECT_ID_HDMI_INTERNAL           = 0x12,
  /* Kaleidoscope (KLDSCP) Class Display Hardware (internal) */
  ENCODER_OBJECT_ID_INTERNAL_KLDSCP_TMDS1   = 0x13,
  ENCODER_OBJECT_ID_INTERNAL_KLDSCP_DVO1    = 0x14,
  ENCODER_OBJECT_ID_INTERNAL_KLDSCP_DAC1    = 0x15,
  ENCODER_OBJECT_ID_INTERNAL_KLDSCP_DAC2    = 0x16,  /* Shared with CV/TV and CRT */
  ENCODER_OBJECT_ID_SI178                   = 0X17,  /* External TMDS (dual link, no HDCP.) */
  ENCODER_OBJECT_ID_MVPU_FPGA               = 0x18,  /* MVPU FPGA chip */
  ENCODER_OBJECT_ID_INTERNAL_DDI            = 0x19,
  ENCODER_OBJECT_ID_VT1625                  = 0x1A,
  ENCODER_OBJECT_ID_HDMI_SI1932             = 0x1B,
  ENCODER_OBJECT_ID_DP_AN9801               = 0x1C,
  ENCODER_OBJECT_ID_DP_DP501                = 0x1D,
  ENCODER_OBJECT_ID_INTERNAL_UNIPHY         = 0x1E,
  ENCODER_OBJECT_ID_INTERNAL_KLDSCP_LVTMA   = 0x1F,
  ENCODER_OBJECT_ID_INTERNAL_UNIPHY1        = 0x20,
  ENCODER_OBJECT_ID_INTERNAL_UNIPHY2        = 0x21,
  ENCODER_OBJECT_ID_ALMOND                  = 0x22,
  ENCODER_OBJECT_ID_NUTMEG                  = 0x22,
  ENCODER_OBJECT_ID_TRAVIS                  = 0x23,
  ENCODER_OBJECT_ID_INTERNAL_VCE            = 0x24,
  ENCODER_OBJECT_ID_INTERNAL_UNIPHY3        = 0x25,
  ENCODER_OBJECT_ID_INTERNAL_AMCLK          = 0x27
};

enum {
  CONNECTOR_OBJECT_ID_NONE                = 0x00,
  CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_I   = 0x01,
  CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_I     = 0x02,
  CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_D   = 0x03,
  CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_D     = 0x04,
  CONNECTOR_OBJECT_ID_VGA                 = 0x05,
  CONNECTOR_OBJECT_ID_COMPOSITE           = 0x06,
  CONNECTOR_OBJECT_ID_SVIDEO              = 0x07,
  CONNECTOR_OBJECT_ID_YPbPr               = 0x08,
  CONNECTOR_OBJECT_ID_D_CONNECTOR         = 0x09,
  CONNECTOR_OBJECT_ID_9PIN_DIN            = 0x0A,  /* Supports both CV & TV */
  CONNECTOR_OBJECT_ID_SCART               = 0x0B,
  CONNECTOR_OBJECT_ID_HDMI_TYPE_A         = 0x0C,
  CONNECTOR_OBJECT_ID_HDMI_TYPE_B         = 0x0D,
  CONNECTOR_OBJECT_ID_LVDS                = 0x0E,
  CONNECTOR_OBJECT_ID_7PIN_DIN            = 0x0F,
  CONNECTOR_OBJECT_ID_PCIE_CONNECTOR      = 0x10,
  CONNECTOR_OBJECT_ID_CROSSFIRE           = 0x11,
  CONNECTOR_OBJECT_ID_HARDCODE_DVI        = 0x12,
  CONNECTOR_OBJECT_ID_DISPLAYPORT         = 0x13,
  CONNECTOR_OBJECT_ID_eDP                 = 0x14,
  CONNECTOR_OBJECT_ID_MXM                 = 0x15,
  CONNECTOR_OBJECT_ID_LVDS_eDP            = 0x16
};

// Initially applecon data is nulled.
IOReturn AtiBiosParser2::translateAtomConnectorInfo(AtiBiosParser2 *parser, AtomConnectorInfo *atomcon, ModernConnector *applecon) {
  if (((atomcon->usConnObjectId & OBJECT_TYPE_MASK) >> OBJECT_TYPE_SHIFT) != GRAPH_OBJECT_TYPE_CONNECTOR)
    return kIOReturnNotFound;

  uint8_t *i2cRecord = atomcon->i2cRecord;
  if (i2cRecord) {
    applecon->sense = (i2cRecord[2] & 0xF) + 1;
  } else {
    applecon->sense = 0;
    kprintf("ATOM: %s: ASSERT(NULL != i2cRecord)\n", "uint8_t AtiBiosParser2::getAuxDdcLine(atom_i2c_record *)");
  }

  uint8_t *hpdRecord = (uint8_t *)atomcon->hpdRecord;
  if (hpdRecord) {
    applecon->hotplug = hpdRecord[2];
  } else {
    applecon->hotplug = 0;
    kprintf("ATOM: %s: ASSERT(NULL != hpdRecord)\n", "uint8_t AtiBiosParser2::getHotPlugPin(atom_hpd_int_record *)");
  }

  AtiBiosParser2::getOutputInformation(parser, atomcon, applecon);
  AtiBiosParser2::getConnectorFeatures(parser, atomcon, applecon);

  if (applecon->flags) {
    if ((applecon->flags & 0x704) && applecon->hotplug)
      applecon->features |= 0x100;
    return kIOReturnSuccess;
  } else {
    kprintf("ATOM: %s: ASSERT(0 != drvInfo.connections)\n", "IOReturn AtiBiosParser2::translateAtomConnectorInfo(AtiObjectInfoTableInterface_V2::AtomConnectorInfo &, ConnectorInfo &)");
  }

  return kIOReturnNotFound;
}

IOReturn AtiBiosParser2::getOutputInformation(AtiBiosParser2 *parser, AtomConnectorInfo *atomcon, ModernConnector *applecon) {
  if (!atomcon->usGraphicObjIds) {
    kprintf("ATOM: %s: ASSERT(0 != objId.u16All)\n", "IOReturn AtiBiosParser2::getOutputInformation(AtiObjectInfoTableInterface_V2::AtomConnectorInfo &, ConnectorInfo &)");
    return kIOReturnBadArgument;
  }

  uint8_t encoder = (uint8_t)atomcon->usGraphicObjIds;
  bool one = ((atomcon->usGraphicObjIds & ENUM_ID_MASK) >> ENUM_ID_SHIFT) == 1;

  switch (encoder) {
    case ENCODER_OBJECT_ID_NUTMEG:
      applecon->flags |= 0x10;
      return kIOReturnSuccess;
    case ENCODER_OBJECT_ID_INTERNAL_UNIPHY:
      if (one) {
        applecon->transmitter |= 0x10;
      } else {
        applecon->transmitter |= 0x20;
        applecon->encoder |= 0x1;
      }
      return kIOReturnSuccess;
    case ENCODER_OBJECT_ID_INTERNAL_UNIPHY1:
      if (one) {
        applecon->transmitter |= 0x11;
        applecon->encoder |= 0x2;
      } else {
        applecon->transmitter |= 0x21;
        applecon->encoder |= 0x3;
      }
      return kIOReturnSuccess;
    case ENCODER_OBJECT_ID_INTERNAL_UNIPHY2:
      if (one) {
        applecon->transmitter |= 0x12;
        applecon->encoder |= 0x4;
      } else {
        applecon->transmitter |= 0x22;
        applecon->encoder |= 0x5;
      }
      return kIOReturnSuccess;
    case ENCODER_OBJECT_ID_INTERNAL_UNIPHY3:
      if (one) {
        applecon->transmitter |= 0x13;
        applecon->encoder |= 0x6;
      } else {
        applecon->transmitter |= 0x23;
        applecon->encoder |= 0x7;
      }
      return kIOReturnSuccess;
  }

  return kIOReturnInvalid;
}

IOReturn AtiBiosParser2::getConnectorFeatures(AtiBiosParser2 *parser, AtomConnectorInfo *atomcon, ModernConnector *applecon) {
  if (!atomcon->usConnObjectId) {
    kprintf("ATOM: %s: ASSERT(0 != objId.u16All)\n", "IOReturn AtiBiosParser2::getConnectorFeatures(AtiObjectInfoTableInterface_V2::AtomConnectorInfo &, ConnectorInfo &)");
    return kIOReturnBadArgument;
  }

  uint8_t connector = (uint8_t)atomcon->usGraphicObjIds;

  switch (connector) {
    case CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_I:
    case CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_D:
      applecon->type = ConnectorDigitalDVI;
      applecon->flags |= 4;
      // unlock 2k res, causes crashes on R9 290X
      // undone by -raddvi
      applecon->transmitter &= 0xCF;
      return kIOReturnSuccess;
    case CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_I:
    case CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_D:
      applecon->type = ConnectorDigitalDVI;
      applecon->flags |= 4;
      return kIOReturnSuccess;
    case CONNECTOR_OBJECT_ID_HDMI_TYPE_A:
    case CONNECTOR_OBJECT_ID_HDMI_TYPE_B:
      applecon->type = ConnectorHDMI;
      applecon->flags |= 0x204;
      return kIOReturnSuccess;
    case CONNECTOR_OBJECT_ID_VGA:
      applecon->type = ConnectorVGA;
      applecon->flags |= 0x10;
      return kIOReturnSuccess;
    case CONNECTOR_OBJECT_ID_LVDS:
      applecon->type = ConnectorLVDS;
      applecon->flags |= 0x40;
      applecon->features |= 0x9;
      // unlock 2k res
      applecon->transmitter &= 0xCF;
      return kIOReturnSuccess;
    case CONNECTOR_OBJECT_ID_DISPLAYPORT:
      applecon->type = ConnectorDP;
      applecon->flags |= 0x304;
      return kIOReturnSuccess;
    case CONNECTOR_OBJECT_ID_eDP:
      applecon->type = ConnectorLVDS;
      applecon->flags |= 0x100;
      applecon->features |= 0x109;
      return kIOReturnSuccess;
  }

  return kIOReturnInvalid;
}
<|endoftext|>


<commit_before>// Generated by the gRPC protobuf plugin.
// If you make any local change, they will be lost.
// source: helloworld.proto

#include "helloworld.grpc_cb.pb.h"

#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/once.h>

#include <grpc_cb/impl/client/client_async_call_cqtag.h>  // for ClientAsyncCallCqTag
#include <grpc_cb/impl/client/client_call_cqtag.h>        // for ClientCallCqTag
#include <grpc_cb/impl/cqueue_for_pluck.h>                // for CQueueForPluck
#include <grpc_cb/impl/proto_utils.h>                     // for Proto::Deserialize()
#include <grpc_cb/impl/server/server_reader_cqtag.h>      // for ServerReaderCqTag
#include <grpc_cb/impl/server/server_reader_writer_cqtag.h>  // for ServerReaderWriterCqTag

// package helloworld
namespace helloworld {

namespace {

const ::google::protobuf::ServiceDescriptor*
service_descriptor_Greeter = nullptr;

void AssignDesc_helloworld_2eproto() {
  // Get the file's descriptor from the pool.
  const ::google::protobuf::FileDescriptor* file =
    ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
      "helloworld.proto");
  GOOGLE_CHECK(file != NULL);
  service_descriptor_Greeter = file->service(0);
}  // AssignDesc_helloworld_2eproto()

GOOGLE_PROTOBUF_DECLARE_ONCE(grpc_cb_AssignDescriptors_once_);
inline void AssignDescriptorsOnce() {
  ::google::protobuf::GoogleOnceInit(
    &grpc_cb_AssignDescriptors_once_,
    &AssignDesc_helloworld_2eproto);
}

}  // namespace

namespace Greeter {  // service Greeter

static const std::string method_names[] = {
  "/helloworld.Greeter/SayHello",
};

const ::google::protobuf::ServiceDescriptor& GetServiceDescriptor() {
  AssignDescriptorsOnce();
  assert(service_descriptor_Greeter);
  return *service_descriptor_Greeter;
}

Stub::Stub(const ::grpc_cb::ChannelSptr& channel,
    const ::grpc_cb::CompletionQueueForNextSptr& cq4n_sptr)
    : ::grpc_cb::ServiceStub(channel, cq4n_sptr) {}

::grpc_cb::Status Stub::BlockingSayHello(
    const ::helloworld::HelloRequest& request,
    ::helloworld::HelloReply* response) {
  std::string req_str(request.SerializeAsString());
  const std::string& method = method_names[0];
  std::string resp_str;
  ::grpc_cb::Status status = BlockingRequest(method, req_str, resp_str);
  if (!status.ok() || !response)
    return status;
  if (response->ParseFromString(resp_str))
    return status;
  return status.InternalError("Failed to parse response.");
}

void Stub::AsyncSayHello(
    const ::helloworld::HelloRequest& request,
    const SayHelloCallback& cb,
    const ::grpc_cb::ErrorCallback& ecb) {
  ::grpc_cb::CallSptr call_sptr(MakeSharedCall(method_names[0]));
  using CqTag = ::grpc_cb::ClientAsyncCallCqTag<::helloworld::HelloReply>;
  CqTag* tag = new CqTag(call_sptr);
  tag->SetOnResponse(cb);
  tag->SetOnError(ecb);
  if (tag->Start(request)) return;
  delete tag;
  if (ecb)
    ecb(::grpc_cb::Status::InternalError("Failed to async request."));
}

Service::Service() {}

Service::~Service() {}

const std::string& Service::GetMethodName(size_t method_index) const {
  assert(method_index < GetMethodCount());
  return method_names[method_index];
}

void Service::CallMethod(
    size_t method_index, grpc_byte_buffer* request_buffer,
    const ::grpc_cb::CallSptr& call_sptr) {
  assert(method_index < GetMethodCount());
  switch (method_index) {
    case 0:
      if (!request_buffer) return;
      SayHello(*request_buffer,
          SayHello_Replier(call_sptr));
      return;
  }  // switch
  assert(false);
  (void)request_buffer;
  (void)call_sptr;
}

void Service::SayHello(
    grpc_byte_buffer& request_buffer,
    const SayHello_Replier& replier) {
  using Request = ::helloworld::HelloRequest;
  Request request;
  ::grpc_cb::Status status =
      ::grpc_cb::Proto::Deserialize(
          &request_buffer, &request, 0 /* TODO: max_message_size*/);
  if (status.ok()) {
    SayHello(request, replier);
    return;
  }
  SayHello_Replier(
      replier).ReplyError(status);
}
void Service::SayHello(
    const ::helloworld::HelloRequest& request,
    SayHello_Replier replier) {
  (void)request;
  replier.ReplyError(::grpc_cb::Status::UNIMPLEMENTED);
}

}  // namespace Greeter

}  // namespace helloworld

<commit_msg>Change to use ServiceStub::AsyncRequest().<commit_after>// Generated by the gRPC protobuf plugin.
// If you make any local change, they will be lost.
// source: helloworld.proto

#include "helloworld.grpc_cb.pb.h"

#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/once.h>

#include <grpc_cb/impl/client/client_async_call_cqtag.h>  // for ClientAsyncCallCqTag
#include <grpc_cb/impl/client/client_call_cqtag.h>        // for ClientCallCqTag
#include <grpc_cb/impl/cqueue_for_pluck.h>                // for CQueueForPluck
#include <grpc_cb/impl/proto_utils.h>                     // for Proto::Deserialize()
#include <grpc_cb/impl/server/server_reader_cqtag.h>      // for ServerReaderCqTag
#include <grpc_cb/impl/server/server_reader_writer_cqtag.h>  // for ServerReaderWriterCqTag

// package helloworld
namespace helloworld {

namespace {

const ::google::protobuf::ServiceDescriptor*
service_descriptor_Greeter = nullptr;

void AssignDesc_helloworld_2eproto() {
  // Get the file's descriptor from the pool.
  const ::google::protobuf::FileDescriptor* file =
    ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
      "helloworld.proto");
  GOOGLE_CHECK(file != NULL);
  service_descriptor_Greeter = file->service(0);
}  // AssignDesc_helloworld_2eproto()

GOOGLE_PROTOBUF_DECLARE_ONCE(grpc_cb_AssignDescriptors_once_);
inline void AssignDescriptorsOnce() {
  ::google::protobuf::GoogleOnceInit(
    &grpc_cb_AssignDescriptors_once_,
    &AssignDesc_helloworld_2eproto);
}

}  // namespace

namespace Greeter {  // service Greeter

static const std::string method_names[] = {
  "/helloworld.Greeter/SayHello",
};

const ::google::protobuf::ServiceDescriptor& GetServiceDescriptor() {
  AssignDescriptorsOnce();
  assert(service_descriptor_Greeter);
  return *service_descriptor_Greeter;
}

Stub::Stub(const ::grpc_cb::ChannelSptr& channel,
    const ::grpc_cb::CompletionQueueForNextSptr& cq4n_sptr)
    : ::grpc_cb::ServiceStub(channel, cq4n_sptr) {}

::grpc_cb::Status Stub::BlockingSayHello(
    const ::helloworld::HelloRequest& request,
    ::helloworld::HelloReply* response) {
  std::string resp_str;
  ::grpc_cb::Status status = BlockingRequest(method_names[0],
      request.SerializeAsString(), resp_str);
  if (!status.ok() || !response)
    return status;
  if (response->ParseFromString(resp_str))
    return status;
  return status.InternalError("Failed to parse response.");
}

void Stub::AsyncSayHello(
    const ::helloworld::HelloRequest& request,
    const SayHelloCallback& cb,
    const ::grpc_cb::ErrorCallback& ecb) {
  AsyncRequest(method_names[0], request.SerializeAsString(),
      ((!cb) ? OnResponse() :
      [cb, ecb](const std::string& resp_str) {
        ::helloworld::HelloReply response;
        if (response.ParseFromString(resp_str)) {
          cb(response);
          return;
        }
        if (ecb)
          ecb(::grpc_cb::Status::InternalError("Failed to parse response."));
      }), ecb);
  //::grpc_cb::CallSptr call_sptr(MakeSharedCall(method_names[0]));
  //using CqTag = ::grpc_cb::ClientAsyncCallCqTag<::helloworld::HelloReply>;
  //CqTag* tag = new CqTag(call_sptr);
  //tag->SetOnResponse(cb);
  //tag->SetOnError(ecb);
  //if (tag->Start(request.SerializeAsString()))
  //  return;
  //delete tag;
  //if (ecb)
  //  ecb(::grpc_cb::Status::InternalError("Failed to async request."));
}

Service::Service() {}

Service::~Service() {}

const std::string& Service::GetMethodName(size_t method_index) const {
  assert(method_index < GetMethodCount());
  return method_names[method_index];
}

void Service::CallMethod(
    size_t method_index, grpc_byte_buffer* request_buffer,
    const ::grpc_cb::CallSptr& call_sptr) {
  assert(method_index < GetMethodCount());
  switch (method_index) {
    case 0:
      if (!request_buffer) return;
      SayHello(*request_buffer,
          SayHello_Replier(call_sptr));
      return;
  }  // switch
  assert(false);
  (void)request_buffer;
  (void)call_sptr;
}

void Service::SayHello(
    grpc_byte_buffer& request_buffer,
    const SayHello_Replier& replier) {
  using Request = ::helloworld::HelloRequest;
  Request request;
  ::grpc_cb::Status status =
      ::grpc_cb::Proto::Deserialize(
          &request_buffer, &request, 0 /* TODO: max_message_size*/);
  if (status.ok()) {
    SayHello(request, replier);
    return;
  }
  SayHello_Replier(
      replier).ReplyError(status);
}
void Service::SayHello(
    const ::helloworld::HelloRequest& request,
    SayHello_Replier replier) {
  (void)request;
  replier.ReplyError(::grpc_cb::Status::UNIMPLEMENTED);
}

}  // namespace Greeter

}  // namespace helloworld

<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "configuration.h"

// appleseed.renderer headers.
#include "renderer/kernel/lighting/backwardlightsampler.h"
#include "renderer/kernel/lighting/pt/ptlightingengine.h"
#include "renderer/kernel/lighting/sppm/sppmlightingengine.h"
#include "renderer/kernel/rendering/final/adaptivepixelrenderer.h"
#include "renderer/kernel/rendering/final/uniformpixelrenderer.h"
#include "renderer/kernel/rendering/generic/genericframerenderer.h"
#include "renderer/kernel/rendering/progressive/progressiveframerenderer.h"
#include "renderer/kernel/texturing/texturestore.h"
#include "renderer/utility/paramarray.h"

// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"

// Standard headers.
#include <cassert>
#include <cstring>

using namespace foundation;
using namespace std;

namespace renderer
{

//
// Configuration class implementation.
//

namespace
{
    const UniqueID g_class_uid = new_guid();
}

UniqueID Configuration::get_class_uid()
{
    return g_class_uid;
}

Configuration::Configuration(const char* name)
  : Entity(g_class_uid)
  , m_base(nullptr)
{
    set_name(name);
}

void Configuration::release()
{
    delete this;
}

void Configuration::set_base(const Configuration* base)
{
    m_base = base;
}

const Configuration* Configuration::get_base() const
{
    return m_base;
}

ParamArray Configuration::get_inherited_parameters() const
{
    if (m_base)
    {
        ParamArray params = m_base->m_params;
        params.merge(m_params);
        return params;
    }
    else
    {
        return m_params;
    }
}

Dictionary Configuration::get_metadata()
{
    Dictionary metadata;

    metadata.insert(
        "spectrum_mode",
        Dictionary()
        .insert("type", "enum")
        .insert("values", "rgb|spectral")
        .insert("default", "rgb")
        .insert("label", "Color Pipeline")
        .insert("help", "Color pipeline used throughout the renderer")
        .insert(
            "options",
            Dictionary()
            .insert(
                "rgb",
                Dictionary()
                .insert("label", "RGB")
                .insert("help", "RGB pipeline"))
            .insert(
                "spectral",
                Dictionary()
                .insert("label", "Spectral")
                .insert("help", "Spectral pipeline using 31 equidistant components in the 400-700 nm range"))));

    metadata.insert(
        "sampling_mode",
        Dictionary()
            .insert("type", "enum")
            .insert("values", "rng|qmc")
            .insert("default", "qmc")
            .insert("label", "Sampler")
            .insert("help", "Sampling algorithm used in Monte Carlo integration")
            .insert(
                "options",
                Dictionary()
                    .insert(
                        "rng",
                        Dictionary()
                            .insert("label", "RNG")
                            .insert("help", "Random sampler"))
                    .insert(
                        "qmc",
                        Dictionary()
                            .insert("label", "QMC")
                            .insert("help", "Quasi Monte Carlo sampler"))));

    metadata.insert(
        "lighting_engine",
        Dictionary()
            .insert("type", "enum")
            .insert("values", "pt|sppm")
            .insert("default", "pt")
            .insert("label", "Lighting Engine")
            .insert("help", "Lighting engine used when rendering")
            .insert(
                "options",
                Dictionary()
                    .insert(
                        "pt",
                        Dictionary()
                            .insert("label", "Unidirectional Path Tracer")
                            .insert("help", "Unidirectional path tracing"))
                    .insert(
                        "sppm",
                        Dictionary()
                            .insert("label", "Progressive Photon Mapping")
                            .insert("help", "Stochastic progressive photon mapping"))));

    metadata.insert(
        "rendering_threads",
        Dictionary()
            .insert("type", "int")
            .insert("label", "Render Threads")
            .insert("help", "Number of threads to use for rendering"));

    metadata.dictionaries().insert(
        "light_sampler",
        BackwardLightSampler::get_params_metadata());

    metadata.dictionaries().insert(
        "texture_store",
        TextureStore::get_params_metadata());

    metadata.dictionaries().insert(
        "uniform_pixel_renderer",
        UniformPixelRendererFactory::get_params_metadata());

    metadata.dictionaries().insert(
        "adaptive_pixel_renderer",
        AdaptivePixelRendererFactory::get_params_metadata());

    metadata.dictionaries().insert(
        "generic_frame_renderer",
        GenericFrameRendererFactory::get_params_metadata());

    metadata.dictionaries().insert(
        "progressive_frame_renderer",
        ProgressiveFrameRendererFactory::get_params_metadata());

    metadata.dictionaries().insert("pt", PTLightingEngineFactory::get_params_metadata());
    metadata.dictionaries().insert("sppm", SPPMLightingEngineFactory::get_params_metadata());

    return metadata;
}

//
// ConfigurationFactory class implementation.
//

auto_release_ptr<Configuration> ConfigurationFactory::create(const char* name)
{
    assert(name);

    return auto_release_ptr<Configuration>(new Configuration(name));
}

auto_release_ptr<Configuration> ConfigurationFactory::create(
    const char*         name,
    const ParamArray&   params)
{
    assert(name);

    auto_release_ptr<Configuration> configuration(new Configuration(name));

    configuration->get_parameters().merge(params);

    return configuration;
}

//
// BaseConfigurationFactory class implementation.
//

auto_release_ptr<Configuration> BaseConfigurationFactory::create_base_final()
{
    auto_release_ptr<Configuration> configuration(new Configuration("base_final"));

    ParamArray& parameters = configuration->get_parameters();

    parameters.insert("spectrum_mode", "rgb");
    parameters.insert("sampling_mode", "qmc");

    parameters.insert("frame_renderer", "generic");
    parameters.insert("tile_renderer", "generic");

    parameters.insert("pixel_renderer", "uniform");
    parameters.dictionaries().insert(
        "uniform_pixel_renderer",
        ParamArray()
            .insert("samples", "64"));

    parameters.insert("sample_renderer", "generic");
    parameters.insert("lighting_engine", "pt");

    return configuration;
}

auto_release_ptr<Configuration> BaseConfigurationFactory::create_base_interactive()
{
    auto_release_ptr<Configuration> configuration(new Configuration("base_interactive"));

    ParamArray& parameters = configuration->get_parameters();

    parameters.insert("spectrum_mode", "rgb");
    parameters.insert("sampling_mode", "qmc");

    parameters.insert("frame_renderer", "progressive");
    parameters.insert("sample_generator", "generic");
    parameters.insert("sample_renderer", "generic");
    parameters.insert("lighting_engine", "pt");

    return configuration;
}

bool BaseConfigurationFactory::is_base_final_configuration(const char* name)
{
    assert(name);
    return strcmp(name, "base_final") == 0;
}

bool BaseConfigurationFactory::is_base_interactive_configuration(const char* name)
{
    assert(name);
    return strcmp(name, "base_interactive") == 0;
}

bool BaseConfigurationFactory::is_base_configuration(const char* name)
{
    return is_base_final_configuration(name) || is_base_interactive_configuration(name);
}

}   // namespace renderer
<commit_msg>Tweak input metadata<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "configuration.h"

// appleseed.renderer headers.
#include "renderer/kernel/lighting/backwardlightsampler.h"
#include "renderer/kernel/lighting/pt/ptlightingengine.h"
#include "renderer/kernel/lighting/sppm/sppmlightingengine.h"
#include "renderer/kernel/rendering/final/adaptivepixelrenderer.h"
#include "renderer/kernel/rendering/final/uniformpixelrenderer.h"
#include "renderer/kernel/rendering/generic/genericframerenderer.h"
#include "renderer/kernel/rendering/progressive/progressiveframerenderer.h"
#include "renderer/kernel/texturing/texturestore.h"
#include "renderer/utility/paramarray.h"

// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"

// Standard headers.
#include <cassert>
#include <cstring>

using namespace foundation;
using namespace std;

namespace renderer
{

//
// Configuration class implementation.
//

namespace
{
    const UniqueID g_class_uid = new_guid();
}

UniqueID Configuration::get_class_uid()
{
    return g_class_uid;
}

Configuration::Configuration(const char* name)
  : Entity(g_class_uid)
  , m_base(nullptr)
{
    set_name(name);
}

void Configuration::release()
{
    delete this;
}

void Configuration::set_base(const Configuration* base)
{
    m_base = base;
}

const Configuration* Configuration::get_base() const
{
    return m_base;
}

ParamArray Configuration::get_inherited_parameters() const
{
    if (m_base)
    {
        ParamArray params = m_base->m_params;
        params.merge(m_params);
        return params;
    }
    else
    {
        return m_params;
    }
}

Dictionary Configuration::get_metadata()
{
    Dictionary metadata;

    metadata.insert(
        "spectrum_mode",
        Dictionary()
        .insert("type", "enum")
        .insert("values", "rgb|spectral")
        .insert("default", "rgb")
        .insert("label", "Color Pipeline")
        .insert("help", "Color pipeline used throughout the renderer")
        .insert(
            "options",
            Dictionary()
            .insert(
                "rgb",
                Dictionary()
                .insert("label", "RGB")
                .insert("help", "RGB pipeline"))
            .insert(
                "spectral",
                Dictionary()
                .insert("label", "Spectral")
                .insert("help", "Spectral pipeline using 31 equidistant components in the 400-700 nm range"))));

    metadata.insert(
        "sampling_mode",
        Dictionary()
            .insert("type", "enum")
            .insert("values", "rng|qmc")
            .insert("default", "qmc")
            .insert("label", "Sampler")
            .insert("help", "Sampling algorithm used in Monte Carlo integration")
            .insert(
                "options",
                Dictionary()
                    .insert(
                        "rng",
                        Dictionary()
                            .insert("label", "RNG")
                            .insert("help", "Random sampler"))
                    .insert(
                        "qmc",
                        Dictionary()
                            .insert("label", "QMC")
                            .insert("help", "Quasi Monte Carlo sampler"))));

    metadata.insert(
        "lighting_engine",
        Dictionary()
            .insert("type", "enum")
            .insert("values", "pt|sppm")
            .insert("default", "pt")
            .insert("label", "Lighting Engine")
            .insert("help", "Light transport engine")
            .insert(
                "options",
                Dictionary()
                    .insert(
                        "pt",
                        Dictionary()
                            .insert("label", "Unidirectional Path Tracer")
                            .insert("help", "Unidirectional path tracing"))
                    .insert(
                        "sppm",
                        Dictionary()
                            .insert("label", "Stochastic Progressive Photon Mapping")
                            .insert("help", "Stochastic Progressive Photon Mapping"))));

    metadata.insert(
        "rendering_threads",
        Dictionary()
            .insert("type", "int")
            .insert("label", "Render Threads")
            .insert("help", "Number of threads to use for rendering"));

    metadata.dictionaries().insert(
        "light_sampler",
        BackwardLightSampler::get_params_metadata());

    metadata.dictionaries().insert(
        "texture_store",
        TextureStore::get_params_metadata());

    metadata.dictionaries().insert(
        "uniform_pixel_renderer",
        UniformPixelRendererFactory::get_params_metadata());

    metadata.dictionaries().insert(
        "adaptive_pixel_renderer",
        AdaptivePixelRendererFactory::get_params_metadata());

    metadata.dictionaries().insert(
        "generic_frame_renderer",
        GenericFrameRendererFactory::get_params_metadata());

    metadata.dictionaries().insert(
        "progressive_frame_renderer",
        ProgressiveFrameRendererFactory::get_params_metadata());

    metadata.dictionaries().insert("pt", PTLightingEngineFactory::get_params_metadata());
    metadata.dictionaries().insert("sppm", SPPMLightingEngineFactory::get_params_metadata());

    return metadata;
}

//
// ConfigurationFactory class implementation.
//

auto_release_ptr<Configuration> ConfigurationFactory::create(const char* name)
{
    assert(name);

    return auto_release_ptr<Configuration>(new Configuration(name));
}

auto_release_ptr<Configuration> ConfigurationFactory::create(
    const char*         name,
    const ParamArray&   params)
{
    assert(name);

    auto_release_ptr<Configuration> configuration(new Configuration(name));

    configuration->get_parameters().merge(params);

    return configuration;
}

//
// BaseConfigurationFactory class implementation.
//

auto_release_ptr<Configuration> BaseConfigurationFactory::create_base_final()
{
    auto_release_ptr<Configuration> configuration(new Configuration("base_final"));

    ParamArray& parameters = configuration->get_parameters();

    parameters.insert("spectrum_mode", "rgb");
    parameters.insert("sampling_mode", "qmc");

    parameters.insert("frame_renderer", "generic");
    parameters.insert("tile_renderer", "generic");

    parameters.insert("pixel_renderer", "uniform");
    parameters.dictionaries().insert(
        "uniform_pixel_renderer",
        ParamArray()
            .insert("samples", "64"));

    parameters.insert("sample_renderer", "generic");
    parameters.insert("lighting_engine", "pt");

    return configuration;
}

auto_release_ptr<Configuration> BaseConfigurationFactory::create_base_interactive()
{
    auto_release_ptr<Configuration> configuration(new Configuration("base_interactive"));

    ParamArray& parameters = configuration->get_parameters();

    parameters.insert("spectrum_mode", "rgb");
    parameters.insert("sampling_mode", "qmc");

    parameters.insert("frame_renderer", "progressive");
    parameters.insert("sample_generator", "generic");
    parameters.insert("sample_renderer", "generic");
    parameters.insert("lighting_engine", "pt");

    return configuration;
}

bool BaseConfigurationFactory::is_base_final_configuration(const char* name)
{
    assert(name);
    return strcmp(name, "base_final") == 0;
}

bool BaseConfigurationFactory::is_base_interactive_configuration(const char* name)
{
    assert(name);
    return strcmp(name, "base_interactive") == 0;
}

bool BaseConfigurationFactory::is_base_configuration(const char* name)
{
    return is_base_final_configuration(name) || is_base_interactive_configuration(name);
}

}   // namespace renderer
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Microsoft Corporation
 *
 * -=- Robust Distributed System Nucleus (rDSN) -=-
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * Description:
 *     What is this file about?
 *
 * Revision history:
 *     xxxx-xx-xx, author, first version
 *     xxxx-xx-xx, author, fix bug about xxx
 */

#include "replication_failure_detector.h"
#include "replica_stub.h"

# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "replica.FD"

namespace dsn { namespace replication {

replication_failure_detector::replication_failure_detector(
    replica_stub* stub, std::vector< ::dsn::rpc_address>& meta_servers)
{
    _meta_servers.assign_group(dsn_group_build("meta.servers"));
    _stub = stub;
    for (auto& s : meta_servers)
    {
        dsn_group_add(_meta_servers.group_handle(), s.c_addr());
    }

    dsn_group_set_leader(_meta_servers.group_handle(),
        meta_servers[random32(0, (uint32_t)meta_servers.size() - 1)].c_addr());
}

replication_failure_detector::~replication_failure_detector(void)
{
    dsn_group_destroy(_meta_servers.group_handle());
}

void replication_failure_detector::end_ping(::dsn::error_code err, const fd::beacon_ack& ack, void* context)
{
    dinfo("end ping result, error[%s], ack.this_node[%s], ack.primary_node[%s], ack.is_master[%s], ack.allowed[%s]",
          err.to_string(), ack.this_node.to_string(), ack.primary_node.to_string(),
          ack.is_master ? "true" : "false", ack.allowed ? "true" : "false");

    if (!failure_detector::end_ping_internal(err, ack))
    {
        // not applicable
        return;
    }

    {
        zauto_lock l(_meta_lock);

        if (dsn_group_is_leader(_meta_servers.group_handle(), ack.this_node.c_addr()))
        {
            if (err != ERR_OK)
            {
                // ping failed, switch master
                rpc_address node = dsn_group_next(_meta_servers.group_handle(), ack.this_node.c_addr());
                if (ack.this_node != node)
                {
                    dsn_group_set_leader(_meta_servers.group_handle(), node.c_addr());
                    switch_master(ack.this_node, node);
                }
            }
            else if (ack.is_master == false)
            {
                // switch master
                if (!ack.primary_node.is_invalid()
                        && !dsn_group_is_leader(_meta_servers.group_handle(), ack.primary_node.c_addr()))
                {
                    dsn_group_set_leader(_meta_servers.group_handle(), ack.primary_node.c_addr());
                    switch_master(ack.this_node, ack.primary_node);
                }
            }
            else
            {
            }
        }
        else // ack.this_node is not leader
        {
            if (err != ERR_OK)
            {
                // do nothing
            }
            else if (ack.is_master == false)
            {
                // switch master
                if (!ack.primary_node.is_invalid()
                        && !dsn_group_is_leader(_meta_servers.group_handle(), ack.primary_node.c_addr()))
                {
                    dsn_group_set_leader(_meta_servers.group_handle(), ack.primary_node.c_addr());
                    switch_master(ack.this_node, ack.primary_node);
                }
            }
            else
            {
                ddebug("update meta server leader to [%s]", ack.this_node.to_string());
                switch_master( dsn_group_get_leader(_meta_servers.group_handle()), ack.this_node.c_addr() );
                dsn_group_set_leader(_meta_servers.group_handle(), ack.this_node.c_addr());
            }
        }
    }
}

// client side
void replication_failure_detector::on_master_disconnected( const std::vector< ::dsn::rpc_address>& nodes )
{
    bool primaryDisconnected = false;
    rpc_address leader = dsn_group_get_leader(_meta_servers.group_handle());

    {
        zauto_lock l(_meta_lock);
        for (auto it = nodes.begin(); it != nodes.end(); it++)
        {
            if (leader == *it)
                primaryDisconnected = true;
        }
    }

    if (primaryDisconnected)
    {
        _stub->on_meta_server_disconnected();
    }
}

void replication_failure_detector::on_master_connected(::dsn::rpc_address node)
{
    bool is_primary = false;

    {
        zauto_lock l(_meta_lock);
        is_primary = dsn_group_is_leader(_meta_servers.group_handle(), node.c_addr());
    }

    if (is_primary)
    {
        _stub->on_meta_server_connected();
    }
}

}} // end namespace

<commit_msg>small fix to make the code more elegant<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Microsoft Corporation
 *
 * -=- Robust Distributed System Nucleus (rDSN) -=-
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * Description:
 *     What is this file about?
 *
 * Revision history:
 *     xxxx-xx-xx, author, first version
 *     xxxx-xx-xx, author, fix bug about xxx
 */

#include "replication_failure_detector.h"
#include "replica_stub.h"

# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "replica.FD"

namespace dsn { namespace replication {

replication_failure_detector::replication_failure_detector(
    replica_stub* stub, std::vector< ::dsn::rpc_address>& meta_servers)
{
    _meta_servers.assign_group(dsn_group_build("meta.servers"));
    _stub = stub;
    for (auto& s : meta_servers)
    {
        dsn_group_add(_meta_servers.group_handle(), s.c_addr());
    }

    dsn_group_set_leader(_meta_servers.group_handle(),
        meta_servers[random32(0, (uint32_t)meta_servers.size() - 1)].c_addr());
}

replication_failure_detector::~replication_failure_detector(void)
{
    dsn_group_destroy(_meta_servers.group_handle());
}

void replication_failure_detector::end_ping(::dsn::error_code err, const fd::beacon_ack& ack, void* context)
{
    dinfo("end ping result, error[%s], ack.this_node[%s], ack.primary_node[%s], ack.is_master[%s], ack.allowed[%s]",
          err.to_string(), ack.this_node.to_string(), ack.primary_node.to_string(),
          ack.is_master ? "true" : "false", ack.allowed ? "true" : "false");

    if (!failure_detector::end_ping_internal(err, ack))
    {
        // not applicable
        return;
    }

    {
        zauto_lock l(_meta_lock);

        if (dsn_group_is_leader(_meta_servers.group_handle(), ack.this_node.c_addr()))
        {
            if (err != ERR_OK)
            {
                // ping failed, switch master
                rpc_address node = dsn_group_next(_meta_servers.group_handle(), ack.this_node.c_addr());
                if (ack.this_node != node)
                {
                    dsn_group_set_leader(_meta_servers.group_handle(), node.c_addr());
                    switch_master(ack.this_node, node);
                }
            }
            else if (ack.is_master == false)
            {
                // switch master
                if (!ack.primary_node.is_invalid()
                        && !dsn_group_is_leader(_meta_servers.group_handle(), ack.primary_node.c_addr()))
                {
                    dsn_group_set_leader(_meta_servers.group_handle(), ack.primary_node.c_addr());
                    switch_master(ack.this_node, ack.primary_node);
                }
            }
            else
            {
            }
        }
        else // ack.this_node is not leader
        {
            if (err != ERR_OK)
            {
                // do nothing
            }
            else if (ack.is_master == false)
            {
                // switch master
                if (!ack.primary_node.is_invalid()
                        && !dsn_group_is_leader(_meta_servers.group_handle(), ack.primary_node.c_addr()))
                {
                    dsn_group_set_leader(_meta_servers.group_handle(), ack.primary_node.c_addr());
                    switch_master(ack.this_node, ack.primary_node);
                }
            }
            else
            {
                ddebug("update meta server leader to [%s]", ack.this_node.to_string());
                rpc_address old_leader = dsn_group_get_leader(_meta_servers.group_handle());
                dsn_group_set_leader(_meta_servers.group_handle(), ack.this_node.c_addr());
                switch_master(old_leader, ack.this_node.c_addr() );
            }
        }
    }
}

// client side
void replication_failure_detector::on_master_disconnected( const std::vector< ::dsn::rpc_address>& nodes )
{
    bool primaryDisconnected = false;
    rpc_address leader = dsn_group_get_leader(_meta_servers.group_handle());

    {
        zauto_lock l(_meta_lock);
        for (auto it = nodes.begin(); it != nodes.end(); it++)
        {
            if (leader == *it)
                primaryDisconnected = true;
        }
    }

    if (primaryDisconnected)
    {
        _stub->on_meta_server_disconnected();
    }
}

void replication_failure_detector::on_master_connected(::dsn::rpc_address node)
{
    bool is_primary = false;

    {
        zauto_lock l(_meta_lock);
        is_primary = dsn_group_is_leader(_meta_servers.group_handle(), node.c_addr());
    }

    if (is_primary)
    {
        _stub->on_meta_server_connected();
    }
}

}} // end namespace

<|endoftext|>


<commit_before>#include <algorithm>
#include <iterator>

template <class Iterator>
bool is_sorted (Iterator first, Iterator last)
{
    if (first == last) return true;
    Iterator next = first;
    while (++next != last) {
        if (*next < *first)
            return false;
        ++first;
    }
    return true;
}

template<class Iterator>
void bogosort(Iterator begin, Iterator end)
{
    while(!is_sorted(begin, end))
        random_shuffle(begin, end);
}
<commit_msg>Update bogosort.cpp<commit_after>#include <algorithm>
#include <iterator>

template <class Iterator>
bool is_sorted (Iterator first, Iterator last)
{
    if (first == last) return true;
    Iterator next  = first;
    while (++next != last) {
        if (*next < *first)
            return false;
        ++first;
    }
    return true;
}

template<class Iterator>
void bogosort(Iterator begin, Iterator end)
{
    while(!is_sorted(begin, end))
        random_shuffle(begin, end);
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebM 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 <climits>
#include <vector>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/video_source.h"
#include "test/util.h"

// Enable(1) or Disable(0) writing of the compressed bitstream.
#define WRITE_COMPRESSED_STREAM 0

namespace {

#if WRITE_COMPRESSED_STREAM
static void mem_put_le16(char *const mem, const unsigned int val) {
  mem[0] = val;
  mem[1] = val >> 8;
}

static void mem_put_le32(char *const mem, const unsigned int val) {
  mem[0] = val;
  mem[1] = val >> 8;
  mem[2] = val >> 16;
  mem[3] = val >> 24;
}

static void write_ivf_file_header(const vpx_codec_enc_cfg_t *const cfg,
                                  int frame_cnt, FILE *const outfile) {
  char header[32];

  header[0] = 'D';
  header[1] = 'K';
  header[2] = 'I';
  header[3] = 'F';
  mem_put_le16(header + 4,  0);                   /* version */
  mem_put_le16(header + 6,  32);                  /* headersize */
  mem_put_le32(header + 8,  0x30395056);          /* fourcc (vp9) */
  mem_put_le16(header + 12, cfg->g_w);            /* width */
  mem_put_le16(header + 14, cfg->g_h);            /* height */
  mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
  mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
  mem_put_le32(header + 24, frame_cnt);           /* length */
  mem_put_le32(header + 28, 0);                   /* unused */

  (void)fwrite(header, 1, 32, outfile);
}

static void write_ivf_frame_size(FILE *const outfile, const size_t size) {
  char header[4];
  mem_put_le32(header, static_cast<unsigned int>(size));
  (void)fwrite(header, 1, 4, outfile);
}

static void write_ivf_frame_header(const vpx_codec_cx_pkt_t *const pkt,
                                   FILE *const outfile) {
  char header[12];
  vpx_codec_pts_t pts;

  if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
    return;

  pts = pkt->data.frame.pts;
  mem_put_le32(header, static_cast<unsigned int>(pkt->data.frame.sz));
  mem_put_le32(header + 4, pts & 0xFFFFFFFF);
  mem_put_le32(header + 8, pts >> 32);

  (void)fwrite(header, 1, 12, outfile);
}
#endif  // WRITE_COMPRESSED_STREAM

const unsigned int kInitialWidth = 320;
const unsigned int kInitialHeight = 240;

unsigned int ScaleForFrameNumber(unsigned int frame, unsigned int val) {
  if (frame < 10)
    return val;
  if (frame < 20)
    return val / 2;
  if (frame < 30)
    return val * 2 / 3;
  if (frame < 40)
    return val / 4;
  if (frame < 50)
    return val * 7 / 8;
  return val;
}

class ResizingVideoSource : public ::libvpx_test::DummyVideoSource {
 public:
  ResizingVideoSource() {
    SetSize(kInitialWidth, kInitialHeight);
    limit_ = 60;
  }

  virtual ~ResizingVideoSource() {}

 protected:
  virtual void Next() {
    ++frame_;
    SetSize(ScaleForFrameNumber(frame_, kInitialWidth),
            ScaleForFrameNumber(frame_, kInitialHeight));
    FillFrame();
  }
};

class ResizeTest : public ::libvpx_test::EncoderTest,
  public ::libvpx_test::CodecTestWithParam<libvpx_test::TestMode> {
 protected:
  ResizeTest() : EncoderTest(GET_PARAM(0)) {}

  virtual ~ResizeTest() {}

  struct FrameInfo {
    FrameInfo(vpx_codec_pts_t _pts, unsigned int _w, unsigned int _h)
        : pts(_pts), w(_w), h(_h) {}

    vpx_codec_pts_t pts;
    unsigned int w;
    unsigned int h;
  };

  virtual void SetUp() {
    InitializeConfig();
    SetMode(GET_PARAM(1));
  }

  virtual void DecompressedFrameHook(const vpx_image_t &img,
                                     vpx_codec_pts_t pts) {
    frame_info_list_.push_back(FrameInfo(pts, img.d_w, img.d_h));
  }

  std::vector< FrameInfo > frame_info_list_;
};

TEST_P(ResizeTest, TestExternalResizeWorks) {
  ResizingVideoSource video;
  ASSERT_NO_FATAL_FAILURE(RunLoop(&video));

  for (std::vector<FrameInfo>::iterator info = frame_info_list_.begin();
       info != frame_info_list_.end(); ++info) {
    const vpx_codec_pts_t pts = info->pts;
    const unsigned int expected_w = ScaleForFrameNumber(pts, kInitialWidth);
    const unsigned int expected_h = ScaleForFrameNumber(pts, kInitialHeight);

    EXPECT_EQ(expected_w, info->w)
        << "Frame " << pts << "had unexpected width";
    EXPECT_EQ(expected_h, info->h)
        << "Frame " << pts << "had unexpected height";
  }
}

const unsigned int kStepDownFrame = 3;
const unsigned int kStepUpFrame = 6;

class ResizeInternalTest : public ResizeTest {
 protected:
#if WRITE_COMPRESSED_STREAM
  ResizeInternalTest()
      : ResizeTest(),
        frame0_psnr_(0.0),
        outfile_(NULL),
        out_frames_(0) {}
#else
  ResizeInternalTest() : ResizeTest(), frame0_psnr_(0.0) {}
#endif

  virtual ~ResizeInternalTest() {}

  virtual void BeginPassHook(unsigned int /*pass*/) {
#if WRITE_COMPRESSED_STREAM
    outfile_ = fopen("vp90-2-05-resize.ivf", "wb");
#endif
  }

  virtual void EndPassHook() {
#if WRITE_COMPRESSED_STREAM
    if (outfile_) {
      if (!fseek(outfile_, 0, SEEK_SET))
        write_ivf_file_header(&cfg_, out_frames_, outfile_);
      fclose(outfile_);
      outfile_ = NULL;
    }
#endif
  }

  virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video,
                                  libvpx_test::Encoder *encoder) {
    if (video->frame() == kStepDownFrame) {
      struct vpx_scaling_mode mode = {VP8E_FOURFIVE, VP8E_THREEFIVE};
      encoder->Control(VP8E_SET_SCALEMODE, &mode);
    }
    if (video->frame() == kStepUpFrame) {
      struct vpx_scaling_mode mode = {VP8E_NORMAL, VP8E_NORMAL};
      encoder->Control(VP8E_SET_SCALEMODE, &mode);
    }
  }

  virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
    if (!frame0_psnr_)
      frame0_psnr_ = pkt->data.psnr.psnr[0];
    EXPECT_NEAR(pkt->data.psnr.psnr[0], frame0_psnr_, 1.0);
  }

  virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
#if WRITE_COMPRESSED_STREAM
    ++out_frames_;

    // Write initial file header if first frame.
    if (pkt->data.frame.pts == 0)
      write_ivf_file_header(&cfg_, 0, outfile_);

    // Write frame header and data.
    write_ivf_frame_header(pkt, outfile_);
    (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile_);
#endif
  }

  double frame0_psnr_;
#if WRITE_COMPRESSED_STREAM
  FILE *outfile_;
  unsigned int out_frames_;
#endif
};

TEST_P(ResizeInternalTest, TestInternalResizeWorks) {
  ::libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
                                       30, 1, 0, 10);
  init_flags_ = VPX_CODEC_USE_PSNR;

  // q picked such that initial keyframe on this clip is ~30dB PSNR
  cfg_.rc_min_quantizer = cfg_.rc_max_quantizer = 48;

  // If the number of frames being encoded is smaller than g_lag_in_frames
  // the encoded frame is unavailable using the current API. Comparing
  // frames to detect mismatch would then not be possible. Set
  // g_lag_in_frames = 0 to get around this.
  cfg_.g_lag_in_frames = 0;
  ASSERT_NO_FATAL_FAILURE(RunLoop(&video));

  for (std::vector<FrameInfo>::iterator info = frame_info_list_.begin();
       info != frame_info_list_.end(); ++info) {
    const vpx_codec_pts_t pts = info->pts;
    if (pts >= kStepDownFrame && pts < kStepUpFrame) {
      ASSERT_EQ(282U, info->w) << "Frame " << pts << " had unexpected width";
      ASSERT_EQ(173U, info->h) << "Frame " << pts << " had unexpected height";
    } else {
      EXPECT_EQ(352U, info->w) << "Frame " << pts << " had unexpected width";
      EXPECT_EQ(288U, info->h) << "Frame " << pts << " had unexpected height";
    }
  }
}

VP8_INSTANTIATE_TEST_CASE(ResizeTest, ONE_PASS_TEST_MODES);
VP9_INSTANTIATE_TEST_CASE(ResizeInternalTest,
                          ::testing::Values(::libvpx_test::kOnePassBest));
}  // namespace
<commit_msg>Adjustment to allowed range in resize unit test<commit_after>/*
 *  Copyright (c) 2012 The WebM 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 <climits>
#include <vector>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/video_source.h"
#include "test/util.h"

// Enable(1) or Disable(0) writing of the compressed bitstream.
#define WRITE_COMPRESSED_STREAM 0

namespace {

#if WRITE_COMPRESSED_STREAM
static void mem_put_le16(char *const mem, const unsigned int val) {
  mem[0] = val;
  mem[1] = val >> 8;
}

static void mem_put_le32(char *const mem, const unsigned int val) {
  mem[0] = val;
  mem[1] = val >> 8;
  mem[2] = val >> 16;
  mem[3] = val >> 24;
}

static void write_ivf_file_header(const vpx_codec_enc_cfg_t *const cfg,
                                  int frame_cnt, FILE *const outfile) {
  char header[32];

  header[0] = 'D';
  header[1] = 'K';
  header[2] = 'I';
  header[3] = 'F';
  mem_put_le16(header + 4,  0);                   /* version */
  mem_put_le16(header + 6,  32);                  /* headersize */
  mem_put_le32(header + 8,  0x30395056);          /* fourcc (vp9) */
  mem_put_le16(header + 12, cfg->g_w);            /* width */
  mem_put_le16(header + 14, cfg->g_h);            /* height */
  mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
  mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
  mem_put_le32(header + 24, frame_cnt);           /* length */
  mem_put_le32(header + 28, 0);                   /* unused */

  (void)fwrite(header, 1, 32, outfile);
}

static void write_ivf_frame_size(FILE *const outfile, const size_t size) {
  char header[4];
  mem_put_le32(header, static_cast<unsigned int>(size));
  (void)fwrite(header, 1, 4, outfile);
}

static void write_ivf_frame_header(const vpx_codec_cx_pkt_t *const pkt,
                                   FILE *const outfile) {
  char header[12];
  vpx_codec_pts_t pts;

  if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
    return;

  pts = pkt->data.frame.pts;
  mem_put_le32(header, static_cast<unsigned int>(pkt->data.frame.sz));
  mem_put_le32(header + 4, pts & 0xFFFFFFFF);
  mem_put_le32(header + 8, pts >> 32);

  (void)fwrite(header, 1, 12, outfile);
}
#endif  // WRITE_COMPRESSED_STREAM

const unsigned int kInitialWidth = 320;
const unsigned int kInitialHeight = 240;

unsigned int ScaleForFrameNumber(unsigned int frame, unsigned int val) {
  if (frame < 10)
    return val;
  if (frame < 20)
    return val / 2;
  if (frame < 30)
    return val * 2 / 3;
  if (frame < 40)
    return val / 4;
  if (frame < 50)
    return val * 7 / 8;
  return val;
}

class ResizingVideoSource : public ::libvpx_test::DummyVideoSource {
 public:
  ResizingVideoSource() {
    SetSize(kInitialWidth, kInitialHeight);
    limit_ = 60;
  }

  virtual ~ResizingVideoSource() {}

 protected:
  virtual void Next() {
    ++frame_;
    SetSize(ScaleForFrameNumber(frame_, kInitialWidth),
            ScaleForFrameNumber(frame_, kInitialHeight));
    FillFrame();
  }
};

class ResizeTest : public ::libvpx_test::EncoderTest,
  public ::libvpx_test::CodecTestWithParam<libvpx_test::TestMode> {
 protected:
  ResizeTest() : EncoderTest(GET_PARAM(0)) {}

  virtual ~ResizeTest() {}

  struct FrameInfo {
    FrameInfo(vpx_codec_pts_t _pts, unsigned int _w, unsigned int _h)
        : pts(_pts), w(_w), h(_h) {}

    vpx_codec_pts_t pts;
    unsigned int w;
    unsigned int h;
  };

  virtual void SetUp() {
    InitializeConfig();
    SetMode(GET_PARAM(1));
  }

  virtual void DecompressedFrameHook(const vpx_image_t &img,
                                     vpx_codec_pts_t pts) {
    frame_info_list_.push_back(FrameInfo(pts, img.d_w, img.d_h));
  }

  std::vector< FrameInfo > frame_info_list_;
};

TEST_P(ResizeTest, TestExternalResizeWorks) {
  ResizingVideoSource video;
  ASSERT_NO_FATAL_FAILURE(RunLoop(&video));

  for (std::vector<FrameInfo>::iterator info = frame_info_list_.begin();
       info != frame_info_list_.end(); ++info) {
    const vpx_codec_pts_t pts = info->pts;
    const unsigned int expected_w = ScaleForFrameNumber(pts, kInitialWidth);
    const unsigned int expected_h = ScaleForFrameNumber(pts, kInitialHeight);

    EXPECT_EQ(expected_w, info->w)
        << "Frame " << pts << "had unexpected width";
    EXPECT_EQ(expected_h, info->h)
        << "Frame " << pts << "had unexpected height";
  }
}

const unsigned int kStepDownFrame = 3;
const unsigned int kStepUpFrame = 6;

class ResizeInternalTest : public ResizeTest {
 protected:
#if WRITE_COMPRESSED_STREAM
  ResizeInternalTest()
      : ResizeTest(),
        frame0_psnr_(0.0),
        outfile_(NULL),
        out_frames_(0) {}
#else
  ResizeInternalTest() : ResizeTest(), frame0_psnr_(0.0) {}
#endif

  virtual ~ResizeInternalTest() {}

  virtual void BeginPassHook(unsigned int /*pass*/) {
#if WRITE_COMPRESSED_STREAM
    outfile_ = fopen("vp90-2-05-resize.ivf", "wb");
#endif
  }

  virtual void EndPassHook() {
#if WRITE_COMPRESSED_STREAM
    if (outfile_) {
      if (!fseek(outfile_, 0, SEEK_SET))
        write_ivf_file_header(&cfg_, out_frames_, outfile_);
      fclose(outfile_);
      outfile_ = NULL;
    }
#endif
  }

  virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video,
                                  libvpx_test::Encoder *encoder) {
    if (video->frame() == kStepDownFrame) {
      struct vpx_scaling_mode mode = {VP8E_FOURFIVE, VP8E_THREEFIVE};
      encoder->Control(VP8E_SET_SCALEMODE, &mode);
    }
    if (video->frame() == kStepUpFrame) {
      struct vpx_scaling_mode mode = {VP8E_NORMAL, VP8E_NORMAL};
      encoder->Control(VP8E_SET_SCALEMODE, &mode);
    }
  }

  virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
    if (!frame0_psnr_)
      frame0_psnr_ = pkt->data.psnr.psnr[0];
    EXPECT_NEAR(pkt->data.psnr.psnr[0], frame0_psnr_, 1.5);
  }

  virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
#if WRITE_COMPRESSED_STREAM
    ++out_frames_;

    // Write initial file header if first frame.
    if (pkt->data.frame.pts == 0)
      write_ivf_file_header(&cfg_, 0, outfile_);

    // Write frame header and data.
    write_ivf_frame_header(pkt, outfile_);
    (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile_);
#endif
  }

  double frame0_psnr_;
#if WRITE_COMPRESSED_STREAM
  FILE *outfile_;
  unsigned int out_frames_;
#endif
};

TEST_P(ResizeInternalTest, TestInternalResizeWorks) {
  ::libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
                                       30, 1, 0, 10);
  init_flags_ = VPX_CODEC_USE_PSNR;

  // q picked such that initial keyframe on this clip is ~30dB PSNR
  cfg_.rc_min_quantizer = cfg_.rc_max_quantizer = 48;

  // If the number of frames being encoded is smaller than g_lag_in_frames
  // the encoded frame is unavailable using the current API. Comparing
  // frames to detect mismatch would then not be possible. Set
  // g_lag_in_frames = 0 to get around this.
  cfg_.g_lag_in_frames = 0;
  ASSERT_NO_FATAL_FAILURE(RunLoop(&video));

  for (std::vector<FrameInfo>::iterator info = frame_info_list_.begin();
       info != frame_info_list_.end(); ++info) {
    const vpx_codec_pts_t pts = info->pts;
    if (pts >= kStepDownFrame && pts < kStepUpFrame) {
      ASSERT_EQ(282U, info->w) << "Frame " << pts << " had unexpected width";
      ASSERT_EQ(173U, info->h) << "Frame " << pts << " had unexpected height";
    } else {
      EXPECT_EQ(352U, info->w) << "Frame " << pts << " had unexpected width";
      EXPECT_EQ(288U, info->h) << "Frame " << pts << " had unexpected height";
    }
  }
}

VP8_INSTANTIATE_TEST_CASE(ResizeTest, ONE_PASS_TEST_MODES);
VP9_INSTANTIATE_TEST_CASE(ResizeInternalTest,
                          ::testing::Values(::libvpx_test::kOnePassBest));
}  // namespace
<|endoftext|>


<commit_before>/*
 *  qiaffine.cpp
 *
 *  Copyright (c) 2015 Tobias Wood.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

#include <iostream>

#include "itkMetaDataObject.h"

#include "QI/Util.h"
#include "QI/IO.h"
#include "QI/Args.h"

using namespace std;

template<typename TImage>
void Convert(const std::string &input, const std::string &output) {
    auto image = QI::ReadImage<TImage>(input);
    QI::WriteImage<TImage>(image, output);
}

int main(int argc, char **argv) {
    args::ArgumentParser parser("Converts images between formats\nhttp://github.com/spinicist/QUIT");

    args::Positional<std::string> input_file(parser, "INPUT", "Input file.");
    args::Positional<std::string> output_file(parser, "OUTPUT", "Output file.");

    args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"});
    args::Flag     verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
    args::ValueFlag<std::string> out_prefix(parser, "OUTPREFIX", "Add a prefix to output filenames", {'o', "out"});
    args::ValueFlagList<std::string> rename(parser, "RENAME", "Rename using specified header fields", {'r', "rename"});
    QI::ParseArgs(parser, argc, argv);

    const std::string input = QI::CheckPos(input_file);
    itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(input.c_str(), itk::ImageIOFactory::ReadMode);
    if (!imageIO) {
        cerr << "Could not open: " << input << endl;
        return EXIT_FAILURE;
    }
    imageIO->SetFileName(input);
    imageIO->ReadImageInformation();
    size_t dims = imageIO->GetNumberOfDimensions();
    auto PixelType = imageIO->GetPixelType();

    std::string output = out_prefix.Get();
    if (rename) {
        bool first = true;
        for (const auto rename_field: args::get(rename)) {
            std::vector<std::string> string_array_value;
            std::string string_value;
            double double_value;
            if (first) {
                first = false;
            } else {
                output.append("_");
            }
            auto dict = imageIO->GetMetaDataDictionary();
            if (!dict.HasKey(rename_field)) {
                QI_EXCEPTION("Rename field '" << rename_field << "' not found in header.");
            }
            if (ExposeMetaData(dict, rename_field, string_array_value)) {
                output.append(string_array_value[0]);
            } else if (ExposeMetaData(dict, rename_field, string_value)) {
                output.append(string_value);
            } else if (ExposeMetaData(dict, rename_field, double_value)) {
                std::ostringstream formatted;
                formatted << double_value;
                output.append(formatted.str());
            } else {
                QI_EXCEPTION("Could not determine type of rename header field:" << rename_field);
            }
        }
    } else {
        output.append(QI::Basename(input));
    }
    output.append(QI::CheckPos(output_file));
    #define DIM_SWITCH( N ) \
    case N:\
        switch (PixelType) {\
        case itk::ImageIOBase::SCALAR: Convert<itk::Image<float, N>>(input, output); break;\
        case itk::ImageIOBase::COMPLEX: Convert<itk::Image<std::complex<float>, N>>(input, output); break;\
        default: std::cerr << "Unsupported PixelType: " << PixelType << std::endl; return EXIT_FAILURE;\
        }\
    break;

    switch (dims) {
    DIM_SWITCH( 2 )
    DIM_SWITCH( 3 )
    DIM_SWITCH( 4 )
    }

    #undef DIM_SWITCH

    return EXIT_SUCCESS;
}
<commit_msg>BUG: Fixed rename missing rename header fields.<commit_after>/*
 *  qiaffine.cpp
 *
 *  Copyright (c) 2015 Tobias Wood.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

#include <iostream>

#include "itkMetaDataObject.h"

#include "QI/Util.h"
#include "QI/IO.h"
#include "QI/Args.h"

using namespace std;

template<typename TImage>
void Convert(const std::string &input, const std::string &output) {
    auto image = QI::ReadImage<TImage>(input);
    QI::WriteImage<TImage>(image, output);
}

int main(int argc, char **argv) {
    args::ArgumentParser parser("Converts images between formats\nhttp://github.com/spinicist/QUIT");

    args::Positional<std::string> input_file(parser, "INPUT", "Input file.");
    args::Positional<std::string> output_file(parser, "OUTPUT", "Output file.");

    args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"});
    args::Flag     verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
    args::ValueFlag<std::string> out_prefix(parser, "OUTPREFIX", "Add a prefix to output filenames", {'o', "out"});
    args::ValueFlagList<std::string> rename(parser, "RENAME", "Rename using specified header fields", {'r', "rename"});
    QI::ParseArgs(parser, argc, argv);

    const std::string input = QI::CheckPos(input_file);
    itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(input.c_str(), itk::ImageIOFactory::ReadMode);
    if (!imageIO) {
        cerr << "Could not open: " << input << endl;
        return EXIT_FAILURE;
    }
    imageIO->SetFileName(input);
    imageIO->ReadImageInformation();
    size_t dims = imageIO->GetNumberOfDimensions();
    auto PixelType = imageIO->GetPixelType();

    std::string output = out_prefix.Get();
    if (rename) {
        bool append_delim = false;
        for (const auto rename_field: args::get(rename)) {
            std::vector<std::string> string_array_value;
            std::string string_value;
            double double_value;
            auto dict = imageIO->GetMetaDataDictionary();
            if (!dict.HasKey(rename_field)) {
                std::cout << "Rename field '" << rename_field << "' not found in header. Ignoring" << std::endl;
                continue;
            }
            if (append_delim) {
                output.append("_");
            } else {
                append_delim = true;
            }
            if (ExposeMetaData(dict, rename_field, string_array_value)) {
                output.append(string_array_value[0]);
            } else if (ExposeMetaData(dict, rename_field, string_value)) {
                output.append(string_value);
            } else if (ExposeMetaData(dict, rename_field, double_value)) {
                std::ostringstream formatted;
                formatted << double_value;
                output.append(formatted.str());
            } else {
                QI_EXCEPTION("Could not determine type of rename header field:" << rename_field);
            }
        }
    } else {
        output.append(QI::Basename(input));
    }
    output.append(QI::CheckPos(output_file));
    #define DIM_SWITCH( N ) \
    case N:\
        switch (PixelType) {\
        case itk::ImageIOBase::SCALAR: Convert<itk::Image<float, N>>(input, output); break;\
        case itk::ImageIOBase::COMPLEX: Convert<itk::Image<std::complex<float>, N>>(input, output); break;\
        default: std::cerr << "Unsupported PixelType: " << PixelType << std::endl; return EXIT_FAILURE;\
        }\
    break;

    switch (dims) {
    DIM_SWITCH( 2 )
    DIM_SWITCH( 3 )
    DIM_SWITCH( 4 )
    }

    #undef DIM_SWITCH

    return EXIT_SUCCESS;
}
<|endoftext|>