Recherche avancée

Médias (1)

Mot : - Tags -/MediaSPIP 0.2

Autres articles (84)

  • Amélioration de la version de base

    13 septembre 2013

    Jolie sélection multiple
    Le plugin Chosen permet d’améliorer l’ergonomie des champs de sélection multiple. Voir les deux images suivantes pour comparer.
    Il suffit pour cela d’activer le plugin Chosen (Configuration générale du site > Gestion des plugins), puis de configurer le plugin (Les squelettes > Chosen) en activant l’utilisation de Chosen dans le site public et en spécifiant les éléments de formulaires à améliorer, par exemple select[multiple] pour les listes à sélection multiple (...)

  • Configuration spécifique pour PHP5

    4 février 2011, par

    PHP5 est obligatoire, vous pouvez l’installer en suivant ce tutoriel spécifique.
    Il est recommandé dans un premier temps de désactiver le safe_mode, cependant, s’il est correctement configuré et que les binaires nécessaires sont accessibles, MediaSPIP devrait fonctionner correctement avec le safe_mode activé.
    Modules spécifiques
    Il est nécessaire d’installer certains modules PHP spécifiques, via le gestionnaire de paquet de votre distribution ou manuellement : php5-mysql pour la connectivité avec la (...)

  • ANNEXE : Les plugins utilisés spécifiquement pour la ferme

    5 mars 2010, par

    Le site central/maître de la ferme a besoin d’utiliser plusieurs plugins supplémentaires vis à vis des canaux pour son bon fonctionnement. le plugin Gestion de la mutualisation ; le plugin inscription3 pour gérer les inscriptions et les demandes de création d’instance de mutualisation dès l’inscription des utilisateurs ; le plugin verifier qui fournit une API de vérification des champs (utilisé par inscription3) ; le plugin champs extras v2 nécessité par inscription3 (...)

Sur d’autres sites (4392)

  • How to adjust mpeg 2 ts start time with ffmpeg ?

    29 juin 2015, par Maxim Kornienko

    I’m writing simple HLS (Http Live Streaming) java server to live cast (really live, not on demand) screenshow + voice. I constantly get chunks of image frames and audio samples as input to my service and produce mpeg 2 ts files + m3u8 playlist web page as output. The workflow is the following :

    1. Collect (buffer) source video frames and audio for certain period of time
    2. Convert series of video frames to h.264 encoded video file
    3. Convert audio samples to mp3 audio file
    4. Merge them to .ts file with ffmpeg command

      ffmpeg -i audio.mp3 -i video.mp4 -f mpegts -c:a copy -c:v copy -vprofile main -level:v 4.0 -vbsf h264_mp4toannexb -flags -global_header segment.ts
    5. Publish several .ts files on m3u8 playlist.

    The problem is resulting playlist interrupts after first segment is played. VLC logs following error :

    freetype error: Breaking unbreakable line
    ts error: libdvbpsi (PSI decoder): TS discontinuity (received 0, expected 4) for PID 17
    ts error: libdvbpsi (PSI decoder): TS duplicate (received 0, expected 1) for PID 0
    ts error: libdvbpsi (PSI decoder): TS duplicate (received 0, expected 1) for PID 4096
    core error: ES_OUT_SET_(GROUP_)PCR is called too late (pts_delay increased to 1000 ms)
    core error: ES_OUT_RESET_PCR called
    core error: Could not convert timestamp 185529572000
    ts error: libdvbpsi (PSI decoder): TS discontinuity (received 0, expected 4) for PID 17
    ts error: libdvbpsi (PSI decoder): TS duplicate (received 0, expected 1) for PID 0
    ts error: libdvbpsi (PSI decoder): TS duplicate (received 0, expected 1) for PID 4096
    core error: ES_OUT_SET_(GROUP_)PCR is called too late (jitter of 8653 ms ignored)
    core error: Could not get display date for timestamp 0
    core error: Could not convert timestamp 185538017000
    core error: Could not convert timestamp 185538267000
    core error: Could not convert timestamp 185539295977
    ...

    I guess the reason is that start time of segments do not belong to one stream, but it’s impossible to concat and resegment (with ffmepg -f segment) whole stream once new chunk is added. Tried adding #EXT-X-DISCONTINUITY tag to playlist as suggested here but it didn’t help. When I ffprobe them I get :

    Input #0, mpegts, from '26.ts':
    Duration: 00:00:10.02, start: 1.876978, bitrate: 105 kb/s
    Program 1
    Metadata:
     service_name    : Service01
     service_provider: FFmpeg
    Stream #0:0[0x100]: Video: h264 (High) ([27][0][0][0] / 0x001B), yuv420p, 640x640, 4 fps, 4 tbr, 90k tbn, 8 tbc
    Stream #0:1[0x101]: Audio: mp3 ([3][0][0][0] / 0x0003), 48000 Hz, mono, s16p, 64 kb/s  

    Where start value in line Duration: 00:00:10.02, start: 1.876978, bitrate: 105 kb/s is more or less equal for all segments.
    When I check segments from available proven-to-work playlists (like http://vevoplaylist-live.hls.adaptive.level3.net/vevo/ch1/appleman.m3u8) they all have diffrenet start values for each segment, for example :

    Input #0, mpegts, from 'segm150518140104572-424570.ts':
    Duration: 00:00:06.17, start: 65884.808689, bitrate: 479 kb/s
    Program 257
    Stream #0:0[0x20]: Video: h264 (Constrained Baseline) ([27][0][0][0] / 0x001B), yuv420p, 320x180 [SAR 1:1 DAR 16:9], 30 fps, 29.97 tbr, 90k tbn, 60 tbc
    Stream #0:1[0x21]: Audio: aac (LC) ([15][0][0][0] / 0x000F), 44100 Hz, stereo, fltp, 115 kb/s
    Stream #0:2[0x22]: Data: timed_id3 (ID3  / 0x20334449)

    and the next after it

    Input #0, mpegts, from 'segm150518140104572-424571.ts':
    Duration: 00:00:06.22, start: 65890.814689, bitrate: 468 kb/s
    Program 257
    Stream #0:0[0x20]: Video: h264 (Constrained Baseline) ([27][0][0][0] / 0x001B), yuv420p, 320x180 [SAR 1:1 DAR 16:9], 30 fps, 29.97 tbr, 90k tbn, 60 tbc
    Stream #0:1[0x21]: Audio: aac (LC) ([15][0][0][0] / 0x000F), 44100 Hz, stereo, fltp, 124 kb/s
    Stream #0:2[0x22]: Data: timed_id3 (ID3  / 0x20334449)

    differ in the way that start time of segm150518140104572-424571.ts is equal to start time + duration of segm150518140104572-424570.ts.

    How could this start value be adjusted with ffmpeg ? Or maybe my whole aproach is wrong ? Unfortunately I couldn’t find on the internet working example of live (not on demand) video service implemented with ffmepg.

  • Google Analytics 4 and GDPR : Everything You Need to Know

    17 mai 2022, par Erin

    Four years have passed since the European General Data Protection Regulation (GDPR, also known as DSGVO in German, and RGPD in French) took effect.

    That’s ample time to get compliant, especially for an organisation as big and innovative as Google. Or is it ? 

    If you are wondering how GDPR affects Google Analytics 4 and what the compliance status is at present, here’s the lowdown. 

    Is Google Analytics 4 GDPR Compliant ?

    No. As of mid-2022, Google Analytics 4 (GA4) isn’t fully GDPR compliant. Despite adding extra privacy-focused features, GA4 still has murky status with the European regulators. After the invalidation of the Privacy Shield framework in 2020, Google is yet to regulate EU-US data protection. At present, the company doesn’t sufficiently protect EU citizens’ and residents’ data against US surveillance laws. This is a direct breach of GDPR.

    Google Analytics and GDPR : a Complex Relationship 

    European regulators have scrutinised Google since GDPR came into effect in 2018.

    While the company took steps to prepare for GDPR provisions, it didn’t fully comply with important regulations around user data storage, transfer and security.

    The relationship between Google and EU regulators got more heated after the Court of Justice of the European Union (CJEU) invalidated the Privacy Shield — a leeway Google used for EU-US data transfers. After 2020, GDPR litigation against Google followed. 

    This post summarises the main milestones in this story and explains the consequences for Google Analytics users. 

    Google Analytics and GDPR Timeline

    2018 : Google Analytics Meets GDPR 

    In 2018, the EU adopted the General Data Protection Regulation (GDPR) — a set of privacy and data security laws, covering all member states. Every business interacting with EU citizens and/or residents had to comply.

    GDPR harmonised data protection laws across member states and put down extra provisions for what constitutes sensitive personal information (or PII). Broadly, PII includes any data about the person’s :

    • Racial or ethnic origin 
    • Employment status 
    • Religious or political beliefs
    • State of health 
    • Genetic or biometric data 
    • Financial records (such as payment method data)
    • Address and phone numbers 

    Businesses were barred from collecting this information without explicit consent (and even with it in some cases). If collected, such sensitive information is also subject to strict requirements on how it should be stored, secured, transferred and used. 

    7 Main GDPR Principles Explained 

    Article 5 of the GDPR lays out seven main GDPR principles for personal data and privacy protection : 

    • Lawfulness, fairness and transparency — data must be obtained legally, collected with consent and in adherence to laws. 
    • Purpose limitation — all personal information must be collected for specified, explicit and legal purposes. 
    • Data minimisation — companies must collect only necessary and adequate data, aligned with the stated purpose. 
    • Accuracy — data accuracy must be ensured at all times. Companies must have mechanisms to erase or correct inaccurate data without delays. 
    • Storage limitation — data must be stored only for as long as the stated purpose suggests. Though there’s no upper time limit on data storage. 
    • Integrity and confidentiality (security) — companies must take measures to ensure secure data storage and prevent unlawful or unauthorised access to it. 
    • Accountability — companies must be able to demonstrate adherence to the above principles. 

    Google claimed to have taken steps to make all of their products GDPR compliant ahead of the deadline. But in practice, this wasn’t always the case.

    In March 2018, a group of publishers admonished Google for not providing them with enough tools for GDPR compliance :

    “[Y]ou refuse to provide publishers with any specific information about how you will collect, share and use the data. Placing the full burden of obtaining new consent on the publisher is untenable without providing the publisher with the specific information needed to provide sufficient transparency or to obtain the requisite specific, granular and informed consent under the GDPR.”

    The proposed Google Analytics GDPR consent form was hard to implement and lacked customisation options. In fact, Google “makes unilateral decisions” on how the collected data is stored and used. 

    Users had no way to learn about or control all intended uses of people’s data — which made compliance with the second clause impossible. 

    Unsurprisingly, Google was among the first companies to face a GDPR lawsuit (together with Facebook). 

    By 2019, French data regulator CNIL, successfully argued that Google wasn’t sufficiently disclosing its data collection across products — and hence in breach of GDPR. After a failed appeal, Google had to pay a €50 million fine and promise to do better. 

    2019 : Google Analytics 4 Announcement 

    Throughout 2019, Google rightfully attempted to resolve some of its GDPR shortcomings across all products, Google Universal Analytics (UA) included. 

    They added a more visible consent mechanism for online tracking and provided extra compliance tips for users to follow. In the background, Google also made tech changes to its data processing mechanism to get on the good side of regulations.

    Though Google addressed some of the issues, they missed others. A 2019 independent investigation found that Google real-time-bidding (RTB) ad auctions still used EU citizens’ and residents’ data without consent, thanks to a loophole called “Push Pages”. But they managed to quickly patch this up before the allegations had made it to court. 

    In November 2019, Google released a beta version of the new product version — Google Analytics 4, due to replace Universal Analytics. 

    GA4 came with a set of new privacy-focused features for ticking GDPR boxes such as :

    • Data deletion mechanism. Users can now request to surgically extract certain data from the Analytics servers via a new interface. 
    • Shorter data retention period. You can now shorten the default retention period to 2 months by default (instead of 14 months) or add a custom limit.  
    • IP Anonymisation. GA4 doesn’t log or store IP addresses by default. 

    Google Analytics also updated its data processing terms and made changes to its privacy policy

    Though Google made some progress, Google Analytics 4 still has many limitations — and isn’t GDPR compliant. 

    2020 : Privacy Shield Invalidation Ruling 

    As part of the 2018 GDPR preparations, Google named its Irish entity (Google Ireland Limited) as the “data controller” legally responsible for EEA and Swiss users’ information. 

    The company announcement says : 

    Google Analytics Statement on Privacy Shield Invalidation Ruling
    Source : Google

    Initially, Google assumed that this legal change would help them ensure GDPR compliance as “legally speaking” a European entity was set in charge of European data. 

    Practically, however, EEA consumers’ data was still primarily transferred and processed in the US — where most Google data centres are located. Until 2020, such cross-border data transfers were considered legal thanks to the Privacy Shield framework

    But in July 2020, The EU Court of Justice ruled that this framework doesn’t provide adequate data protection to digitally transmitted data against US surveillance laws. Hence, companies like Google can no longer use it. The Swiss Federal Data Protection and Information Commissioner (FDPIC) reached the same conclusion in September 2020. 

    The invalidation of the Privacy Shield framework put Google in a tough position.

     Article 14. f of the GDPR explicitly states : 

    “The controller (the company) that intends to carry out a transfer of personal data to a recipient (Analytics solution) in a third country or an international organisation must provide its users with information on the place of processing and storage of its data”.

    Invalidation of the Privacy Shield framework prohibited Google from moving data to the US. At the same time, GDPR provisions mandated that they must disclose proper data location. 

    But Google Analytics (like many other products) had no a mechanism for : 

    • Guaranteeing intra-EU data storage 
    • Selecting a designated regional storage location 
    • Informing users about data storage location or data transfers outside of the EU 

    And these factors made Google Analytics in direct breach of GDPR — a territory, where they remain as of 2022.

    2020-2022 : Google GDPR Breaches and Fines 

    The 2020 ruling opened Google to GDPR lawsuits from country-specific data regulators.

    Google Analytics in particular was under a heavy cease-fire. 

    • Sweden first fined Google for violating GDPR for no not fulfilling its obligations to request data delisting in 2020. 
    • France rejected Google Analytics 4 IP address anonymisation function as a sufficient measure for protecting cross-border data transfers. Even with it, US intelligence services can still access user IPs and other PII. France declared Google Analytics illegal and pressed a €150 million fine. 
    • Austria also found Google Analytics GDPR non-compliant and proclaimed the service as “illegal”. The authority now seeks a fine too. 

    The Dutch Data Protection Authority and  Norwegian Data Protection Authority also found Google Analytics guilty of a GDPR breach and seek to limit Google Analytics usage. 

    New privacy controls in Google Analytics 4 do not resolve the underlying issue — unregulated, non-consensual EU-US data transfer. 

    Google Analytics GDPR non-compliance effectively opens any website tracking or analysing European visitors to legal persecution.

    In fact, this is already happening. noyb, a European privacy-focused NGO, has already filed over 100 lawsuits against European websites using Google Analytics.

    2022 : Privacy Shield 2.0. Negotiations

    Google isn’t the only US company affected by the Privacy Shield framework invalidation. The ruling puts thousands of digital companies at risk of non-compliance.

    To settle the matter, US and EU authorities started “peace talks” in spring 2022.

    European Commission President Ursula von der Leyen said that they are working with the Biden administration on the new agreement that will “enable predictable and trustworthy data flows between the EU and US, safeguarding the privacy and civil liberties.” 

    However, it’s just the beginning of a lengthy negotiation process. The matter is far from being settled and contentious issues remain as we discussed on Twitter (come say hi !).

    For one, the US isn’t eager to modify its surveillance laws and is mostly willing to make them “proportional” to those in place in the EU. These modifications may still not satisfy CJEU — which has the power to block the agreement vetting or invalidate it once again. 

    While these matters are getting hashed out, Google Analytics users, collecting data about EU citizens and/or residents, remain on slippery grounds. As long as they use GA4, they can be subject to GDPR-related lawsuits. 

    To Sum It Up 

    • Google Analytics 4 and Google Universal Analytics are not GDPR compliant because of Privacy Shield invalidation in 2020. 
    • French and Austrian data watchdogs named Google Analytics operations “illegal”. Swedish, Dutch and Norwegian authorities also claim it’s in breach of GDPR. 
    • Any website using GA for collecting data about European citizens and/or residents can be taken to court for GDPR violations (which is already happening). 
    • Privacy Shield 2.0 Framework discussions to regulate EU-US data transfers have only begun and may take years. Even if accepted, the new framework(s) may once again be invalidated by local data regulators as has already happened in the past. 

    Time to Get a GDPR Compliant Google Analytics Alternative 

    Retaining 100% data ownership is the optimal path to GDPR compliance.

    By selecting a transparent web analytics solution that offers 100% data ownership, you can rest assured that no “behind the scenes” data collection, processing or transfers take place. 

    Unlike Google Analytics 4, Matomo offers all of the features you need to be GDPR compliant : 

    • Full data anonymisation 
    • Single-purpose data usage 
    • Easy consent and an opt-out mechanism 
    • First-party cookies usage by default 
    • Simple access to collect data 
    • Fast data removals 
    • EU-based data storage for Matomo Cloud (or storage in the country of your choice with Matomo On-Premise)

    Learn about your audiences in a privacy-centred way and protect your business against unnecessary legal exposure. 

    Start your 21-day free trial (no credit card required) to see how fully GDPR-compliant website analytics works ! 

  • ADD Image overlay to ffmpeg video stream

    1er juillet 2017, par Chris

    I am new to ffmpeg and want to add an HUD to the video stream, so a few questions.

    1. What file do I need to edit.
    2. What do I need to do to achieve this.

    Thanks in advance. Also I am VERY new to all of this, I will need instructions step by step

    I saw other questions saying to add this : ffmpeg -n -i video.mp4 -i logo.png -filter_complex "[0:v]setsar=sar=1[v];[v][1]blend=all_mode='overlay':all_opacity=0.7" -movflags +faststart tmb/video.mp4

    But I dont know where to put it, i entered it in the terminal and got this :

    pi@raspberrypi:~ $ ffmpeg -n -i video.mp4 -i logo.png -filter_complex "[0:v]setsar=sar=1[v];[v][1]blend=all_mode='overlay':all_opacity=0.7" -movflags +faststart tmb/video.mp4
    ffmpeg version N-86215-gb5228e4 Copyright (c) 2000-2017 the FFmpeg developers
     built with gcc 4.9.2 (Raspbian 4.9.2-10)
     configuration: --arch=armel --target-os=linux --enable-gpl --enable-libx264 --enable-nonfree --extra-libs=-ldl
     libavutil      55. 63.100 / 55. 63.100
     libavcodec     57. 96.101 / 57. 96.101
     libavformat    57. 72.101 / 57. 72.101
     libavdevice    57.  7.100 / 57.  7.100
     libavfilter     6. 90.100 /  6. 90.100
     libswscale      4.  7.101 /  4.  7.101
     libswresample   2.  8.100 /  2.  8.100
     libpostproc    54.  6.100 / 54.  6.100
    video.mp4: No such file or directory

    I dont understand what i am supposed to do with the video.mp4 ?

    HERE IS THE SCRIPT THAT SENDS THE VIDEO.

    import subprocess
    import shlex
    import re
    import os
    import time
    import urllib2
    import platform
    import json
    import sys
    import base64
    import random


    import argparse

    parser = argparse.ArgumentParser(description='robot control')
    parser.add_argument('camera_id')
    parser.add_argument('video_device_number', default=0, type=int)
    parser.add_argument('--kbps', default=450, type=int)
    parser.add_argument('--brightness', default=75, type=int, help='camera brightness')
    parser.add_argument('--contrast', default=75, type=int, help='camera contrast')
    parser.add_argument('--saturation', default=15, type=int, help='camera saturation')
    parser.add_argument('--rotate180', default=False, type=bool, help='rotate image 180 degrees')
    parser.add_argument('--env', default="prod")



    args = parser.parse_args()



    server = "runmyrobot.com"
    #server = "52.52.213.92"


    from socketIO_client import SocketIO, LoggingNamespace

    # enable raspicam driver in case a raspicam is being used
    os.system("sudo modprobe bcm2835-v4l2")


    if args.env == "dev":
       print "using dev port 8122"
       port = 8122
    elif args.env == "prod":
       print "using prod port 8022"
       port = 8022
    else:
       print "invalid environment"
       sys.exit(0)


    print "initializing socket io"
    print "server:", server
    print "port:", port
    socketIO = SocketIO(server, port, LoggingNamespace)
    print "finished initializing socket io"

    #ffmpeg -f qtkit -i 0 -f mpeg1video -b 400k -r 30 -s 320x240 http://52.8.81.124:8082/hello/320/240/


    def onHandleCameraCommand(*args):
       #thread.start_new_thread(handle_command, args)
       print args


    socketIO.on('command_to_camera', onHandleCameraCommand)


    def onHandleTakeSnapshotCommand(*args):
       print "taking snapshot"
       inputDeviceID = streamProcessDict['device_answer']
       snapShot(platform.system(), inputDeviceID)
       with open ("snapshot.jpg", 'rb') as f:
           data = f.read()
       print "emit"

       socketIO.emit('snapshot', {'image':base64.b64encode(data)})

    socketIO.on('take_snapshot_command', onHandleTakeSnapshotCommand)


    def randomSleep():
       """A short wait is good for quick recovery, but sometimes a longer delay is needed or it will just keep trying and failing short intervals, like because the system thinks the port is still in use and every retry makes the system think it's still in use. So, this has a high likelihood of picking a short interval, but will pick a long one sometimes."""

       timeToWait = random.choice((0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 5))
       print "sleeping", timeToWait
       time.sleep(timeToWait)



    def getVideoPort():


       url = 'http://%s/get_video_port/%s' % (server, cameraIDAnswer)


       for retryNumber in range(2000):
           try:
               print "GET", url
               response = urllib2.urlopen(url).read()
               break
           except:
               print "could not open url ", url
               time.sleep(2)

       return json.loads(response)['mpeg_stream_port']

    def getAudioPort():


       url = 'http://%s/get_audio_port/%s' % (server, cameraIDAnswer)


       for retryNumber in range(2000):
           try:
               print "GET", url
               response = urllib2.urlopen(url).read()
               break
           except:
               print "could not open url ", url
               time.sleep(2)

       return json.loads(response)['audio_stream_port']



    def runFfmpeg(commandLine):

       print commandLine
       ffmpegProcess = subprocess.Popen(shlex.split(commandLine))
       print "command started"

       return ffmpegProcess



    def handleDarwin(deviceNumber, videoPort, audioPort):


       p = subprocess.Popen(["ffmpeg", "-list_devices", "true", "-f", "qtkit", "-i", "dummy"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

       out, err = p.communicate()

       print err

       deviceAnswer = raw_input("Enter the number of the camera device for your robot from the list above: ")
       commandLine = 'ffmpeg -f qtkit -i %s -f mpeg1video -b 400k -r 30 -s 320x240 http://%s:%s/hello/320/240/' % (deviceAnswer, server, videoPort)

       process = runFfmpeg(commandLine)

       return {'process': process, 'device_answer': deviceAnswer}


    def handleLinux(deviceNumber, videoPort, audioPort):

       print "sleeping to give the camera time to start working"
       randomSleep()
       print "finished sleeping"


       #p = subprocess.Popen(["ffmpeg", "-list_devices", "true", "-f", "qtkit", "-i", "dummy"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
       #out, err = p.communicate()
       #print err


       os.system("v4l2-ctl -c brightness={brightness} -c contrast={contrast} -c saturation={saturation}".format(brightness=args.brightness,
                                                                                                                contrast=args.contrast,
                                                                                                                saturation=args.saturation))


       if deviceNumber is None:
           deviceAnswer = raw_input("Enter the number of the camera device for your robot: ")
       else:
           deviceAnswer = str(deviceNumber)


       #commandLine = '/usr/local/bin/ffmpeg -s 320x240 -f video4linux2 -i /dev/video%s -f mpeg1video -b 1k -r 20 http://runmyrobot.com:%s/hello/320/240/' % (deviceAnswer, videoPort)
       #commandLine = '/usr/local/bin/ffmpeg -s 640x480 -f video4linux2 -i /dev/video%s -f mpeg1video -b 150k -r 20 http://%s:%s/hello/640/480/' % (deviceAnswer, server, videoPort)
       # For new JSMpeg
       #commandLine = '/usr/local/bin/ffmpeg -f v4l2 -framerate 25 -video_size 640x480 -i /dev/video%s -f mpegts -codec:v mpeg1video -s 640x480 -b:v 250k -bf 0 http://%s:%s/hello/640/480/' % (deviceAnswer, server, videoPort) # ClawDaddy
       #commandLine = '/usr/local/bin/ffmpeg -s 1280x720 -f video4linux2 -i /dev/video%s -f mpeg1video -b 1k -r 20 http://runmyrobot.com:%s/hello/1280/720/' % (deviceAnswer, videoPort)


       if args.rotate180:
           rotationOption = "-vf transpose=2,transpose=2"
       else:
           rotationOption = ""

       # video with audio
       videoCommandLine = '/usr/local/bin/ffmpeg -f v4l2 -framerate 25 -video_size 640x480 -i /dev/video%s %s -f mpegts -codec:v mpeg1video -s 640x480 -b:v %dk -bf 0 -muxdelay 0.001 http://%s:%s/hello/640/480/' % (deviceAnswer, rotationOption, args.kbps, server, videoPort)
       audioCommandLine = '/usr/local/bin/ffmpeg -f alsa -ar 44100 -ac 1 -i hw:1 -f mpegts -codec:a mp2 -b:a 32k -muxdelay 0.001 http://%s:%s/hello/640/480/' % (server, audioPort)


       print videoCommandLine
       print audioCommandLine

       videoProcess = runFfmpeg(videoCommandLine)
       audioProcess = runFfmpeg(audioCommandLine)

       return {'video_process': videoProcess, 'audioProcess': audioProcess, 'device_answer': deviceAnswer}



    def handleWindows(deviceNumber, videoPort):

       p = subprocess.Popen(["ffmpeg", "-list_devices", "true", "-f", "dshow", "-i", "dummy"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)


       out, err = p.communicate()
       lines = err.split('\n')

       count = 0

       devices = []

       for line in lines:

           #if "]  \"" in line:
           #    print "line:", line

           m = re.search('.*\\"(.*)\\"', line)
           if m != None:
               #print line
               if m.group(1)[0:1] != '@':
                   print count, m.group(1)
                   devices.append(m.group(1))
                   count += 1


       if deviceNumber is None:
           deviceAnswer = raw_input("Enter the number of the camera device for your robot from the list above: ")
       else:
           deviceAnswer = str(deviceNumber)

       device = devices[int(deviceAnswer)]
       commandLine = 'ffmpeg -s 640x480 -f dshow -i video="%s" -f mpegts -codec:v mpeg1video -b 200k -r 20 http://%s:%s/hello/640/480/' % (device, server, videoPort)


       process = runFfmpeg(commandLine)

       return {'process': process, 'device_answer': device}



    def handleWindowsScreenCapture(deviceNumber, videoPort):

       p = subprocess.Popen(["ffmpeg", "-list_devices", "true", "-f", "dshow", "-i", "dummy"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)


       out, err = p.communicate()

       lines = err.split('\n')

       count = 0

       devices = []

       for line in lines:

           #if "]  \"" in line:
           #    print "line:", line

           m = re.search('.*\\"(.*)\\"', line)
           if m != None:
               #print line
               if m.group(1)[0:1] != '@':
                   print count, m.group(1)
                   devices.append(m.group(1))
                   count += 1


       if deviceNumber is None:
           deviceAnswer = raw_input("Enter the number of the camera device for your robot from the list above: ")
       else:
           deviceAnswer = str(deviceNumber)



       device = devices[int(deviceAnswer)]
       commandLine = 'ffmpeg -f dshow -i video="screen-capture-recorder" -vf "scale=640:480" -f mpeg1video -b 50k -r 20 http://%s:%s/hello/640/480/' % (server, videoPort)

       print "command line:", commandLine

       process = runFfmpeg(commandLine)

       return {'process': process, 'device_answer': device}




    def snapShot(operatingSystem, inputDeviceID, filename="snapshot.jpg"):    

       try:
           os.remove('snapshot.jpg')
       except:
           print "did not remove file"

       commandLineDict = {
           'Darwin': 'ffmpeg -y -f qtkit -i %s -vframes 1 %s' % (inputDeviceID, filename),
           'Linux': '/usr/local/bin/ffmpeg -y -f video4linux2 -i /dev/video%s -vframes 1 -q:v 1000 -vf scale=320:240 %s' % (inputDeviceID, filename),
           'Windows': 'ffmpeg -y -s 320x240 -f dshow -i video="%s" -vframes 1 %s' % (inputDeviceID, filename)}

       print commandLineDict[operatingSystem]
       os.system(commandLineDict[operatingSystem])



    def startVideoCapture():

       videoPort = getVideoPort()
       audioPort = getAudioPort()
       print "video port:", videoPort
       print "audio port:", audioPort

       #if len(sys.argv) >= 3:
       #    deviceNumber = sys.argv[2]
       #else:
       #    deviceNumber = None
       deviceNumber = args.video_device_number

       result = None
       if platform.system() == 'Darwin':
           result = handleDarwin(deviceNumber, videoPort, audioPort)
       elif platform.system() == 'Linux':
           result = handleLinux(deviceNumber, videoPort, audioPort)
       elif platform.system() == 'Windows':
           #result = handleWindowsScreenCapture(deviceNumber, videoPort)
           result = handleWindows(deviceNumber, videoPort, audioPort)
       else:
           print "unknown platform", platform.system()

       return result


    def timeInMilliseconds():
       return int(round(time.time() * 1000))



    def main():

       print "main"

       streamProcessDict = None


       twitterSnapCount = 0

       while True:



           socketIO.emit('send_video_status', {'send_video_process_exists': True,
                                               'camera_id':cameraIDAnswer})


           if streamProcessDict is not None:
               print "stopping previously running ffmpeg (needs to happen if this is not the first iteration)"
               streamProcessDict['process'].kill()

           print "starting process just to get device result" # this should be a separate function so you don't have to do this
           streamProcessDict = startVideoCapture()
           inputDeviceID = streamProcessDict['device_answer']
           print "stopping video capture"
           streamProcessDict['process'].kill()

           #print "sleeping"
           #time.sleep(3)
           #frameCount = int(round(time.time() * 1000))

           videoWithSnapshots = False
           while videoWithSnapshots:

               frameCount = timeInMilliseconds()

               print "taking single frame image"
               snapShot(platform.system(), inputDeviceID, filename="single_frame_image.jpg")

               with open ("single_frame_image.jpg", 'rb') as f:

                   # every so many frames, post a snapshot to twitter
                   #if frameCount % 450 == 0:
                   if frameCount % 6000 == 0:
                           data = f.read()
                           print "emit"
                           socketIO.emit('snapshot', {'frame_count':frameCount, 'image':base64.b64encode(data)})
                   data = f.read()

               print "emit"
               socketIO.emit('single_frame_image', {'frame_count':frameCount, 'image':base64.b64encode(data)})
               time.sleep(0)

               #frameCount += 1


           if False:
            if platform.system() != 'Windows':
               print "taking snapshot"
               snapShot(platform.system(), inputDeviceID)
               with open ("snapshot.jpg", 'rb') as f:
                   data = f.read()
               print "emit"

               # skip sending the first image because it's mostly black, maybe completely black
               #todo: should find out why this black image happens
               if twitterSnapCount > 0:
                   socketIO.emit('snapshot', {'image':base64.b64encode(data)})




           print "starting video capture"
           streamProcessDict = startVideoCapture()


           # This loop counts out a delay that occurs between twitter snapshots.
           # Every 50 seconds, it kills and restarts ffmpeg.
           # Every 40 seconds, it sends a signal to the server indicating status of processes.
           period = 2*60*60 # period in seconds between snaps
           for count in range(period):
               time.sleep(1)

               if count % 20 == 0:
                   socketIO.emit('send_video_status', {'send_video_process_exists': True,
                                                       'camera_id':cameraIDAnswer})

               if count % 40 == 30:
                   print "stopping video capture just in case it has reached a state where it's looping forever, not sending video, and not dying as a process, which can happen"
                   streamProcessDict['video_process'].kill()
                   streamProcessDict['audio_process'].kill()
                   time.sleep(1)

               if count % 80 == 75:
                   print "send status about this process and its child process ffmpeg"
                   ffmpegProcessExists = streamProcessDict['process'].poll() is None
                   socketIO.emit('send_video_status', {'send_video_process_exists': True,
                                                       'ffmpeg_process_exists': ffmpegProcessExists,
                                                       'camera_id':cameraIDAnswer})

               #if count % 190 == 180:
               #    print "reboot system in case the webcam is not working"
               #    os.system("sudo reboot")

               # if the video stream process dies, restart it
               if streamProcessDict['video_process'].poll() is not None or streamProcessDict['audio_process'].poll():
                   # wait before trying to start ffmpeg
                   print "ffmpeg process is dead, waiting before trying to restart"
                   randomSleep()
                   streamProcessDict = startVideoCapture()

           twitterSnapCount += 1

    if __name__ == "__main__":


       #if len(sys.argv) > 1:
       #    cameraIDAnswer = sys.argv[1]
       #else:
       #    cameraIDAnswer = raw_input("Enter the Camera ID for your robot, you can get it by pointing a browser to the runmyrobot server %s: " % server)

       cameraIDAnswer = args.camera_id


       main()

    ERROR :

    ffmpeg -n -f mpegts -i http://54.183.232.63:12221 -i logo.png -filter_complex "[0:v]setsar=sar=1[v];[v][1]blend=all_mode='overlay':all_opacity=0.7" -movflags +faststart tmb/video.mp4
    ffmpeg version N-86215-gb5228e4 Copyright (c) 2000-2017 the FFmpeg developers
     built with gcc 4.9.2 (Raspbian 4.9.2-10)
     configuration: --arch=armel --target-os=linux --enable-gpl --enable-libx264 --enable-nonfree --extra-libs=-ldl
     libavutil      55. 63.100 / 55. 63.100
     libavcodec     57. 96.101 / 57. 96.101
     libavformat    57. 72.101 / 57. 72.101
     libavdevice    57.  7.100 / 57.  7.100
     libavfilter     6. 90.100 /  6. 90.100
     libswscale      4.  7.101 /  4.  7.101
     libswresample   2.  8.100 /  2.  8.100
     libpostproc    54.  6.100 / 54.  6.100
    [mpegts @ 0x1a57390] Could not detect TS packet size, defaulting to non-FEC/DVHS
    http://54.183.232.63:12221: could not find codec parameters