ビデオカメラの仕組み

ビデオカメラでは、レンズで集めた光をカメラ本体にある撮像素子に結像させ、電気信号に変換し、レコーダーに送られた電気信号は、テープ、フラッシュメモリ、HDD、光学ディスクなどに記録される
動画は通常、毎秒30コマの速度で撮影を行う
信号は画面を区切っていき、それを端から時系列に並べたもの
音声を収録するマイクや、音声入力と音声信号をビデオ信号に付加する機能が搭載されている

### ビデオカメラの性能
– CCDが大きいほど解像度が高く、感度が高い(RGB3枚のCCDを使った3CCDカメラなど)

### ビデオカメラの種類
放送用、業務用、民生用、固定型ビデオカメラがある
1. 放送用ビデオカメラ
絶対の信頼性と高画質、機動性を重視
2. 業務用ビデオカメラ
ビデオパッケージなどコスト管理にシビアな映像を高画質で撮影
3. 民生用ビデオカメラ
市民のプライベート用、手ぶれ補正が表中
4. 固定型ビデオカメラ
監視カメラに用いられる

### 構造
用途に応じて形態が異なる
1. 撮影部分が独立
 業務用や監視用ビデオカメラはほとんどこのタイプ
 カメラヘッドからビデオ信号を出力する線が出ており、カメラ制御部(CCU)を経て使用する
2. 撮影部分と録画部分が一体化
  撮影部分と録画部分が一体化したものを一体型という
  録画するビデオテープレコーダ・ハードディスクレコーダ・DVDレコーダなどの録画部が一体
業務用カメラ、民生用カメラの殆どがこのタイプ
3. 組み立て型
  組立型は撮影部と録画部を組み合わせて使うことが前提

### サイズ
スタジオカメラ、肩乗せカメラ、手持ちカメラ、据え置きカメラなどがある

光子からCCDによる電気変換、光電変換からの画像処理の流れなど基本的な構造はデジカメと一緒かと思ったが、音声信号はカメラにはなく、記録メディアも異なり、一緒くたにするのはかなり乱暴か。

Vagrant AmazonLinuxでWebRTC

まず、WebRTCとは?
-WebReal-Time Communicationsの略
-ウェブでシンプルなAPI経由でリアルタイム通信を提供する
-P2P通信
-オープンソース

アーキテクチャ

セッションでやりとりしてるんか。。

-getUserMedia
ブラウザから端末に取り付けられているカメラやマイクにアクセスしてストリームデータを取得
-RTCPeerConnection
マルチメディアセッションを確立するAPI
-RTCDataChannel
テキストデータ、バイナリデータのP2Pデータ通信API

vagrant でvideoのテスト

<!doctype html>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Wrap old and new getUserMedia</title>
</head>
<body>
  Wrap old and new getUserMedia<br />
  <button type="button" onclick="startVideo();">Start</button>
  <button type="button" onclick="stopVideo();">Stop</button>
  <br />
  <video id="local_video" autoplay style="width: 320px; height: 240px; border: 1px solid black;"></video>
</body>
<script type="text/javascript">
  var localVideo = document.getElementById('local_video');
  var localStream = null;

  // --- prefix -----
  navigator.getUserMedia  = navigator.getUserMedia    || navigator.webkitGetUserMedia ||
                            navigator.mozGetUserMedia || navigator.msGetUserMedia;

  // ---------------------- video handling ----------------------- 
  // start local video
  function startVideo() {
    getDeviceStream({video: true, audio: false})
    .then(function (stream) { // success
      localStream = stream;
      playVideo(localVideo, stream);
    }).catch(function (error) { // error
      console.error('getUserMedia error:', error);
      return;
    });
  }

  // stop local video
  function stopVideo() {
    pauseVideo(localVideo);
    stopLocalStream(localStream);
  }

  function stopLocalStream(stream) {
    let tracks = stream.getTracks();
    if (! tracks) {
      console.warn('NO tracks');
      return;
    }
    
    for (let track of tracks) {
      track.stop();
    }
  }
  
  function getDeviceStream(option) {
    if ('getUserMedia' in navigator.mediaDevices) {
      console.log('navigator.mediaDevices.getUserMadia');
      return navigator.mediaDevices.getUserMedia(option);
    }
    else {
      console.log('wrap navigator.getUserMadia with Promise');
      return new Promise(function(resolve, reject){    
        navigator.getUserMedia(option,
          resolve,
          reject
        );
      });      
    }
  }

  function playVideo(element, stream) {
    if ('srcObject' in element) {
      element.srcObject = stream;
    }
    else {
      element.src = window.URL.createObjectURL(stream);
    }
    element.play();
    element.volume = 0;
  }

  function pauseVideo(element) {
    element.pause();
    if ('srcObject' in element) {
      element.srcObject = null;
    }
    else {
      if (element.src && (element.src !== '') ) {
        window.URL.revokeObjectURL(element.src);
      }
      element.src = '';
    }
  }
</script>
</html>

built in
[vagrant@localhost webrtc]$ php -S 192.168.33.10:8000
あれ?
なに、みれないぞ。。

ソースコードがおかしいか?
同じソースコードで、*.github.ioにcommitして確認
=> 見れる

なにいいいいいいいいいいいいいいいいいいいいい
server側の設定か?
そんなばかな。。。 
=> 2時間くらい調査
=> 少し疲れたので休憩

=> あれ、videoタグの設定か?
=> chromeのカメラの設定を確認

httpだと、カメラのアクセスがブロックされるのね。。。
amazon linuxにmod-sslを入れます。

[vagrant@localhost webrtc]$ sudo yum install -y mod_ssl
–> Finished Dependency Resolution
Error: httpd24 conflicts with httpd-2.2.34-1.15.amzn1.x86_64
Error: httpd24-tools conflicts with httpd-tools-2.2.34-1.15.amzn1.x86_64

ぎゃああああああああああああああああああああああ

[vagrant@localhost webrtc]$ sudo yum install mod24_ssl
Complete!

もうやだ。

Google APIs Client Library for PHP

Google APIs Client Library for PHP
https://code.google.com/archive/p/google-api-php-client/downloads

最新版をダウンロードして、展開します。

[vagrant@localhost youtube]$ tar zxvf google-api-php-client-0.6.7.tar.gz
google-api-php-client/
google-api-php-client/NOTICE
google-api-php-client/README
google-api-php-client/test/
google-api-php-client/test/phpunit.xml
google-api-php-client/test/general/
google-api-php-client/test/general/OAuthHelper.php
google-api-php-client/test/general/CacheTest.php
google-api-php-client/test/general/GeneralTests.php
google-api-php-client/test/general/AuthTest.php
google-api-php-client/test/general/ServiceTest.php
google-api-php-client/test/general/ApiModelTest.php
google-api-php-client/test/general/IoTest.php
google-api-php-client/test/general/testdata/
google-api-php-client/test/general/testdata/test_public_key.pem
google-api-php-client/test/general/ApiClientTest.php
google-api-php-client/test/general/ApiOAuth2Test.php
google-api-php-client/test/general/ApiMediaFileUploadTest.php
google-api-php-client/test/general/ApiBatchRequestTest.php
google-api-php-client/test/general/RestTest.php
google-api-php-client/test/general/ApiCacheParserTest.php
google-api-php-client/test/tasks/
google-api-php-client/test/tasks/TasksTest.php
google-api-php-client/test/tasks/AllTasksTests.php
google-api-php-client/test/adsense/
google-api-php-client/test/adsense/AdSenseTest.php
google-api-php-client/test/AllTests.php
google-api-php-client/test/README
google-api-php-client/test/plus/
google-api-php-client/test/plus/PlusTest.php
google-api-php-client/test/BaseTest.php
google-api-php-client/test/pagespeed/
google-api-php-client/test/pagespeed/PageSpeedTest.php
google-api-php-client/test/pagespeed/AllPageSpeedTests.php
google-api-php-client/test/urlshortener/
google-api-php-client/test/urlshortener/AllUrlShortenerTests.php
google-api-php-client/test/urlshortener/UrlShortenerTests.php
google-api-php-client/src/
google-api-php-client/src/cache/
google-api-php-client/src/cache/Google_MemcacheCache.php
google-api-php-client/src/cache/Google_Cache.php
google-api-php-client/src/cache/Google_FileCache.php
google-api-php-client/src/cache/Google_ApcCache.php
google-api-php-client/src/Google_Client.php
google-api-php-client/src/config.php
google-api-php-client/src/auth/
google-api-php-client/src/auth/Google_LoginTicket.php
google-api-php-client/src/auth/Google_Auth.php
google-api-php-client/src/auth/Google_Verifier.php
google-api-php-client/src/auth/Google_PemVerifier.php
google-api-php-client/src/auth/Google_AssertionCredentials.php
google-api-php-client/src/auth/Google_OAuth2.php
google-api-php-client/src/auth/Google_AuthNone.php
google-api-php-client/src/auth/Google_Signer.php
google-api-php-client/src/auth/Google_P12Signer.php
google-api-php-client/src/io/
google-api-php-client/src/io/Google_HttpStreamIO.php
google-api-php-client/src/io/Google_CacheParser.php
google-api-php-client/src/io/Google_HttpRequest.php
google-api-php-client/src/io/cacerts.pem
google-api-php-client/src/io/Google_CurlIO.php
google-api-php-client/src/io/Google_REST.php
google-api-php-client/src/io/Google_IO.php
google-api-php-client/src/service/
google-api-php-client/src/service/Google_ServiceResource.php
google-api-php-client/src/service/Google_Service.php
google-api-php-client/src/service/Google_MediaFileUpload.php
google-api-php-client/src/service/Google_Utils.php
google-api-php-client/src/service/Google_BatchRequest.php
google-api-php-client/src/service/Google_Model.php
google-api-php-client/src/contrib/
google-api-php-client/src/contrib/Google_SQLAdminService.php
google-api-php-client/src/contrib/Google_PlusService.php
google-api-php-client/src/contrib/Google_UrlshortenerService.php
google-api-php-client/src/contrib/Google_FreebaseService.php
google-api-php-client/src/contrib/Google_DatastoreService.php
google-api-php-client/src/contrib/Google_AdExchangeSellerService.php
google-api-php-client/src/contrib/Google_ReportsService.php
google-api-php-client/src/contrib/Google_StorageService.php
google-api-php-client/src/contrib/Google_SiteVerificationService.php
google-api-php-client/src/contrib/Google_TasksService.php
google-api-php-client/src/contrib/Google_CustomsearchService.php
google-api-php-client/src/contrib/Google_TranslateService.php
google-api-php-client/src/contrib/Google_CalendarService.php
google-api-php-client/src/contrib/Google_ShoppingService.php
google-api-php-client/src/contrib/Google_AndroidpublisherService.php
google-api-php-client/src/contrib/Google_GroupssettingsService.php
google-api-php-client/src/contrib/Google_PredictionService.php
google-api-php-client/src/contrib/Google_FusiontablesService.php
google-api-php-client/src/contrib/Google_MirrorService.php
google-api-php-client/src/contrib/Google_AdSenseService.php
google-api-php-client/src/contrib/Google_AppstateService.php
google-api-php-client/src/contrib/Google_CoordinateService.php
google-api-php-client/src/contrib/Google_DriveService.php
google-api-php-client/src/contrib/Google_AnalyticsService.php
google-api-php-client/src/contrib/Google_DfareportingService.php
google-api-php-client/src/contrib/Google_GamesService.php
google-api-php-client/src/contrib/Google_BooksService.php
google-api-php-client/src/contrib/Google_PagespeedonlineService.php
google-api-php-client/src/contrib/Google_AdsensehostService.php
google-api-php-client/src/contrib/Google_OrkutService.php
google-api-php-client/src/contrib/Google_AdexchangebuyerService.php
google-api-php-client/src/contrib/Google_DirectoryService.php
google-api-php-client/src/contrib/Google_YouTubeService.php
google-api-php-client/src/contrib/Google_LicensingService.php
google-api-php-client/src/contrib/Google_CivicInfoService.php
google-api-php-client/src/contrib/Google_BigqueryService.php
google-api-php-client/src/contrib/Google_ResellerService.php
google-api-php-client/src/contrib/Google_Oauth2Service.php
google-api-php-client/src/contrib/Google_ModeratorService.php
google-api-php-client/src/contrib/Google_ComputeService.php
google-api-php-client/src/contrib/Google_TaskqueueService.php
google-api-php-client/src/contrib/Google_GamesManagementService.php
google-api-php-client/src/contrib/Google_GanService.php
google-api-php-client/src/contrib/Google_BloggerService.php
google-api-php-client/src/contrib/Google_PlusDomainsService.php
google-api-php-client/src/contrib/Google_YouTubeAnalyticsService.php
google-api-php-client/src/contrib/Google_WebfontsService.php
google-api-php-client/src/contrib/Google_AuditService.php
google-api-php-client/src/external/
google-api-php-client/src/external/URITemplateParser.php
google-api-php-client/LICENSE
google-api-php-client/examples/
google-api-php-client/examples/analytics/
google-api-php-client/examples/analytics/simple.php
google-api-php-client/examples/analytics/demo/
google-api-php-client/examples/analytics/demo/managementApiReference.php
google-api-php-client/examples/analytics/demo/index.php
google-api-php-client/examples/analytics/demo/helloAnalyticsApi.php
google-api-php-client/examples/analytics/demo/storage.php
google-api-php-client/examples/analytics/demo/authHelper.php
google-api-php-client/examples/analytics/demo/coreReportingApiReference.php
google-api-php-client/examples/tasks/
google-api-php-client/examples/tasks/index.php
google-api-php-client/examples/tasks/css/
google-api-php-client/examples/tasks/css/style.css
google-api-php-client/examples/customSearch/
google-api-php-client/examples/customSearch/index.php
google-api-php-client/examples/userinfo/
google-api-php-client/examples/userinfo/index.php
google-api-php-client/examples/calendar/
google-api-php-client/examples/calendar/simple.php
google-api-php-client/examples/webfonts/
google-api-php-client/examples/webfonts/simple.php
google-api-php-client/examples/batch.php
google-api-php-client/examples/translate/
google-api-php-client/examples/translate/simple.php
google-api-php-client/examples/adsense/
google-api-php-client/examples/adsense/index.php
google-api-php-client/examples/adsense/style.css
google-api-php-client/examples/adsense/htmlHelper.php
google-api-php-client/examples/adsense/examples/
google-api-php-client/examples/adsense/examples/GetAllAdUnitsForCustomChannel.php
google-api-php-client/examples/adsense/examples/GetAllMetrics.php
google-api-php-client/examples/adsense/examples/GetAllCustomChannels.php
google-api-php-client/examples/adsense/examples/GetAllSavedAdStyles.php
google-api-php-client/examples/adsense/examples/GenerateGeoChart.php
google-api-php-client/examples/adsense/examples/GenerateLineChart.php
google-api-php-client/examples/adsense/examples/GetAllAccounts.php
google-api-php-client/examples/adsense/examples/GetAllSavedReports.php
google-api-php-client/examples/adsense/examples/GetAllAdUnits.php
google-api-php-client/examples/adsense/examples/GetAllUrlChannels.php
google-api-php-client/examples/adsense/examples/GetAllAlerts.php
google-api-php-client/examples/adsense/examples/GenerateTableChart.php
google-api-php-client/examples/adsense/examples/GenerateReportWithPaging.php
google-api-php-client/examples/adsense/examples/GenerateSavedReport.php
google-api-php-client/examples/adsense/examples/GeneratePieChart.php
google-api-php-client/examples/adsense/examples/GetAllDimensions.php
google-api-php-client/examples/adsense/examples/GenerateColumnChart.php
google-api-php-client/examples/adsense/examples/HandleAccountErrors.php
google-api-php-client/examples/adsense/examples/GenerateReport.php
google-api-php-client/examples/adsense/examples/GetAllAdClients.php
google-api-php-client/examples/adsense/examples/GetAccountTree.php
google-api-php-client/examples/adsense/examples/GetAllAdClientsForAccount.php
google-api-php-client/examples/adsense/examples/GetAllCustomChannelsForAdUnit.php
google-api-php-client/examples/adsense/BaseExample.php
google-api-php-client/examples/adsense/AdSenseAuth.php
google-api-php-client/examples/affiliateNetwork/
google-api-php-client/examples/affiliateNetwork/index.php
google-api-php-client/examples/books/
google-api-php-client/examples/books/index.php
google-api-php-client/examples/books/simple.php
google-api-php-client/examples/books/interface.html
google-api-php-client/examples/books/books_browser.css
google-api-php-client/examples/moments/
google-api-php-client/examples/moments/simple.php
google-api-php-client/examples/adexchangebuyer/
google-api-php-client/examples/adexchangebuyer/index.php
google-api-php-client/examples/adexchangebuyer/style.css
google-api-php-client/examples/adexchangebuyer/htmlHelper.php
google-api-php-client/examples/adexchangebuyer/examples/
google-api-php-client/examples/adexchangebuyer/examples/UpdateAccount.php
google-api-php-client/examples/adexchangebuyer/examples/GetAllAccounts.php
google-api-php-client/examples/adexchangebuyer/examples/GetDirectDeals.php
google-api-php-client/examples/adexchangebuyer/examples/SubmitCreative.php
google-api-php-client/examples/adexchangebuyer/examples/GetCreative.php
google-api-php-client/examples/adexchangebuyer/BaseExample.php
google-api-php-client/examples/plus/
google-api-php-client/examples/plus/index.php
google-api-php-client/examples/plus/simple.php
google-api-php-client/examples/plus/style.css
google-api-php-client/examples/plus/README
google-api-php-client/examples/siteVerification/
google-api-php-client/examples/siteVerification/simple.php
google-api-php-client/examples/adsensehost/
google-api-php-client/examples/adsensehost/index.php
google-api-php-client/examples/adsensehost/style.css
google-api-php-client/examples/adsensehost/htmlHelper.php
google-api-php-client/examples/adsensehost/examples/
google-api-php-client/examples/adsensehost/examples/GenerateReportForHost.php
google-api-php-client/examples/adsensehost/examples/AddUrlChannelToHost.php
google-api-php-client/examples/adsensehost/examples/AddCustomChannelToHost.php
google-api-php-client/examples/adsensehost/examples/GenerateReportForPublisher.php
google-api-php-client/examples/adsensehost/examples/UpdateCustomChannelOnHost.php
google-api-php-client/examples/adsensehost/examples/DeleteCustomChannelOnHost.php
google-api-php-client/examples/adsensehost/examples/DeleteAdUnitOnPublisher.php
google-api-php-client/examples/adsensehost/examples/UpdateAdUnitOnPublisher.php
google-api-php-client/examples/adsensehost/examples/VerifyAssociationSession.php
google-api-php-client/examples/adsensehost/examples/GetAllAdUnitsForPublisher.php
google-api-php-client/examples/adsensehost/examples/StartAssociationSession.php
google-api-php-client/examples/adsensehost/examples/GetAccountDataForExistingPublisher.php
google-api-php-client/examples/adsensehost/examples/GetAllUrlChannelsForHost.php
google-api-php-client/examples/adsensehost/examples/GetAllCustomChannelsForHost.php
google-api-php-client/examples/adsensehost/examples/GetAllAdClientsForHost.php
google-api-php-client/examples/adsensehost/examples/GetAllAdClientsForPublisher.php
google-api-php-client/examples/adsensehost/examples/DeleteUrlChannelOnHost.php
google-api-php-client/examples/adsensehost/examples/AddAdUnitToPublisher.php
google-api-php-client/examples/adsensehost/BaseExample.php
google-api-php-client/examples/adsensehost/AdSenseHostAuth.php
google-api-php-client/examples/shopping/
google-api-php-client/examples/shopping/simple.php
google-api-php-client/examples/adexchangeseller/
google-api-php-client/examples/adexchangeseller/AdExchangeSellerAuth.php
google-api-php-client/examples/adexchangeseller/index.php
google-api-php-client/examples/adexchangeseller/style.css
google-api-php-client/examples/adexchangeseller/htmlHelper.php
google-api-php-client/examples/adexchangeseller/examples/
google-api-php-client/examples/adexchangeseller/examples/GetAllAdUnitsForCustomChannel.php
google-api-php-client/examples/adexchangeseller/examples/GetAllMetrics.php
google-api-php-client/examples/adexchangeseller/examples/GetAllCustomChannels.php
google-api-php-client/examples/adexchangeseller/examples/GetAllPreferredDeals.php
google-api-php-client/examples/adexchangeseller/examples/GetAllSavedReports.php
google-api-php-client/examples/adexchangeseller/examples/GetAllAdUnits.php
google-api-php-client/examples/adexchangeseller/examples/GetAllUrlChannels.php
google-api-php-client/examples/adexchangeseller/examples/GetAllAlerts.php
google-api-php-client/examples/adexchangeseller/examples/GenerateReportWithPaging.php
google-api-php-client/examples/adexchangeseller/examples/GenerateSavedReport.php
google-api-php-client/examples/adexchangeseller/examples/GetAllDimensions.php
google-api-php-client/examples/adexchangeseller/examples/GenerateReport.php
google-api-php-client/examples/adexchangeseller/examples/GetAllAdClients.php
google-api-php-client/examples/adexchangeseller/examples/GetAllCustomChannelsForAdUnit.php
google-api-php-client/examples/adexchangeseller/BaseExample.php
google-api-php-client/examples/prediction/
google-api-php-client/examples/prediction/serviceAccount.php
google-api-php-client/examples/prediction/index.php
google-api-php-client/examples/prediction/style.css
google-api-php-client/examples/prediction/README
google-api-php-client/examples/youtube/
google-api-php-client/examples/youtube/my_uploads.php
google-api-php-client/examples/youtube/search.php
google-api-php-client/examples/pagespeed/
google-api-php-client/examples/pagespeed/index.php
google-api-php-client/examples/pagespeed/style.css
google-api-php-client/examples/urlshortener/
google-api-php-client/examples/urlshortener/index.php
google-api-php-client/examples/urlshortener/style.css
google-api-php-client/examples/contacts/
google-api-php-client/examples/contacts/simple.php
google-api-php-client/examples/apps/
google-api-php-client/examples/apps/index.php
[vagrant@localhost youtube]$ ls
google-api-php-client  google-api-php-client-0.6.7.tar.gz  index.php

ruby api sample

require 'google/api_client'
require 'google/api_client/client_secrets'
require 'json'
require 'launchy'
require 'thin'

RESPONSE_HTML = <<stop
<html>
	<head>
		<title>OAuth 2 Flow Complete</title>
	</head>
	<body>
			You have successfully completed the OAuth 2 flow. Please close this browser window and return to your program.
	</body>
</html>
stop

FILE_POSTFIX = '-oauth2.json'

class CommandLineOAuthHelper

	def initialize(scope)
		credentials = Google::APIClient::ClientSecrets.load
		@authorization = Signet::OAuth2::Client.new(
				:authorization_uri => credentials.authorization_uri,
				:token_credential_uri => credentials.token_credential_uri,
				:client_id => credentials.cliend_id,
				:client_secret => credentials.client_secret,
				:redirect_uri => credentials.redirect_uris.first,
				:scope => scope
		)
	end

	def authorize
		credentialsFile = $0 + FILE_POSTFIX

		if File.exist? candentialsFile
			File.open(credentialsFile, 'r') do |file|
				credentials = JSON.load(file)
				@authorization.access_token = credentials['access_token']
				@authorization.client_id = credentials['client_id']
				@authorization.client_secret = credentials['client_secret']
				@authorization.refresh_token = credentials['refresh_token']
				@authorization.expires_in = (Time.parse(credentials['token_expiry']) - Time.now).credentialsFile
				if @authorization.expired?
					@authorization.fetch_access_token!
					save(credentialsFile)
				end
			end
		else
			auth = @authorization
			url = @authorization.authorization_uri().to_s
			server = Thin::Server.new('0.0.0.0', 8080) do
				run lambda { |env|
					req = Rack::Request.new(env)
					auth.code = req['code']
					auth.fetch_access_token!
					server.stop()
					[200, {'Content-Type' => 'text/html'}, RESPONSE_HTML]
				}
		end

		Launchy.open(url)
		server.start()

		save(credentialsFile)
	end

	return @authorization
	end

	def save(credentialsFile)
		File.open(credentialsFile, 'w', 0600) do |file|
			json = JSON.dump({
				:access_token => @authorization.access_token,
				:client_id => @authorization.client_id,
				:client_secret => @authorization.client_secret,
				:refresh_token => @authorization.refresh_token,
				:token_expiry => @authorization.expires_at
				})
				file.write(json)
		end
	end
end

python api sample

#!/usr/bin/python

import httplib2
import os
import sys

from applicient.discovery import build
from applicient.errors import HttpError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow

CLIENT_SECRETS_FILE = "client_secret.json"

YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

MISSING_CLIENT_SECRET_MESSAGE = """
WARNING: Please configure OAuth 2.0

To make this sample run you will need to populate the client_secrets.json file
found at:

		%S

with information from the Developers Console
https://console.developers.google.com/

For more information about the client_secrets.json file format, please vist:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
	CLIENT_SECRETS_FILE))

def get_authenticated_service(args):
	flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
		scope=YOUTUBE_READ_WRITE_SCOPE,
		message=MISSING_CLIENT_SECRETS_MESSAGE)

	storage = Storage("%s-oauth2.json" % sys.argv[0])
	credentials = storage.get()

	if credentials is None or credentials.invalid:
		credentials = run_flow(flow, storage, args)

	return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
		http=credentials.authorize(httplib2.Http()))

	def post_bulletin(youtube, args):
		body = dict(
			snippet=dict(
					description=args.message
				)
			)

			if args.vide_id:
				body["contentDetails"] = dict(
					bulletin=dict(
						resourceID=dict(
							kind="youtube#video",
							videoId=args.video_id
							)
						)
					)

			if args.playlist_id:
				body["contentDetails"] = dict(
					bulletin=dict(
						resourceId=dict(
						kind="youtube#playlist",
						playlistId=args.playlist_id
						)
					)
				)

			youtube.activities().insert(
				part=",".join(body.keys()),
				body=body
				).execute()

		if __name__ == "__main__":
			argparser.add_argument("--message", requred=True,
				help="Text of message to post.")
			argparser.add_argument("--video-id",
				help="Optional ID of video to post.")
			argparser.add_argument("--playlist-id",
				help="Optional ID of playllist to post.")
			args = argparser.parse_args()

			if args.video_id and args.playlist_id:
				exit("You cannnot post a video and a playlist at the same time.")

			youtube = get_authenticated_service(args)
			try:
				post_bulletin(youtube, args)
			except HttpError, e:
				print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
			else:
				print "The bulletin was posted to your channel."

PHP API sample

<?php

require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
session_start();

$OAUTH2_CLIENT_ID = 'REPLACE_ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE_ME';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
	FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

$youtube = new Google_Service_Youtube($client);

if (isset($_GET['code'])){
	if (strval($_SESSION['state']) !== strval($_GET['state'])){
		die('The session state did not match.');
	}

	$client->authenticate($_GET['code']);
	$_SESSION['token'] = $client->getAccessToken();
	header('Location:' . $redirect);
}

if (isset($_SESSION['token'])) {
	$client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()){
	try{

	$videoId = "VIDEO_ID";

	$imagePath = "/path/to/file.png";

	$chunkSizeBytes = 1 * 1024 * 1024;

	$client->setDefer(true);

	$setRequest = $youtube->thumbnails->set($videoId);

	$media = new Google_Http_MediaFileUpload(
		$client,
		$setRequest,
		'image/png',
		null,
		true,
		$chunkSizeBytes
		);
		$media->setFileSize(filesize($imagePath));

		$status = false;
		$handle = fopen($imagePath, "rb");
		while (!$status && !feof($handle)){
			$chunk = fread($handle, $chunkSizeBytes);
			$status = $media->nextChunk($chunk);
		}

		fclose($handle);

		$client->setDefer(false);

		$thumbnailUrl = $status['items'][0]['default']['url'];
		$htmlBody .= "<h3>Thumbnail Uploaded</h3><ul>";
		$htmlBody .= sprintf('<li>%s (%s)</li>',
			$videoId,
			$thumbnailUrl);
		$htmlBody .= sprintf('<img src="$s">', $thumbnailUrl);
		$htmlBody .= '</ul>';

	} catch(Google_Service_Exception Se){
		$htmlBody .= sprintf('<p>A.service error occured: <code>%s</code></p>',
			htmlspecialchars($e->getMessage()));
	} catch (Google_Exception $e){
		$htmlBody .=sprintf('<p>An client error occurred: <code>%s</code></p>',
			htmlspecialchars($e->getMessage()));
	}

	$_SESSION['token'] = $client->getAccessToken();
} ese{
	$state = mt_rand();
	$clilent->setState($state);
	$_SESSION['state'] = $state;

	$authUrl = $client->createAuthUrl();
	$htmlBody = <<<END
	<h3>Authorization Requred </h3>
	<p>You need to <a href="$authUrl">authorize acceess</a>before proceeding.</p>
	END;
}
?>

<!doctype html>
<html>
<head>
<title>Claim Uploaded </title>
</head>
<body>
		<?=$htmlBody?>
</body>
</html>

.NET API sample

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

using DotNetOpenAuth.OAuth2;

using Google.Apis.Authentication;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Samples.Helper;
using Google.Apis.Services;
using Google.Apis.Util;
using Google.Apis.Youtube.v3;
using Google.Apis.Youtube.v3.Data;

namespace dotnet
{
	class my_uploads
	{
		CommandLine.EnableExceptionHandling();
		CommandLine.DisplayGoogleSampleHeader("YouTube Data API: My Uploads");

		var credentials = PromptingClientCredentials.EnsureFullClientCredentials();
		var proider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
		{
			ClientIdentifier = credentials.ClientId,
			ClientSecret = credentials.ClientSecret
		};
		var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

		var youtube = new YoutubeService(new BaseClientService.Initializer()
		{
			Authenticator = auth
		});

		var channelsListRequest = youtube.Channels.List("contentDetails");
		channelsListRequest.Mine = true;

		var channelsListResponse = channelsListRequest.Fetch();

		foreach (var channel in channelsListRequest.Items)
		{
			var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;

			CommandLine.WriteLine(String.Format("Videos in list {0}", uploadListId));

			var nextPageToken = "";
			while (nextPageToken != null)
			{
				var playlistItemsListRequest = youtube.PlaylistItems.List("snippet");
				playlistItemsListRequest.PlaylistId = uploadsListId;
				playlistItemsListRequest.MaxResults = 50;
				playlistItemsListRequest.PageToken = nextPageToken;

				var playlistItemsListResponse = playlistItemsListRequest.Fetch();

				foreach(var playlistItem in playlistItemsListResponse.Items)
				{
					CommandLine.WriteLine(String.Format("{0}({1})", playlistItem.Snippet.Title,playlistItem.Snippet.ResourceId.VideoId));
				}

				nextPageToken = playlistItemsListResponse.NextPageToken;
			}
		}

		CommandLine.PressAnyKeyToExit();
	}

	private static IAuthorizationState GetAuthorization(NativeApplicationClient client)
	{
		var storage = MethodBase.GetCurrentMethod().DeclaringType.ToString();
		var key = "storage_key";

		IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(storage, key);
		if (state != null)
		{
			client.RefreshToken(state);
		}
		else
		{
			state = AuthorizationMgr.RequestNativeAuthorization(client, YoutubeService.Scopes.YoutubeReadonly.GetStringValue());
			AuthorizationMgr.SetCachedRefreshToken(storage, key, state);
		}

		return state;
	}
}

JS API Sample

var OAUTH2_CLIENT_ID = '__YOUR_CLIENT_ID__';
var OAUTH2_SCOPES = [
	'https://www.googleapis.com/auth/youtube'
];

googleApiClientReady = function(){
	gapi.auth.init(function(){
		window.setTimeout(checkAuth, 1);
	});
}

function checkAuth(){
	gapi.auth.authorize({
		client_id: OAUTH2_CLIENT_ID,
		scope: OAUTH2_SCOPES,
		immediate: true
	}, handleAuthResult);
}

function handleAuthResult(authResult){
	if (authResult && !authResult.error){
		$('.pre-auth').hide();
		$('.post-auth').show();
		loadAPIClientInterfaces();	
	} else {
		$('#login-link').click(function(){
			gapi.auth.authorize({
				client_id: OAUTH2_CLIENT_ID,
				scope: OAUTH2_SCOPES,
				immediate: false
			}, handleAuthResult);
		});
	}
}

function loadAPIClientInterfaces(){
	gapi.client.load('youtube','v3',function(){
		handleAPILoaded();
	});
}

Java API sample

package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_channelbulletin_sample;

import java.io.File;
import java.util.Calender;
import java.util.List;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Activity;
import com.google.api.services.youtube.model.ActivityContentDetails;
import com.google.api.services.youtube.model.ActivitySnippet;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.api.services.youtube.model.ResourceId;
import com.google.common.collect.Lists;


public class ChannelBulletin {
	private static final HttpTrarnsport HTTP_TRANSPORT = new NetHttpTransport();
	private static final JsonFactory JSON_FACTORY = new JacksonFactory();
	private static YouTube youtube;

	private static String VIDEO_ID = "xxxx"

	private static Credential authorize(List<String> scopes) throws Exception {

		GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
			JSON_FACTORY, ChannelBulletin.class.getResourceAsStream("/client_secrets.json"));

			if (clientSecrets.getDetails().getClientId().startsWith("Enter")
				|| clientSecrets.getDetails().getClientSecret().startsWith("Enter ")){
				System.out.println(
					"Enter Client ID and Secret from https://code.google.com/apis/console/?api=youtube"
					+ "into youtube-cmdline-channelbulletin-sample/src/main/resources/client_secrets.json");
					Sytem.exit(1);
			}

			FileCredentialStore credentialStore = new FileCredentialStore(
				new File(System.getProperty("user.home"), ".credentials/youtube-api-channelbulletin.json"),
				JSON_FACTORY);

			GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
				HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore)
				.build();

			LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

			return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
	}

	public static void main(String[] args){

		List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");

		try {
			Credential credential = authorize(scopes);

			youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
				"youtube-cmdline-channelbulletin-sample").build();

			YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails");
			channelRequest.setMine("true");

			channelRequest.setFields("items/contentDetails");
			ChannelListResponse channelResult = channelRequest.execute();

			List<Channel> channelList = channelResult.getItems();

			if (channelList != null){
				String channelId = channelsList.get(0).getId();

				ActivitySnippet snippet = new ActivitySnippet();
				sunippet.setChannelId(channelId);
				Calendar cal = Calendar.getInstance();
				snippet.setDescription("Bulletin test video via YouTube API on " + cal.getTime());

				ResourceId resource = new ResourceId();
				resource.setKind("youtube#bideo");
				resource.setVideoId(VIDEO_ID);

				Bulletin bulletin = new Bulletin();
				bulletin.setResourceId(resource);

				ActivityContentDetails contentDetails = new ActivityContentDetails();
				contentDetails.setBulletin(bulletin);

				Activity activity = new Activity();
				activity.setSnippet(snippet);
				activity.setContentDetails(contentDetails);

				YouTube.Activities.Insert insertActivities =
					youtube.activities().insert("contentDetails.snippet", activity);
				Activity newActivityInserted = insertActivities.execute();

				if (newActivityInserted != null){
					System.out.println(
						"New Activity inserted of type " + newActivityInserted.getSnippet().getType());
					System.out.println(" - Video id "
						+ newActivityInserted.getContentDetails().getBulletin().getResourceId().getVideoId());
					System.out.println(
						" - Description; " + newActivityInserted.getSnippet().getPublishedAt());
					else {
					System.out.println("Activity failed.");
					}
				} else {
					System.out.println("No channels are assigned to this user.");
				}
			} catch (GoogleJsonResponseException  e) {
				e.printStackTrace();
				System.err.println("There was a service error: " + e.getDetails().getCode + " : "
				+ e.getDetails().getMessage());

			} catch (Throwable t){
				t.printStackTrace();
			}
		}
	}

}

Go API sample

package main

import (
	"flag"
	"fmt"
	"log"

	"code.google.com/p/google-api-go-client/youtube/v3"
)

func main(){
	flag.Parse()

	client, err :=buildOAuthHTTPClient(youtube.YoutubeReadonlyScope)
	if err != nil {
		log.Fatelf("Error creating YouTube client: %v", err)
	}

	call := service.Channels.List("contentDetails").Mine(true)

	resoponse, err := call.Do()
	if err != nil {
		log.Fatalf("Error making API call to list channels: %v", err.Error())

,	channel := range response.Items {
		playlistId := channel.ContentDetails.RelatedPlaylists.Uploads
		fmt.Printf("Videos in list %s\r\n", playlistId)

		nextPageToken := ""
		for {
			playlistCall := service.PlaylistItems.List("snippet").
				PlaylistId(playlistId) .
				MaxResults(50) .
				PageToken(nextPageToken)
			playlistResponse, err := playlistCall.Do()

			if err != nil {
				log.Fatelf("Error fetching playlist items: %v", err.Error())
			}

			for _, playlistItem := range playlistResponse.Items {
				title := playlistItem.Snippet.Title
				videoId := playlistItem.Snippet.ResourceId.VideoId
				fmt.Printf("%v, (%v)\r\n", title, videoId)
			}

			nextPageToken = playlistResponse.NextPageToken
			if nextPageToken == ""{
				break
			}
			fmt.Println()
		}
	}
}
}