Quantcast
Channel: Android*
Viewing all 473 articles
Browse latest View live

Integrating Facebook* Functionality into Hybrid Apps Using the Intel XDK

$
0
0

This document will illustrate how to add Facebook functionality to your application using the credentials component of Intel’s App Dev Center.  It includes a sample application, a helper library, and detailed instructions on how to use your Facebook developer account to accept requests from a mobile application.  For more information on how to use Facebook in an application, find the basic article here.

Facebook Developer Page Setup

The first step to integrating Facebook functionality into your application is to create a Facebook application. This setting can then be used to add Facebook functionality to your HTML5 hybrid application or allow you to build your application for Facebook.

Navigate to the Facebook developer site (http://developer.facebook.com) and set up a new Facebook application. Set up the basic information including the display name and namespace.

Set the App Domains

Set the App Domains field to html5tools-software.intel.com and set Sandbox Mode to Disabled.

Set the Mobile Web URL

After setting up the Facebook application, edit the application and set the Mobile Web URL to:

http://html5tools-software.intel.com

 

Copy the Facebook App ID

Once the Mobile Web URL is set, copy down the Facebook Application’s App ID for the next step.  The App ID  is a unique 15-digit number generated by Facebook to identify an application running on their system.

Give App Dev Center the Facebook App ID

Log into the App Dev Center at:

http://appcenter.html5tools-software.intel.com

If you haven’t used App Dev Center in the past, find out more about how to use it here.

If you haven’t yet set up an application to test Facebook Integration, click on the Add or Register an App button.Upload the sample application included with this document for the test.

Find the application to test Facebook integration within the Control Center, and click on the Credentials icon.

 

Select the Configure Facebook option, and then paste the Facebook App ID copied from the previous step into the appropriate edit field.  Enter the same App ID with the letters ‘fb’ in front of it in the Protocol Handler field, unless the particular application uses a different protocol handler for some reason.

 

Please be aware that since the callback will be unique for each application, you may only have one Facebook App Id per App.  Sharing a single Facebook App Id between HTML5m apps could break the process.  

Testing Facebook Integration in the XDK

The first place to test Facebook integration is within the XDK.  The XDK may be installed here:

http://xdk-software.intel.com/

Install the Facebook sample application found along with this implementation guide into a brand new application.  If you run the game in the XDK, it should look something like this.

Touching the Facebook icon in the upper right-hand corner will allow the user to log into Facebook and make a post inviting other folks to play “Awesome Possum” with them.  The code to make that post is delivered through a helper library, but the basic post command should look like this:

document.addEventListener("appMobi.facebook.dialog.complete",function(evt){ console.log("dialog post complete"); },false); AppMobi.facebook.showNewsFeedDialog({"name":"Awesome Possum","caption":"Join the crowd! Awesome Possum is real roadkill-munching fun. Click to try it out now!","link":"http://apps.facebook.com/awesomeaspossum/","picture":"http://dev.appmobi.com/documentation/images/possums.jpg"});

It is passed a JavaScript object with a variety of parameters.  The valid parameters that Facebook accepts for news feed dialogs can be found on their documentation site. The app_id parameter is provided automatically.

When the user activates the code, they should be presented with a page like the one shown below once they log into Facebook:

Testing Facebook Integration on Mobile Device

Testing the Facebook Integration on device is pretty straightforward.  It requires a few more settings to the application on Facebook’s side, as well as setting up a test application to host the application code.  It will work with both iOS and Android devices.

Get the iOS Application ID

The first step to enabling iOS applications to integrate with Facebook is to find your HTML5m application’s bundle ID.  The easiest way to do this is to mouse over the iOS Build Button and select Change Build Settings.

 

In the build settings, look at step 5c for the bundle ID.  Copy it down for later.  

 

Give Facebook the Application ID

Return to the Facebook developer’s site and reopen the Facebook application used for the application.  Select the Edit Settings option to change how the application interacts with Facebook.  Open up the settings for Native iOS Application.  Paste the bundle ID into the field for iOS Bundle ID.  

 

Next, copy down the store ID Apple assigns to the application once it has been submitted to the appstore, and drop them into the appropriate App Store ID fields.  Finally enable both Configured for iOS SSO and iOS Native Deep Linking.  

Copy the Android Key Hash from App Center

Next, you’ll want to set up Facebook integration for the Android version of your app.  The first step to enabling Android applications to integrate with Facebook is to find your application’s Facebook Application Signature.  The easiest way to do this is to mouse over the Android Build Button and select Change Build Settings.

 

During step 4b of the Android build process, copy the Facebook Application Signature from App Center.  The Facebook Application Id should already be in the field for 4a.  

  

Give Facebook the Application Signature

Log back into the Facebook Developer page, and open up the settings for a Native Android App.  Enable the setting for Facebook Login: and paste the application signature taken from the App Center build process into the field marked Key Hash. Also, you will need to paste your BundleID (you can access this from the iOS build, step 5c).

   

Building a Facebook Enabled Native Application

Once you feel confident that the application is working appropriately in the XDK, build the application for iOS or Android (including Amazon and Nook Android builds).  

Select the app building drop down to reveal the list of potential build targets.  

 

Select the appropriate build button to start the process for building the application for iOS, Android, Amazon, or Nook.  Follow the onscreen instructions.  For more information on using the cloud build system, check out this document.

Building your Application for Facebook

The Facebook build button will allow you to create a version of your application appropriate for the Facebook Canvas.  For more information from Facebook about the canvas, read Facebook’s documentation on the subject here.

Clicking on the build for Facebook button will give you the ability to size your application appropriately for the Facebook canvas.  For best results, consider setting the height and width to match the AppMobi.device.useViewPort command.  For example, the sample application uses the following function to handle the appMobi.device.ready event. 

var onDeviceReady=function(){ //Size the display to 768px by 1024px AppMobi.display.useViewport(768,1024); //put the app in Landscape mode AppMobi.device.setRotateOrientation("landscape"); AppMobi.device.setAutoRotate("false"); }

The Facebook application should then use the following settings when it is built:

 

The result of the build is a URL that carries some query string parameters.  The following parameters are simply generated by the build settings:

fbh – Height of the sized Facebook application

fbw – Width of the sized Facebook application

fbs – Scale of the Facebook application, use this to resize the entire application.  A value of ‘1’ indicates no scaling (or scaling at 100%).

Any other query string parameters added to this string will be passed through normally to the application.

 

When the Facebook build completes, download the zip file. At this point you can host it on your own server, or you can host the files with appMobi. If you choose to host with appMobi, click the button to do so. You will need to setup your application with appMobi. After you upload your Facebook build to appMobi, you will be provided with a Content URL. Use this URL (or the URL that you host your application with) to populate the App on Facebook settings.

Reopen the Facebook developer site and edit the settings for the sample application.  Take this URL generated by the Facebook build and insert it into the App on Facebook section of the page.  Use the same URL with an https:// rather than an http:// for the Secure Canvas URL entry.  

 

  • html5
  • javascript
  • Desarrolladores
  • Android*
  • Apple iOS*
  • HTML5
  • HTML5
  • JavaScript*
  • Intermedio
  • Intel® HTML5 Development Environment
  • Contrato de licencia: 

  • Dirección URL
  • Ejemplo de código
  • html5-v2

  • Por dentro do novo Intel® HTML5 Development Environment

    $
    0
    0

    Há alguns meses a Intel lançou um novo conjunto de ferramentas para o desenvolvimento de apps multiplataforma para dispositivos móveis em HTML5, o Intel® HTML5 Development Environment. São ferramentas e serviços na nuvem gratuitos e ilimitados que ajudam os desenvolvedores a escrever uma única base de código usando HTML, CSS e JavaScript e a gerar aplicações (executáveis) para diversos sistemas operacionais e dispositivos móveis.

    Se você tem algum conhecimento em HTML5 e uma boa ideia de desenvolvimento de app na cabeça, recomendo um teste destas ferramentas, pois vai descobrir que implementar esta ideia não é algo tão difícil de fazer.

    O desenvolvimento nativo para dispositivos móveis exige do desenvolvedor conhecimento em linguagens de programação distintas (tipicamente C/C++, Java e C#), e a utilização de ferramentas, compiladores e SDKs específicos para cada sistema operacional. Estas ferramentas por sua vez, demandam a utilização de sistemas operacionais específicos no ambiente de desenvolvimento, o que significa que o desenvolvedor terá que manter algumas máquinas dedicadas ao desenvolvimento e build das aplicações, além de dominar os SDKs e as linguagens específicas.

    A grande vantagem do HTML5 é que bibliotecas específicas criam uma camada de abstração entre os diversos sistemas operacionais de dispositivos móveis, permitindo assim que uma única linha de código tenha o mesmo efeito em sistemas operacionais e dispositivos distintos.

    Além de abstrair estas diferenças, estas bibliotecas auxiliam ainda a complementar as funcionalidades das APIs padrão do HTML5, dando acesso a recursos dos dispositivos, como sensores, câmera e a arquivos existentes nos dispositivos móveis. Com tudo isso junto, quando você desenvolve um app utilizando HTML5, você pode focar todo o seu esforço de desenvolvimento na implementação de funcionalidades inovadoras no seu app ao invés de ficar perdendo muito tempo se preocupando com as nuances e diferenças entre cada dispositivo e sistema operacional.

    Para acelerar ainda mais o desenvolvimento dos seus apps, o Intel XDK (kit de desenvolvimento em plataforma cruzada da Intel), possui ainda duas funcionalidades que considero extremamente úteis para o desenvolvimento de apps. A primeira delas é um editor gráfico para a construção inicial da interface gráfica do seu app (o que para muito programador que conheço costuma ser um pesadelo), e um excelente emulador de dispositivos que permite que você veja como seu app se comporta em dispositivos com tamanhos de tela diferentes sem precisar ter uma infinidade de dispositivos para testes ao seu lado o tempo todo. Este emulador permite ainda que você simule diversos eventos no dispositivo, como a captura de movimento através do acelerômetro, tudo isso dentro do seu navegador Google Chrome, pois o Intel XDK é uma extensão do Google Chrome.

    O ciclo de desenvolvimento, testes e depuração de dispositivos móveis costuma ser bem demorado, pois em geral você precisa compilar cada versão para testes e transferi-la para o seu dispositivo móvel (quem já teve que fazer isso sabe do que eu estou falando). Usando o Intel XDK, você simplesmente instala um App em seu dispositivo móvel (chamado App Lab) e transfere o código que acabou de escrever no XDK para ele usando os serviços gratuitos na nuvem que a Intel oferece. Isso significa que o ciclo de depuração do seu app em um dispositivo real fica extremamente acelerado e depois de uma alteração de código, com apenas alguns cliques você já pode ver como seu app se comporta no seu dispositivo móvel. Melhor do que isso, você pode ainda incluir algumas linhas especiais dentro do seu código e utilizar um sistema de depuração na nuvem, que permite que você execute o app em seu dispositivo móvel e receba as mensagens de depuração na console do seu navegador, ajudando muito a entender o que está de fato acontecendo quando o seu app é executado em um dispositivo real.

    Quando você está satisfeito com o status de desenvolvimento do seu projeto, com alguns cliques você acessa os serviços na nuvem do App Dev Center e gera executáveis na nuvem, prontos para ser enviados para as lojas de aplicativos dos dispositivos ou distribuídos para seus colegas de trabalho e amigos te ajudar com os testes.

    Com tanta coisa assim disponível de forma gratuita e ilimitada, acredito que chegou a hora de você colocar a mão na massa e transformar a ideia que anda te atormentando nos últimos tempos em um app que pode te ajudar no dia a dia, ajudar outras pessoas e claro, que pode ser a sua entrada com chave de ouro para o mundo dos apps para dispositivos móveis.

    Para saber mais sobre as principais características do Intel® HTML5 Development Environment, preparamos um artigo em português que pode ser acessado aqui, que responde as principais dúvidas dos desenvolvedores sobre a ferramenta, além de apresentar mais algumas ferramentas gratuitas da Intel que podem te ajudar a dominar rapidamente este novo mundo de apps multiplataforma.

    Se durante a sua caminhada você tiver alguma dúvida ou dificuldade, utilize nosso fórum de HTML5 em português para que outros membros da comunidade possam te ajudar com ela, e temos ainda diversos exemplos e muito código fonte disponível aqui, e como o HTML5 é um padrão aberto, você pode encontrar na Internet muitos exemplos, tutoriais para te ajudar no aprendizado inicial e claro, se você encontrar alguma biblioteca disponibilizada que queria usar em seu app, basta inclui-la na árvore de código do seu projeto do Intel XDK.

    Toda a documentação das ferramentas e bibliotecas da Intel para o desenvolvimento de Apps pode ser encontrada aqui, e esta página conta ainda com diversos artigos com boas práticas de codificação e diversos tutoriais muito interessantes. Se você prefere aprender assitindo a um vídeo, temos ainda diversos webinars disponíveis aqui, e para começar a sua jornada, recomendo assistir este video aqui.

    Para começar usando agora as ferramentas e finalmente iniciar a sua jornada por este novo e divertido mundo dos apps, clique aqui. Lembre-se que toda grande jornada começa com um primeiro passo, ou melhor dizendo neste caso, com um primeiro clique !

    Imagen del icono: 

    Apresentações da Intel no FISL 14

    $
    0
    0

    Estamos disponibilizando abaixo as apresentações da Intel feitas durante o FISL 14 em Porto Alegre.

    03/07:

    Luciano Palma - Como domar uma fera de 1TFlop que cabe na palma da sua mão

    O Intel Xeon Phi é um coprocessador que equipa o computador mais potente do mundo, o Tianhe-2. Ele traz uma avançada arquitetura que interconecta até 61 núcleos de processamento e 8 GB de memória. Confira como tirar proveito desta façanha tecnológica, utilizando técnicas e ferramentas de paralelismo como as extensões CILK e as bibliotecas Intel TBB.

    Nota: Este é o vídeo que deveria ter sido transmitido ao final da palestra:

    O vídeo da palestra, disponibilizado pela organização do evento pode ser acessado aqui.

    05/07:

    George Silva - Escreva sua app Android sem gastar energia

    As restrições das plataformas móveis, a concorrência e a facilidade dos usuários em recomendar ou criticar as aplicações tornaram o desafio dos desenvolvedores muito maior nas lojas de aplicativos. Além das preocupações com arquitetura e um bom plano de testes, as restrições de bateria e desempenho menor que as plataformas tradicionais exigem mais criatividade para encontrar o melhor balanço entre responsividade e consumo de energia.

    O vídeo da palestra, disponibilizado pela organização do evento pode ser acessado aqui.

    Jomar Silva - Livros eletrônicos interativos com HTML5 e ePub3

    A utilização conjunta dos padrões HTML5 e ePUB3 permite a criação de livros eletrônicos interativos, que são livros eletrônicos tradicionais com Apps em HTML5 embarcadas, expandindo consideravelmente as possibilidades de uso dos livros e possibilitando o reuso de conteúdos já existentes.

    O vídeo da palestra, disponibilizado pela organização do evento pode ser acessado aqui.

    06/07:

    Jomar Silva - Desenvolvimento Apps Híbridos para dispositivos móveis com HTML5

    O número crescente de dispositivos móveis e sistemas operacionais que encontramos hoje na indústria, traz aos desenvolvedores um desafio técnico adicional: Como escrever aplicações com o menor custo e maior alcance de audiência ? Apps híbridos com HTML5 possibilitam aos desenvolvedores manter uma única base de código e gerar a partir dela Apps para diversos dispositivos e sistemas operacionais móveis, com maior flexibilidade e menor time to market.

    O vídeo da palestra, disponibilizado pela organização do evento pode ser acessado aqui.

    Um super obrigado a todos os que assistiram as nossas palestras no FISL 14 e nos vemos no FISL 15 !

    Imagen del icono: 

    Creating a Geolocation App Framework Plugin

    $
    0
    0

    Creating an attractive and effective hybrid HTML5 application that uses geolocation services is easy with this piece of code I would like to share. This plugin for App Framework will query the mobile device for its current location and then plot it on a map drawn on a particular page using App Framework. Take a look at this video for a demonstration:

    You can find the source code for this App Framework Plugin included with this blog post.

  • html5
  • geolocation
  • App Framework
  • Imagen del icono: 

    Adjuntos: 

    http://software.intel.com/sites/default/files/blog/402089/geolocationappframeworkplugin.zip
  • Sample Code
  • html5-v2
  • Intel® Integrated Performance Primitives - Supported Versions

    $
    0
    0

    Interactive support via Intel® Premier Support is provided for the two most recent Intel® Integrated Performance Primitives (Intel® IPP) major releases with a Commercial or Academic license. Older Intel® IPP versions are not supported. However, all users are welcome to post questions in our User Forum.

    If you have any questions about this policy, contact Intel® Premier Support or post on the Intel® IPP User Forum.

    The following Intel® IPP versions are currently supported:

    • Intel® IPP 8.0  for Windows*, Linux*, OS X*
    • Intel® IPP 7.1  for Windows*, Linux*, OS X*

    Product updates are supplied for the most recent version only.

  • support
  • version
  • release
  • Android*
  • Apple Mac OS X*
  • Linux*
  • Microsoft Windows* (XP, Vista, 7)
  • Microsoft Windows* 8
  • Intel® Integrated Performance Primitives
  • Dirección URL
  • Meshcentral.com - New Wifi location feature

    $
    0
    0

    Yesterday I updated Meshcentral.com along with the release of the Microsoft Windows Mesh Agent v1.70 to add a new location feature. First, this is a optional feature, you need to have it enabled in the mesh access policy for this to work, and existing meshes have this feature off by default. If you create a new mesh, just select it during mesh creation. For existing meshes, you need to use Mesh Connector to edit the policy and add the new feature.

    Once location access is enabled, the Windows v1.70 Mesh agent will periodically send nearby WIFI access points and signal strength to the Mesh Server. This is similar with that other services do on mobile phones. Meshcentral.com will compile a list of know access points and keep only the last seen access points for each node.

    I have not yet put any web site features using this data, but I do have a C# API that can connect to Meshcentral.com and ask the following questions:

    • What WIFI location enabled nodes are present in my account?
    • What access points does a given node see?
    • What nodes are visible from a given access point?
    • What nodes are near a given node?

    All queries only return nodes that are present in your Meshcentral.com account. So even if another node belonging to someone else is in the area, it will no show up in these queries. Initialy the idea is to use this information to know what nodes are located physically near each other. This can be used for ad-hoc collaboration, or other uses. In the future, I will be looking at converting this data into real coordinates using some type of 3rd party service so that users can see a map of the location of all nodes on their account. Could be useful for asset tracking and as an anti-theft feature.

    If someone want to try to mesh location API right away, let me know. Otherwise, I will be making it available generally when I get time. I also want to add some use of this data on the web site itself.

    Ylian
    meshcentral.com


  • Mesh. Meshcentral
  • MeshCentral.com
  • p2p
  • WiFi
  • Wireless
  • AP
  • Access Point
  • location
  • Geo-location
  • Geo
  • position
  • map
  • Ylian
  • Imagen del icono: 

    Make Apps Using the Intel HTML5 Development Environment

    $
    0
    0

    Intel is empowering Web developers to create incredible cross-platform experiences, reach more customers, reduce costs, and improve time-to-market.

    Attend this webinar to learn:

    • How to use the Intel HTML5 Development Environment to develop great apps
    • What tools are available to help developers test and debug their HTML5 apps
    • How developers can build their HTML5 apps for a variety of platforms as Web apps or Hybrid apps

    This Webinar is aimed at Web developers interested in using their talents to create cross-platform HTML5 applications for a variety of devices. Join this Webinar to learn how the Intel HTML5 Development Environment can help you!

  • javascript
  • hybrid apps
  • Desarrolladores
  • Android*
  • Apple iOS*
  • Apple Mac OS X*
  • Linux*
  • Microsoft Windows* 8
  • HTML5
  • HTML5
  • JavaScript*
  • Herramientas de desarrollo
  • Dirección URL
  • Empecemos
  • Learning Lab
  • Part 1 of 4 - Make Apps Using the Intel HTML5 Development Environment

    $
    0
    0
    Inglés
    Part 1 of 4 - Make Apps Using the Intel HTML5 Development Environment

    Attend this webinar to learn:

    • How to use the Intel HTML5 Development Environment to develop great apps
    • What tools are available to help developers test and debug their HTML5 apps
    • How developers can build their HTML5 apps for a variety of platforms as Web apps or Hybrid apps

    This Webinar is aimed at Web developers interested in using their talents to create cross-platform HTML5 applications for a variety of devices. Join this Webinar to learn how the Intel HTML5 Development Environment can help you!

    Click here to see the series

  • Tutorial
  • Desarrolladores
  • Empecemos
  • Android*
  • Apple iOS*
  • Apple Mac OS X*
  • Linux*
  • Microsoft Windows* 8
  • HTML5
  • HTML5
  • JavaScript*
  • Herramientas de desarrollo

  • Part 2 of 4 - Make Apps Using the Intel HTML5 Development Environment

    $
    0
    0
    Inglés
    Part 2 of 4 - Make Apps Using the Intel HTML5 Development Environment

    Attend this webinar to learn:

    • How to use the Intel HTML5 Development Environment to develop great apps
    • What tools are available to help developers test and debug their HTML5 apps
    • How developers can build their HTML5 apps for a variety of platforms as Web apps or Hybrid apps

    This Webinar is aimed at Web developers interested in using their talents to create cross-platform HTML5 applications for a variety of devices. Join this Webinar to learn how the Intel HTML5 Development Environment can help you!

    Click here to see the series

  • Tutorial
  • Desarrolladores
  • Empecemos
  • Android*
  • Apple iOS*
  • Apple Mac OS X*
  • Linux*
  • Microsoft Windows* 8
  • HTML5
  • HTML5
  • JavaScript*
  • Herramientas de desarrollo
  • Part 3 of 4 - Make Apps Using the Intel HTML5 Development Environment

    $
    0
    0
    Inglés
    Part 3 of 4 - Make Apps Using the Intel HTML5 Development Environment

    Attend this webinar to learn:

    • How to use the Intel HTML5 Development Environment to develop great apps
    • What tools are available to help developers test and debug their HTML5 apps
    • How developers can build their HTML5 apps for a variety of platforms as Web apps or Hybrid apps

    This Webinar is aimed at Web developers interested in using their talents to create cross-platform HTML5 applications for a variety of devices. Join this Webinar to learn how the Intel HTML5 Development Environment can help you!

    Click here to see the series

  • Tutorial
  • Desarrolladores
  • Empecemos
  • Android*
  • Apple iOS*
  • Apple Mac OS X*
  • Linux*
  • Microsoft Windows* 8
  • HTML5
  • HTML5
  • JavaScript*
  • Herramientas de desarrollo
  • Part 4 of 4 - Make Apps Using the Intel HTML5 Development Environment

    $
    0
    0
    Inglés
    Part 4 of 4 - Make Apps Using the Intel HTML5 Development Environment

    Attend this webinar to learn:

    • How to use the Intel HTML5 Development Environment to develop great apps
    • What tools are available to help developers test and debug their HTML5 apps
    • How developers can build their HTML5 apps for a variety of platforms as Web apps or Hybrid apps

    This Webinar is aimed at Web developers interested in using their talents to create cross-platform HTML5 applications for a variety of devices. Join this Webinar to learn how the Intel HTML5 Development Environment can help you!

    Click here to see the series

  • Tutorial
  • Desarrolladores
  • Empecemos
  • Android*
  • Apple iOS*
  • Apple Mac OS X*
  • Linux*
  • Microsoft Windows* 8
  • HTML5
  • HTML5
  • JavaScript*
  • Herramientas de desarrollo
  • Intel® Memory Protection Extensions (Intel® MPX) Design Considerations

    $
    0
    0

    My very first exposure to buffer overflow was with Morris worm in 80’s and since then, we collectively have tried to get a good handle on buffer overflow as it impacts both security and robustness of C/C++ software. Needless to say, we have made significant progress with addressing buffer overflow via execute disable bit, Canary on stack etc. through which we are able to prevent a class of exploits after the buffer overflow has taken place.

    The work on Intel MPX started with a basic idea that if we can prevent buffer overflow, we can prevent “all” exploits using buffer overflow. At the same time, we recognized that changing C/C++ language (syntax or semantics) or ABI’s would be a deal breaker in terms of adoption. Ideally, we would have liked to have existing binaries be protected from buffer overflow, by inserting the necessary information to check for buffer overflow in the binaries, but this was simply not possible (at least for us). A solution had to be based on compilers, and knowing that having multiple binaries would only prolong its adoption, we had to come up with a creative (efficient) solution so the Intel MPX binary would not only run on legacy systems (albeit without protection) but will also provide end user flexibility in turning Intel MPX on or off at run time. We recognized that an application is not a monolith and it utilizes both OS APIs and third party libraries and not all of these libraries may be compiled/enabled for Intel MPX. Therefore, the Intel MPX-enabled application must be able to call legacy libraries and APIs, and therefore, while we can extend ABIs, we could not change them.

    In summary, we set the following goals for Intel MPX:

    1. No extensions or changes to C/C++
    2. Minimal to no changes to source code
    3. Enabled via compilation
    4. Runs on legacy CPUs with very small performance impact and no benefit
    5. Ability to dynamically turn Intel MPX on or off for an enabled program
    6. No performance impact to legacy applications, and very small performance impact to Intel MPX enabled apps that dynamically turned it off
    7. Hardware acceleration for Intel MPX enabled apps when Intel MPX is turned on.
    8. Extend existing ABIs (for popular OSes)
    9.  Interoperability with legacy libraries and APIs
    10. Support partial compilation/enabling of Intel MPX for incremental enabling and/or performance/security trade-off

     Please keep in mind that performance is highly dependent on nature of application, workload and specific hardware configuration and therefore, will vary.


    Over next few weeks, I will explain key aspects of Intel MPX design that helped us achieve the above goals.

  • MPX Buffer overflow Buffer overrun
  • Imagen del icono: 

    Meshcentral.com - Who is next to me?

    $
    0
    0

    Just a quick follow up on the new Meshcentral.com location feature from my previous post. I just added in the web UI a new entry in the device page that shows which other devices are physically nearby. The new entry is just below the Intel AMT line, and is ranked starting with the nearest node. The distance is determined by how many WIFI access points both devices can see in common. If you hover the mouse over the links, a little box will show the number of AP's in common.

    Ok, that is it. Again, this wifi feature is opt-in only and you need to set the mesh policy to enable it. Also, nodes need to have Wifi to have this work and it will show only other nearby devices that are also in your account.

    Ylian
    meshcentral.com

  • Mesh
  • MeshCentral
  • MeshCentral.com
  • p2p
  • geolocation
  • Geo
  • WiFi
  • Access Point
  • location
  • Ylian
  • Imagen del icono: 

    Fun with Intel® Transactional Synchronization Extensions

    $
    0
    0

    By now, many of you have heard of Intel® Transactional Synchronization Extensions (Intel® TSX). If you have not, I encourage you to check out this page (http://www.intel.com/software/tsx) before you read further. In a nutshell, Intel TSX provides transactional memory support in hardware, making the lives of developers who need to write synchronization codes for concurrent and parallel applications easier. It comes in two flavors: Hardware Lock Elision (HLE) and Restricted Transactional Memory (RTM). If you haven’t read the background, go and do so now, since from here on, I assume that you have that basic knowledge.

    I had been developing a PIN-based emulator for Intel TSX for the past few years. The emulator is now integrated into Intel Software Development Emulator. During the development, I had a lot of grins and grimaces with respect to HLE/RTM. I would like to share three such particularly memorable incidents.

    The Incidents

    Example 1.

    The following codelet is a part of a test program a colleague of mine wrote who wanted to learn how to use RTM. With the array ‘data’ containing integer values and the array ‘group’ mapping the data’s elements to the slots in the array ‘sums’, the test program tries to store the sum of the data belonging to a group in the corresponding slot in the array ‘sums’. Since multiple threads may access the same slot simultaneously, each addition is performed in an RTM transaction. When a transaction aborts, the thread re-executes the addition in the critical section along the fallback path (i.e. ‘else’). Do you think it is correct? If you don’t, can you spot what is wrong?

    #pragma omp parallel for
        for(int i = 0; i < N; i++){
            int mygroup = group[i];
            if(_xbegin()==-1) {
                  sums[mygroup] += data[i];
                _xend();
              } else {
                  #pragma omp critical
                  {
                      sums[mygroup] += data[i];
                  }
              }
          }

    Example 2.

    I was taught code reuse is imporant when I was in school (sorry, not in the kindergarten ;^)). So, I decided to put to work what I learned when a need arose to write an RTM test. The test was similar to the one in Example 1, except that this test alternates RTM and HLE transactions. (Notice that the test does not have the non-speculative fallback path required for the RTM transaction. Having no fallback path makes the test UNSAFE because Intel TSX does not guarantee forward-progress; i.e., it can abort RTM transactions forever.) The test has two addition statements: one is protected with RTM and the other is protected with HLE. Quite a feat, eh? I felt proud of myself ;-) ... until I started to run the test. The test occasionally printed out incorrect sums. I panicked at first because the test was simple and looked almost identical with other tests, leading me to believe, however briefly, that the emulator had a nasty bug that had hidden unnoticed for a long time. But after a closer look, I realized the test had a flaw. Can you see what I did wrong?

        #define PREFIX_XACQUIRE ".byte 0xF2; "    #define PREFIX_XRELEASE ".byte 0xF3; " 
        class mutex_elided {
          uint8_t flag;
          inline bool try_lock_elided() {
            uint8_t value = 1;
            __asm__ volatile (PREFIX_XACQUIRE "lock; xchgl %0, %1"                : "=r"(value),"=m"(flag):"0"(value),"m"(flag):"memory" );
            return uint8_t(value^1);
          }
        public:
          inline void acquire() {
            for(;;) {
                exponential_backoff backoff;
                while((volatile unsigned char&)flag==1)
                    backoff.pause();
                if(try_lock_elided())
                    return;
                __asm__ volatile ("pause\n" : : : "memory" );
            }
          }
     
          inline void release() {
            __asm__ volatile (PREFIX_XRELEASE "movl $0, %0"               : "=m"(flag) : "m"(flag) : "memory" );
          }
        };
        ...
     
     
          mutex_elided m;
    #pragma omp parallel for
        for(int i = 0; i < N; i++) {
            int mygroup = group[i];
            if( (i&1) ) {
                while(_xbegin()!=-1) ;
                // must have a fallback path
                sums[mygroup] += 1;
                _xend();
            } else {
                m.acquire();
                sums[mygroup] += 1;
                m.release();
            }
        }

    Example 3.

    A colleague of mine tried to use RTM to improve performance of a benchmark. (I changed function names for clarity.) The following fragment of the benchmark permutes an array of IDs by, for each ID, swapping its value with that of a randomly picked partner. In the fallback path, elements i and j are exclusively acquired in the increasing order of their indices, and then written back in the reverse order. He was running it on the emulator and came back to me with an occasional hang problem. Can you come up with a sequence of events that leads to an indefinite wait?

    bool pause( volatile int64_t* l ) {
        __asm__ __volatile__( "pause\n" : : : "memory" );
        return true;
    }
     
    int64_t read_and_lock( volatile int64_t* loc ) {
        int64_t val;
        while(1) {
            while( pause( loc ) )
                if(  empty_val != (val = *loc) )
                        break;
            assert( val!=empty_val );
            if ( __sync_bool_compare_and_swap( loc, val, empty_val ) )
                break;
        }
        assert( val!=0 );
        return val;
    }
     
    void write_and_release( volatile int64_t* loc, int64_t val ) {
        while( pause( loc ) )
            if( __sync_bool_compare_and_swap( loc, empty_val, val ) )
                break;
        return;
    }
     
    ...
    #pragma omp parallel for num_threads(16)
        for (int i=0; i<n; i++) {
            int j = (int64_t) ( n * gen_rand() );
     
            if( _xbegin()==-1 ) {
                if(i != j) {
                    const vid_t tmp_val = vid_values[i];
                    vid_values[i] = vid_values[j];
                    vid_values[j] = tmp_val;
                }
                _xend();
            } else {
                if (i < j) {
                    const vid_t tmp_val_i = read_and_lock( &vid_values[i] );
                    const vid_t tmp_val_j = read_and_lock( &vid_values[j] );
                    write_and_release( &vid_values[j], tmp_val_i );
                    write_and_release( &vid_values[i], tmp_val_j );
                } else if (j < i) {
                    const vid_t tmp_val_j = read_and_lock( &vid_values[j] );
                    const vid_t tmp_val_i = read_and_lock( &vid_values[i] );
                    write_and_release( &vid_values[i], tmp_val_j );
                    write_and_release( &vid_values[j], tmp_val_i );
                }
            }
        }

    Analysis

    Example 1.

    The fallback path has a race with the code in the RTM path. For example, the following interleaving may happen. (Always keep in mind that one should not make any assumption on relative speeds of threads!)

    Thread 1
    Thread 2
    start critical section
     
    read sums[mygroup]
     
     
    do transaction that updates 
    sums[mygroup]
    write sums[mygroup]
     

    As a result, the example occasionally loses the increment done in the RTM transaction.

    Example 2.

    Don’t let the HLE transaction fool you. When an HLE transaction gets aborted, it acquires the same mutex non-speculatively. When this happens, the case effectively becomes identical to Example 1.

    Example 3.

    Again, one should not make any assumption on relative speeds of concurrently executing threads. Even though the fallback path is race free on its own, it has a race with the code in the RTM path. For example, the following sequence of events may occur.

    Thread 1
    Thread 2
    read_and_lock( vid_values[i]  )
     
    do transaction that swaps vid_values[i] and
    vid_values[k] and makes vid_values[i] non-zero
    read_and_lock( vid_values[j] )
    write_and_release( vid_values[j] )
     
    Wait for vid_values[i] to become 0
     

    Possible Fixes

    Now that we have concrete diagnosis for each of the examples, the fixes are straightforward.

    Example 1.

    Replacing ‘omp critical’ with an atomic increment such as __sync_add_and_fetch would fix the problem. I.e.,

        __sync_add_and_fetch( &sums[mygroup], data[i] );

     A more general solution is to use a mutex in the fallback path and add it to the readset of the RTM transaction to force the transaction to abort if the mutex is acquired by another thread.

    mutex fallback_mutex;
     
    ...
    #pragma omp parallel for num_threads(8)
        for(int i = 0; i < N; i++){
            int mygroup = group[i];
            if(_xbegin()==-1) {
                if( !fallback_mutex.is_acquired() ) {
                    sums[mygroup] += data[i];
                } else {
                    _xabort(1);
                }
                _xend();
            } else {
                fallback_mutex.acquire();
                sums[mygroup] += data[i];
                fallback_mutex.release();
            }
        }

    Example 2.

    Similarly, we may extend mutex_elided to have the is_acquired() method. Since the lock variable is read inside the RTM transaction, any non-speculative execution of the HLE path which makes the change to the lock variable visible will abort the transaction.

        mutex_elided m;
    #pragma omp parallel for num_threads(8)
        for(int i = 0; i < N; i++) {
            int mygroup = group[i];
            if( (i&1) ) {
                while(_xbegin()!=-1) // having no fallback path is
                    ;                // UNSAFE
                if( !m.is_acquired() )
                    sums[mygroup] += data[i];
                else
                    _xabort(0);
                _xend();
            } else {
                m.acquire();
                sums[mygroup] += data[i];
                m.release();
            }
        }

    Example 3.

    We can also apply the mutex-based approach to this example. Another approach is to read the two ID values in the RTM transaction and check if either of them contains the ‘empty_value’. If so, we abort the transaction and force the thread to follow the fallback path.

    #pragma omp parallel for num_threads(16)
        for (int i=0; i<n; i++) {
            int j = (int64_t) ( n * gen_rand() );
            if( _xbegin()==-1 ) {
                if(i != j) {
                    const vid_t tmp_val_i = vid_values[i];
                    const vid_t tmp_val_j = vid_values[j];
                    if( tmp_val_i==0 || tmp_val_j==0 )
                        _xabort(0);
                    vid_values[i] = tmp_val_j;
                    vid_values[j] = tmp_val_i;
                }
                _xend();
            } else {
                if (i < j) {
                    const vid_t tmp_val_i = read_and_lock( &vid_values[i] );
                    const vid_t tmp_val_j = read_and_lock( &vid_values[j] );
                    write_and_release( &vid_values[j], tmp_val_i );
                    write_and_release( &vid_values[i], tmp_val_j );
                } else if (j < i) {
                    const vid_t tmp_val_j = read_and_lock( &vid_values[j] );
                    const vid_t tmp_val_i = read_and_lock( &vid_values[i] );
                    write_and_release( &vid_values[i], tmp_val_j );
                    write_and_release( &vid_values[j], tmp_val_i );
                }
            }
        }

    Conclusions

    So, what have I learned from these examples? As you may have already noticed, all of these are related to the ‘restricted’ part of RTM. Intel TSX has great potential for improving performance of concurrent/parallel applications. But, the synchronization between the speculative code inside the RTM transaction and the non-speculative fallback path needs to be carefully managed, since the interactions are subtle. I gather most programmers won’t need to worry too much about it because higher-level abstractions in supporting libraries should hide most of agonizing synchronization details. But for those who are willing to get their hands dirty to squeeze out the last drop of performance gain, it always pays to have a watchful eye on the interactions between an RTM code path and its non-speculative fallback. (And we have many tools such as Intel SDE to assist you.)

    Disclaimer: The opinion expressed in the blog is the author's own and reflects none of his employer's or his colleagues'.

  • Intel Transactional Synchronization Extensions (Intel TSX)
  • Restricted Transactional Memory (RTM)
  • Transactional memory
  • hardware lock elision
  • Imagen del icono: 

    Meshcentral.com - Server Issues & News Update

    $
    0
    0

    Quick post to update everyone on a few things:

    • Meshcentral.com has been having outages. A few hours 2 days ago and a few hours yesterday both times during the night. The server is actualy fine but administrators of my server room are doing some work on the network. I did get a few mails about this and forwarded the concerns to the server room administrators. Hopefully it will not happen again.
    • Mesh agent v1.71. I just release a new version of the agent to fix a problems with the agent running on some machines. Version 1.70 had a new wireless scanning feature and made use of "wlanapi.dll" which I assumed all versions of Windows had, even back to Windows XP. Well, the was not correct, some version of Windows Server don't come with wireless services installed and the new agent failed to run. Agent v1.71 has dynamic bindings to this DLL, so if the DLL is not present, it's ok, it will still run but with WiFi scanning disabled.
    • Intel Developer Forum. It's this time of year again, IDF 2013 will be in San Francisco September 10 to 12th. I will be a speaker this time around with one session and two labs. My topic is connecting Intel Platforms to the cloud, I will have a great time using a much hardware features as I can possibly use to make Intel computers work with the cloud. More blogs on this to come.

    That is it for now,
    Ylian
    meshcentral.com

  • Mesh
  • MeshCentral
  • MeshCentral.com
  • p2p
  • database
  • IDF
  • intel developer forum
  • IDF2013
  • Ylian
  • Imagen del icono: 


    Intel Highlights für Entwickler bei der Developer Week 2013 in Nürnberg

    $
    0
    0

    Die jährliche Developer Week 2013 Konferenz von der Neue Mediengesellschaft Ulm mbH fand vom 24. – 26.Juni 2013 in Nürnberg statt. Bei dieser Konferenz handelt es sich sogar um eine Sammlung unterschiedler Konferenzen. So trifft man auf die Developer Week (kurz DWX) die Web Developer Conference (WDC), Mobile Developer Conference (MDC) und die .NET Developer Conference (DDC) in einer Woche und an einem Ort. Das ist gerade hilfreich für Entwickler, die sich oft mehr als für einen Themenbereich interessieren und deswegen immer wieder im Konflikt stehen, welche Konferenz sie besuchen sollen.


    Kurz vor der Eröffnung der DWX 2013 Konferenz

    Wir vom Intel Developer Zone Team waren als Austeller dabei. In unserer Intel Developer Lounge stellten wir passend zum Konzept der Konferenz auch für jeden Themenbereich einen Entwickler-Trend vor. Diese Trends sind eine Kombination aus unseren Hardware- und Softwarelösungen. Einen Wow-Effekt lösten bereits die Softwarelösungen aus. Intel ist schließlich bekannt für gute Hardware, aber was haben wir mit Software für Entwickler zu tun? Genau das möchte ich hier mit ein paar Beispielen wiederholt demonstrieren:

    Perceptual Computing

    Steht im Deutschen für Wahrnehmungs-Computing und zeigt eine neue Art mit Computer agieren zu können. Dabei sind typische Eingabemedien wie die Tastatur, Maus oder Touchscreen von Gestern. Hier wird Software über Sprache und natürlichen Handbewegungen in der Luft gesteuert. Mit Hilfe einer 3D Kamera von Creative und dem Intel® Perceptual Computing SDK 2013, kann man via C++ oder auch mit C# diese neuen Möglichkeiten in die eigene Software implementieren.


    Tanja und Tina beim Spielen ihres Lieblingspiels Kung Pow Kevin

    Neu ist das Konzept nicht. Lange spricht man bereits von Argument Reality, das für erweiterte Realität steht. Aus Bildern von einer Videokamera, soll Software interaktiv eine Lösung bieten. Mit der Spielekonsole Xbox 360 schaffte Microsoft einen Durchbruch mit der ersten 3D Kamera Microsoft Kinect.


    Auch Christoph fuchtelte wild in der Luft herum

    Dennoch bietet derzeit das kostenfreie Intel® Perceptual Computing SDK 2013 eine innovative Lösung gegenüber bekannter Lösungen. Das SDK ist explizit für einzelne Fingergesten konzeptioniert. Womit zum Beispiel fertige Events für „Daumen hoch“, „Daumen runter“ oder dem bekannten „Peace zeichen aus zwei Fingern“ erkannt werden. Es geht noch weiter, eine integrierte Gesichtserkennung ermittelt die Stimmung, ob jemand lacht oder traurig ist. Aber nicht nur das, sondern auch welchem Geschlecht die aktuelle Person entspricht.

    Das kostenfreie Intel® Perceptual Computing SDK 2013 gibt es hier zum Download:
    http://software.intel.com/en-us/vcsource/tools/perceptual-computing-sdk

    Weitere Informationen folgen demnächst mit einem separaten Blog-Post meinerseits. 

    Intel´s App Framework - Eine App für jede Plattform

    Mit nur einem Source-Code, eine App für jede Plattform erstellen. Dieser Traum wurde bereits mit dem Mobile Development Framework PhoneGap ermöglicht. Die Entwicklung findet nur einmalig mit HTML5 und JavaScript statt, der Rest wird automatisch in der Cloud erzeugt.


    Mal was ganz anderes: Uli spielte einen Song passend zu seinem HTML5 Developer Tools Vortrag

    Intel´s App Framework ist quasi eine Erweiterung von PhoneGap und stellt noch viele weitere nützliche Komponenten zur Verfügung. Ein besonderes Highlight ist die Entwicklungsumgebung XDK. Die vollständig vom Browser aus als Web-Anwendung zur Verfügung steht. Das erspart mühevolles Installieren und kann jederzeit von jedem Gerät verwendet werden.


    Intel® XDK

    Ein weiteres persönliches Highlight gegenüber dem klassischen PhoneGap ist, dass Intel kostenfrei das Erstellen der App für jede Plattform in der Cloud erzeugt. Auch das App Framework + XDK bleibt kostenfrei. Was will man als Entwickler mehr?

    Weitere Informationen:
    http://html5dev-software.intel.com

    Auch hier folgen in nächster Zeit noch einige How-To´s meinerseits.

    Tablets, Ultrabooks und Ultrabook Convertibles

    Ultrabook ist ein Konzept von Intel für besonders kleine und leichte Notebooks mit Intel-Prozessoren. Um den Namen tragen zu dürfen, müssen die Geräte eine Reihe von Spezifikationen erfüllen. Dazu gehören eine hohe Akkulaufzeit, eine akzeptable Leistung und Tablet-Computer-ähnliche Eigenschaften wie ein schnelles Aufwachen aus dem Standby. Ein besonderes Merkmal sind ein MultiTouch-Screen und weitere zahlreiche Sensoren wie GPS, NFC, Accelerometer, Magnetometer, Gyrometer, und einen Ambient Light Sensor.


    Tablets, Ultrabooks und Ultrabooks Convertibles

    Einen Schritt weiter gehen Ultrabook Convertibles. Diese Ultrabooks sind Hybrid-Geräte und lassen sich jederzeit sekundenschnell zu einem Tablet verwandeln. Der Start von Windows 8 war gleichzeitig auch der Start dieser neuen Hardware-Generation und namenhafte Hersteller wie Dell, Lenovo, Asus und Toshiba veröffentlichten ihre Vision davon. So bietet jeder seinen eigenen Mechanismus zur Konvertierung an. Die zwei beliebtesten sind das Lenovo IdeaPad Yoga 13 und das Dell XPS 12.


    Acer Iconia W510 Tablets

    Somit sind diese beiden Gerätetypen ideale Kandidaten, wenn es um die App Entwicklung für Tablets und mobile Geräte geht. Auf dem folgenden Video zeige ich, wie einfach auf die Sensoren mit der neuen Windows Runtime zugegriffen wird:

    Mein Tipp: Windows 8 - App-Entwicklung für UltraBook Sensoren mit WinRT - Developer Garden TechTalk

    Smartphones mit ATOM Power

    Der legendäre Intel ATOM-Prozessor, der sich durch seine extrem lange Akkulaufzeit für Netbooks und Tablets bewährt hat, gibt es auch für Smartphones. Das ermöglicht zudem ein schnelles laden der Webseiten und Anwendungen. Auch das Wechseln von App zu App, geschieht flüssig und schnell. So wie man es eben von leistungsstarken Computern gewohnt ist.


    Hier zeigt Florian die Smartphones mit Intel® Technik

    Jedoch gibt es weitere interessante Intel Schmankerl. Das erste russische Android-Smartphone MegaFon Mint ermöglicht eine Full-HD-Wiedergabe von Videos im 1080p-Format. Die 8-MP-HD Kamera nimmt circa 10 Aufnahmen innerhalb 1 Sekunde auf. Damit wird garantiert kein kurzlebiger Augenblick verpasst. Das Beste kommt allerdings noch: Der Wireless-Display-Support. Damit werden Inhalte per Funk auf einen geeigneten HD-Fernseher mit entsprechendem Adapter übertragen. So kann man als Entwickler die eigene App ganz einfach professionell auf einem großen Bildschirm präsentieren.


    Ein Rennspiel was auf dem Smartphone läuft kann bequem via Mini-HDMI-Ausgang vom Bildschirm aus gespielt werden

    Mit einer solchen Vielzahl an Technologien für Smartphones, wird die App-Entwicklung zum Hochgenuss.

    Mein Tipp: Intel Smartphone Reference Demo

    Fazit

    Für mich persönlich war es spannend zu erfahren, welche Geschichte sich hinter jedem einzelnen Entwickler verbirgt. Die Konferenz hat angefangen mit einer jungen Dame, die mit Hilfe von Kinect Software für den Medizinbereich entwickelt. Die Herausforderungen der täglichen Spieleentwicklung brachten mich schon fast zum Schwitzen. Mein Mitgefühl erhielten die Web-Entwickler, die immer noch unter Kompatibilitätsproblemen der unterschiedlichen Browser mit HTML5 leiden.

    Spontan durfte ich für zwei ausgefallene Sessions Vorträge halten. So erzählte ich über "Entwickeln für Sensoren unter Windows 8" und "Softwarearchitektur mit dem Beispiel GoFish".



    Ein weiteres Highlight war unsere große Party bei der Teilnehmer die unseren Stand besuchten exklusiven Zutritt erhielten. Für die Musik sorgte Uli, der auch privat auf großen Bühnen unterwegs ist.

    Auf jeden Fall hat es uns großen Spaß gemacht für jeden etwas dabei zu haben und ich freue mich jetzt schon auf das nächste Jahr, wenn es heißt DWX 2014!

    Imagen del icono: 

    Android* Application Optimization on Intel® Architecture Multi-core Processors

    $
    0
    0

    1. Introduction

    The 4.1 version of Android* has a new improvement that optimizes multi-thread applications running on multi-core processors. The Android operating system can schedule threads to run on each CPU core. In addition, on Intel architecture (IA)-based devices, you have another way to implement multi-core optimization—Intel® Threading Building Blocks (Intel® TBB).

    Intel TBB can be downloaded from http://threadingbuildingblocks.org/download. You must choose the Linux* version. You also need libtbb.so and libtbbmalloc.so, which you can download from lib/android.

    2. Using Intel TBB with SSE

    As we know, SSE ( Streaming SIMD Extensions) can get amazing performance improvements on IA devices, but it only works for single core. Using Intel TBB together with SSE will get the best performance on multi-core devices. Here, I use a program called YUV2RGB as an example.

    YUV2RGB is a color space transform function. You can find this function in many open-source web sites, such as ffmpeg and opencv. Generally it has SSE (or MMX2) function for IA platforms. SSE optimization can get nearly a 6x performance improvement.

    3040*1824 YUV2RGB888

    SWS_BILINEAR

    SWS_FAST_BILINEAR

    C code

    179 ms

    155 ms

    SSE code

    27 ms

    27 ms

    See * below

    But on the Intel® Atom™ processor which is based on a 2-core 4 hyper-threads , Intel TBB can get 2.2X performance improvement. The score should be better when running on more CPU cores.

    Use SSE code + TBB

    12 ms

    12 ms

    See * below for performance tests notice

    3. How to do in detail

    For image processing, we generally apply SSE optimization on the image width. That is to say, we get 8~16 pixels and package them into the XMM register, and then run the SSE instruct on the whole width. Generally, for each width the operation is nearly the same, so parallelism is possible for the height. Sample code for parallelism image processing is shown below:

    #include "tbb/task_scheduler_init.h"
    #include "tbb/blocked_range.h"
    #include "tbb/parallel_for.h"
    
    using namespace tbb;
    
    class multi_two
    {
    public:
      void operator()(const tbb::blocked_range<size_t>& range) const
      {		
    		Log (“range.begin(),range.end()”);
    		for(int j=range.begin();j<range.end();j++) {
    			for(i=0; i<ImgWidth; i+=8) {
    				__asm__ volatile(
    				// do sse 
    			);
    				YUVBuffer+=8;
    			}
    		}
    		//.. the same as UV
      }
        multi_two(BYTE * _RGBBuffer, BYTE * _YUVBuffer)
        {
        	RGBBuffer = _ RGBBuffer;
    		YUVBuffer = _ YUVBuffer;
        }
    private:
    		BYTE * RGBBuffer;
    BYTE * YUVBuffer;
    };
    
    void YUV2RGB(BYTE * YUVBuffer, BYTE * RGBBuffer)
    {
    	tbb::parallel_for(tbb::blocked_range<size_t>(0, height/2), multi_two(YUVBuffer , RGBBuffer ));
    	
    	//if using MMX, remember add emms after all parallel computing finish
    	//__asm__ volatile("emms");	
    }
    

    parallel_for is the simplest usage for Intel TBB. You must create a class that has a function named “operator,” and pass this class as a parameter. The blocked range is important to Intel TBB, as the range tells Intel TBB to split the whole operation into several task ranges from range.begin() to range.end(). So if you set the range as [0,4], you can get 4 logs which may be [2,3], [0,1], [3,4], [1,2]. Generally, we set the task range from 0 to height/2 (for UV height, it is Y height/2).

    Note: The task is not a thread. Intel TBB will create a thread pool according to the CPU core number and distribute these tasks into running threads (from the thread pool). So Intel TBB will try splitting tasks evenly into each thread (each thread binding into a CPU core), and get the best performance compared to multi-thread.

    4. Intel TBB vs. Multi-Thread

    pthread_create(&m_StreamingThread1, NULL, streamingThreadProc1, NULL);
    pthread_create(&m_StreamingThread2, NULL, streamingThreadProc2, NULL);
    pthread_create(&m_StreamingThread3, NULL, streamingThreadProc3, NULL);
    pthread_create(&m_StreamingThread4, NULL, streamingThreadProc4, NULL);
    
    void* status;
    pthread_join(m_StreamingThread1,&status);  //wait thread1 finish
    pthread_join(m_StreamingThread2,&status);  //wait thread2 finish
    pthread_join(m_StreamingThread3,&status);  //wait thread3 finish
    pthread_join(m_StreamingThread4,&status);  //wait thread4 finish
    

    This demo compares Intel TBB and multi-thread. It splits single threads like this:

    When no other threads are running, the execution times for Intel TBB and multi-thread are nearly the same. But when I add some dummy threads that just wait 200 ms, things change. Multi-thread is slower even than single thread, but Intel TBB’s time is still good. The reason, you assume, is that all threads will finish at the same time. But actually some other threads will block the four threads running, so that the total finish time will be slower.

    Test results are shown in the table below (each step adds 2 dummy threads, the dummy thread is just waiting 10 ms).

    STEP

    Multi-Thread

    Intel TBB

    1

    296 ms

    272 ms

    2

    316 ms

    280 ms

    3

    341 ms

    292 ms

    4

    363 ms

    298 ms

    5

    457 ms

    310 ms

    See * below for performance tests notice

    "*": Software and workloads used in performance tests may have been optimized for performance only on Intel microprocessors. Performance tests, such as SYSmark and MobileMark, are measured using specific computer systems, components, software, operations and functions. Any change to any of those factors may cause the results to vary. You should consult other information and performance tests to assist you in fully evaluating your contemplated purchases, including the performance of that product when combined with other products.
    Configurations: [describe config + what test used + who did testing]. For more information go to http://www.intel.com/performance

  • Desarrolladores
  • Android*
  • Android*
  • Optimización
  • Computación en paralelo
  • Phone
  • Tablet
  • Dirección URL
  • NFC Application Development on Android* (multiple case studies)

    $
    0
    0

    Introduction

    NFC (near field communication) is a standards-based, short-range wireless connectivity technology that enables simple and intuitive two-way interactions between electronic devices. It is very convenient to touch and communicate between two NFC devices. For example, with smartphone-integrated NFC technology, you can easily touch your phone to purchase items, share business cards, download discount coupons and so on. You will see many NFC-based new usages will be developed in the future.

    This paper introduces NFC-based technology and usage modes in the current market. Then it also describes how to use NFC in the android applications. Finally, it presents two case studies for how to develop the NFC-based reader/writer applications.

    NFC Technology Architecture

    NFC is based on RFID technology at 13.56 MHz, with a typical operating distance up to 10 cm. The data exchange rate is up to 424 kilobits/s. Compared to other communication technology, the biggest advantage of NFC is it is quick and easy to use. The following graph compares NFC to other communication technologies.

    Figure 1: Comparison of short-range communication technologies

     

    NFC technology has three modes: NFC card emulation mode, peer-to-peer mode, and reader/writer mode, shown in the following graph.

    Figure 2: NFC Protocol Families

     

    In card emulation mode, NFC simulates an RFID integrated circuit (IC) card, with a security module, which allows users to make purchases safely. In peer–to-peer mode, you can share information, such as business cards, between different NFC devices via an NFC connection. You can also set up a WiFi* or Bluetooth* connection quickly through the NFC connection and transfer big files through the WiFi or Bluetooth connection. In reader/writer mode, you can use NFC-enabled devices to read NFC tags and launch smart tasks.

    Each mode is discussed in more detail below.

    NFC Card Emulation Mode

    An NFC module usually consists of two parts: an NFC controller and a secure element (SE). The NFC controller is responsible for communication. The SE is responsible for encrypting and decrypting sensitive data.

    Figure 3: NFC Hardware Components

     

    The SE connects to the NFC controller via SWP (Single Wire Protocol) or DCLB (Digital Contactless Bridge) bus. NFC standards define a logical interface between the host and the controller allowing them to communicate via the RF-field. A built-in app or a small OS implements the SE, which is responsible for the encrypting and decrypting the sensitive data.

    The three solutions to implement the SE are:

    • Embedded in SIM card
    • Embedded in SD card
    • Embedded in NFC Chip

    Figure 4: Three NFC SE Solutions

    The telecom operators, such as CMCC (China Mobile Communication Corporation), Vodafone and AT&T, usually prefer the SIM card-based solution, who are encouraging their users to replace old SIM cards with new NFC-enabled ones for free.

    NFC Peer-to peer Mode

    Two devices with NFC can communicate directly and easily to share small files such as business cards. Two NFC-enabled devices can also share configured .xml files with each other and establish Bluetooth/WiFi connection to share big files. In this mode, no SE module is needed.

    NFC Reader /Writer Mode

    In this mode, the NFC host can read/write NFC tags. A good example is to read useful

    information from smart posters. Users can access links to view the advertisements and download discount coupons.

    Figure 5: NFC Reader/Writer Mode

    Introduction to Android NFC development

    Android supports NFC with two packages: android.nfc and android.nfc.tech.

    The main classes in the android.nfc package are:

    NfcManager: Android devices can be used to manage all indicated NFC adapters, but because most Android devices support only one NFC adapter, NfcManager is generally called directly with getDefaultAdapter to get the specific phone adapter.

    NfcAdapter: It works as an NFC agent, which is similar to the network adapter installed in the computer,by which cellphones access the NFC hardware to initiate NFC communication.

    NDEF: NFC standards define a common data format called NFC Data Exchange Format (NDEF), which can store and transport various kinds of items, ranging from any MIME-typed object to ultra-short RTD-documents, such as URLs. NdefMessage and NdefRecord are two kinds of NDEF for the NFC forum defined data formats, which will be used in the sample code.

    Tag: Android defined it represents a passive object like labels, cards, and so on. When the device detects a tag, Android will create a tag object, then put it in the Intent object, lastly send it to the appropriate Activity.

    The android.nfc.tech package also contains many important sub-classes. These sub-classes provide access to a tag technology's features, which contain read and write operations. Depending on the type of technology used, these classes are divided into different categories, such as: NfcA, NfcB, NfcF, MifareClassic, and so on.

    When a phone has NFC turned on, and after detection of a TAG, the TAG distribution system will automatically create a package of NFC TAG information of intent. If the phone has more than one application that can deal with this intent, a pop-up box will ask the user to choose which TAG activity to do. The TAG distribution system defines three types of intent. It is arranged in descending order of priority:

    NDEF_DISCOVERED, TECH_DISCOVERED, TAG_DISCOVERED

    Here we use the action intent-filter type to handle all types from TECH_DISCOVERED to ACTION_TECH_DISCOVERED. The file nfc_tech_filter.xml is used for the types defined in the file TAG. For details, see the Android documentation. The figure below shows the Activity of the matching process when the phone detects a TAG .

    Figure 6: Process of NFC Tag Detected

    Case study: Develop an NFC-based reader/writer application

    The following demo shows the reader/writer function for the NFC tag. Before you can access a device's NFC hardware and properly handle NFC intents, declare these items in your AndroidManifest.xml file:

    <uses-permission android:name="android.permission.NFC" />
    

    The minimum SDK version that your application must support is level 10, so declare these items in your AndroidManifest.xml file:

    <uses-sdk android:minSdkVersion="10"/>
    
    In the onCreate function,you can apply the NfcAdapter:
    
    public void onCreate(Bundle savedInstanceState) {
    ……
    adapter = NfcAdapter.getDefaultAdapter(this);
    ……
    }  
    

    The following Intent call back shows the reader function. If the system broadcast Intent equals NfcAdapter.ACTION_TAG_DISCOVERED , then you can read the information in the tag and show it.

    @Override
    	protected void onNewIntent(Intent intent){
    		if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
    		mytag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);  // get the detected tag
    		Parcelable[] msgs =
    intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    			NdefRecord firstRecord = ((NdefMessage)msgs[0]).getRecords()[0];
    			byte[] payload = firstRecord.getPayload();
    			int payloadLength = payload.length;
    			int langLength = payload[0];
    			int textLength = payloadLength - langLength - 1;
    			byte[] text = new byte[textLength];
    			System.arraycopy(payload, 1+langLength, text, 0, textLength);
    			Toast.makeText(this, this.getString(R.string.ok_detection)+new String(text), Toast.LENGTH_LONG).show();
    					}
    	}
    
    

    The following code shows the writer function. Before you can determine the value of mytag, you must know whether there is a tag detected or not, then write the information to mytag.

    If (mytag==Null){
    	……
    }
    else{
    ……
    write(message.getText().toString(),mytag);
    ……
    }
    	private void write(String text, Tag tag) throws IOException, FormatException {
    		NdefRecord[] records = { createRecord(text) };
    		NdefMessage  message = new NdefMessage(records);
    // Get an instance of Ndef for the tag.
    		Ndef ndef = Ndef.get(tag); // Enable I/O
    		ndef.connect(); // Write the message
    		ndef.writeNdefMessage(message); // Close the connection
    		ndef.close();
    	}
    
    

    Depending on the information read from the tag, you can do more operations, such as launch a smart task, access a web site, and so on.

    Case study: Develop an NFC-based application that uses the MifareClassic Card

    In this demo, we use the Mifare card for the data read test and use the card’s TAG type, MifareClassic. The MifareClassic card is commonly used in many scenarios, such as ID card,bus card and so on. The traditional MifareClassic card’s storage space is divided into 16 zones (Sector), each zone has four blocks (Block), and each block can store 16 bytes of data.

    The last block in each district is called the Trailer, which is mainly used to store the local block key for reading and writing data. It has two keys: A and B, and each key length is 6 bytes, the default value of which is generally full-key FF or 0 by the MifareClassic.KEY_DEFAULT definition.

    So when writing the Mifare card, you first need to have the correct key value (play a protective role), and the successful authentication must be done before a user can read and write data in the area.

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"   
        package="org.reno"   
        android:versionCode="1"   
        android:versionName="1.0">   
        <uses-permission android:name="android.permission.NFC" />   
        <uses-sdk android:minSdkVersion="14" />   
        <uses-feature android:name="android.hardware.nfc" android:required="true" />   
        <application   
            android:icon="@drawable/ic_launcher"   
            android:label="@string/app_name">   
            <activity   
                android:name="org.reno.Beam"   
                android:label="@string/app_name"   
                android:launchMode="singleTop">   
                <intent-filter>   
                    <action android:name="android.intent.action.MAIN" />   
       
                    <category android:name="android.intent.category.LAUNCHER" />   
                </intent-filter>   
                <intent-filter>   
                    <action android:name="android.nfc.action.TECH_DISCOVERED" />   
                </intent-filter>   
                <meta-data   
                    android:name="android.nfc.action.TECH_DISCOVERED"   
                    android:resource="@xml/nfc_tech_filter" />   
            </activity>  
        </application>   
    </manifest>   
    

    res/xml/nfc_tech_filter.xml:

    <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> 
        <tech-list> 
           <tech>android.nfc.tech.MifareClassic</tech> 
        </tech-list> 
    </resources> 
    

    An example of how to read a MifareClassic card is as follows:

    
         private void processIntent(Intent intent) {    
            Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);   
            for (String tech : tagFromIntent.getTechList()) {   
                System.out.println(tech);   
            }   
            boolean auth = false;   
            MifareClassic mfc = MifareClassic.get(tagFromIntent);   
            try {   
                String metaInfo = "";   
                //Enable I/O operations to the tag from this TagTechnology object.   
                mfc.connect();   
                int type = mfc.getType(); 
                int sectorCount = mfc.getSectorCount();   
                String typeS = "";   
                switch (type) {   
                case MifareClassic.TYPE_CLASSIC:   
                    typeS = "TYPE_CLASSIC";   
                    break;   
                case MifareClassic.TYPE_PLUS:   
                    typeS = "TYPE_PLUS";   
                    break;   
                case MifareClassic.TYPE_PRO:   
                    typeS = "TYPE_PRO";   
                    break;   
                case MifareClassic.TYPE_UNKNOWN:   
                    typeS = "TYPE_UNKNOWN";   
                    break;   
                }   
                metaInfo += "Card type:" + typeS + "n with" + sectorCount + " Sectorsn, "   
                        + mfc.getBlockCount() + " BlocksnStorage Space: " + mfc.getSize() + "Bn";   
                for (int j = 0; j < sectorCount; j++) {   
                    //Authenticate a sector with key A.   
                    auth = mfc.authenticateSectorWithKeyA(j,   
                            MifareClassic.KEY_DEFAULT);   
                    int bCount;   
                    int bIndex;   
                    if (auth) {   
                        metaInfo += "Sector " + j + ": Verified successfullyn";   
                        bCount = mfc.getBlockCountInSector(j);   
                        bIndex = mfc.sectorToBlock(j);   
                        for (int i = 0; i < bCount; i++) {   
                            byte[] data = mfc.readBlock(bIndex);   
                            metaInfo += "Block " + bIndex + " : "   
                                    + bytesToHexString(data) + "n";   
                            bIndex++;   
                        }   
                    } else {   
                        metaInfo += "Sector " + j + ": Verified failuren";   
                    }   
                }   
                promt.setText(metaInfo);   
            } catch (Exception e) {   
                e.printStackTrace();   
            }   
        }   
    

    Summary

    The smartphone equipped with NFC allow individuals to have everything they need at the tip of their fingers without lugging around ticket stubs or parking passes. The technology can even connect with friends to share information, play games, and transfer data. NFC strives to embrace both work and play, a crucial factor in creating its success and facilitating our lives in the future.

    About the Author

    Songyue Wang and Liang Zhang are application engineers in Intel Software and Service Group, and focus on mobile application enabling, including Android applications development and optimization for x86 devices, Web HTML5 application development.

  • Desarrolladores
  • Android*
  • Android*
  • NFC
  • Dirección URL
  • Intel and Baidu Announced a Joint Mobile Application Test Center Offering Free Test For Applications for Intel Android Devices

    $
    0
    0

    Big news last week for Baidu, China's No. 1 search engine giant, Baidu, Inc. announced   that it will buy all equity interests in smartphone apps distributor 91 Wireless from NetDragon for a record 1.9 billion U.S. dollars. According to the memorandum of understanding, the move, which is Baidu's latest effort to show muscle to expand it business,  beyond its core search engine,  to the world’s No. 1  blooming mobile phone and tablet users ecosystem, is set to mark China's biggest merger and acquisition.

    Another news for Baidu this week, Intel and Baidu announced the official launch of a joint mobile application Test Center (MTC), and offer free virtual test platform for compatibility as well as full test for application developed on Android on IA.

     

    Picture above shows the Baidu Application Store interface. Most applications are free and in-app ads supported.

    To help the majority of app application developers to quickly and cost-effectively develop and  publish applications for mobile devices based on Intel architectured.  Intel and Baidu is making available a combination of back-end server to the front end use of mobile devices,  mobile statistical services and one-stop testing and migration for mobile applications developers.  

    Picture above shows the offical  Temple Run 2 application on Baidu.com. The application has 50 millions downloads thus far.

    Every time  there is a new phone comeing out on the market, it is a very troubling issue for an app developer, as they need to buy a lot of mobile phones to be tested, or borrow a phone from a friend. So it is very beneficial for developers and partners to have  a  free virtual environment for a quick and easy way to validate their app and to enter the ecosystem with minimum cost. The proposed MTC testing center can complete the quick compatibility test in 2 hours and is comprehensive fully compatible test  in 6 hours online.

    The picture above shows the in-browser application store on Baidu.com. Baidu has integrated its app store with the Baidu search page.. Bai Du Fact Sheet provides more information about Baidu and its search business.

  • Android Application Testing
  • Imagen del icono: 

    “Why should I update GCC x86 compiler?” or “GCC compiler performance on Intel® Atom™ from version to version”

    $
    0
    0

          I’ll try to figure out what is new for Intel® Atom™ architecture in new versions of GCC and how this affects performance and code size on the well-known EEMBC® CoreMark®  benchmark: www.coremark.org

          The chart below shows CoreMark performance results for base and peak option sets on various GCC versions relative to GCC 4.4.6 base performance (higher is better):

          

    base: “-O2 -ffast-math -mfpmath=sse -m32 -march=atom

    base + if convertion: “-O2 -ffast-math -mfpmath=sse -ftree-loop-if-convert -m32 -march=atom

    peak: “-Ofast -funroll-loops -mfpmath=sse -m32 -march=atom”, for 4.4 and 4.5 versions “-Ofast” is replaced with “-O3 -ffast-math

    See: http://software.intel.com/en-us/blogs/2012/09/26/gcc-x86-performance-hints for performance option details. One of the peak performance option: “-flto” delivers no extra performance on CoreMark.

    Here we can see that the base option set with “-ftree-loop-if-convert” reached peak performance on CoreMark.

          The chart below shows peak to base binary code size ratio on CoreMark for different GCC versions:

          The chart below shows binary code size increase on CoreMark for base option set relative to GCC 4.4.6 base option set:

    -ffunction-sections -Wl,--gc-sections -fno-asynchronous-unwind-tables -Wl,--strip-all” was added to base and peak option sets to get numbers in the chart. These options do not affect performance on CoreMark.

    See: http://software.intel.com/en-us/blogs/2013/01/17/x86-gcc-code-size-optimizations for details.

    Here we can see that code size at peak option set is ~2 times larger than base and keeps growing, base option set code size is a little better than stable.

    All measurements were made for the single thread run at Fedora 17 on Intel® Atom™ CPU D525, 1.80GHz, 4Gb memory, 2 cores.

          GCC showed very good progress from 4.4 to 4.8 version (mostly from 4.6 to 4.7 and from "if conversion" on base at 4.8 version). Code size on base option set is unchanged, on peak it keeps growing.

    Below is a short summary of optimizations influence on CoreMark:

    • GCC 4.5 is the first version introducing "-march=atom" (see http://gcc.gnu.org/gcc-4.5/changes.html). GCC 4.4 represented here just for back reference and CoreMark for this version was built with “-march=i686 -mtune=generic -mssse3”. Major number of current Unix systems are using gcc-4.4+. Note that some gcc-4.4 builds may have “-march=atom” option backported from 4.5. For example, Android NDK gcc-4.4.
    • 4.6 version of GCC introduces much better inline algorithm and new opportunity to improve CoreMark performance: "-ftree-loop-if-convert" which is enabled by default at "-O3 (-Ofast)" and gives ~8% at “base” option set. Official changes: http://gcc.gnu.org/gcc-4.6/changes.html
    • At 4.7 version GCC “-march=atom” get LEA and IMUL tuning as well as other Atom™ architecture specific improvements. By IMUL tuning, I mean IMUL grouping as the architecture has to switch into a special mode to calculate IMUL (fixed in latest Atom™ processor Silvermont). LEA tuning is replacing LEA with moves and adds when LEA result goes to ALU (fixed in latest Atom™ processor Silvermont). Official changes: http://gcc.gnu.org/gcc-4.7/changes.html
    • 4.8 version of GCC improves bool optimizations resulting in less register pressure for some functions in CoreMark (affects only base option set with "-ftree-loop-if-convert” turned on). Also the 4.8 version introduces the ability to lower scheduler pressure: “-fschedule-insns -fsched-pressure” at high stability level on x86 (gives ~1% for CoreMark on peak option set). Generally “-fschedule-insns -fsched-pressure” add performance if "-funroll-loops" option is set. Official changes: http://gcc.gnu.org/gcc-4.8/changes.html

          What if GCC "-march=atom" was just “-march=i686 -mtune=generic -mssse3” at 4.8 version? Performance drop would be ~5%. "-ftree-loop-if-convert” would yield an additional 13% at "base". That’s another reason to switch to the newer version of GCC.

          So if you want to tune Atom™ application performance and care about code size, try GCC 4.8 with:

    “-O2 -ffast-math -mfpmath=sse -ftree-loop-if-convet -fschedule-insns -fsched-pressure -m32 -march=atom”

          If code size is not critical, use GCC 4.8 and:

    “-Ofast -flto -funroll-loops -mfpmath=sse -fschedule-insns -fsched-pressure -m32 -march=atom”

  • gcc
  • GNU
  • compiler performance
  • optimization options
  • code size
  • Imagen del icono: 

  • Analyst Report
  • Case Study
  • Technical Article
  • Viewing all 473 articles
    Browse latest View live