aboutsummaryrefslogtreecommitdiff
path: root/hsm-web/Client/src/CameraStream.vue
blob: 1defed29cea32ff31254164fb89bb10f8bd82e54 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<template>
  <h2>Camera Stream</h2>
  <button @click='toggleStream()' :disabled='disabled'>{{ command }}</button>
  <video ref='player' muted></video>
</template>

<script>
import axios              from 'axios'
import config             from './config'
import GstWebRTCAPI       from '@tomoxv/gstwebrtc-api/src/gstwebrtc-api.js'
import { useTemplateRef } from 'vue'

export default {
  data() {
    return {
      api:       null,
      listener:  null,
      player:    null,
      session:   null,

      command:   'Loading',
      disabled:  true,
      streaming: false
    }
  },
  mounted() {
    this.player = useTemplateRef('player')
    this.monitor()
    this.bindStream()
  },
  methods: {
    // Continuously checks if WebRTC stream is running on server
    async monitor() {
      const res = await axios.get(config.api + '/isStreaming')
  
      switch (res.status) {
      case 200:
        this.command   = res.data ? 'Stop' : 'Play'
        this.disabled  = false
        this.streaming = res.data
        break
      default:
        this.command   = 'Error'
        this.disabled  = true
        this.streaming = false
      }
  
      setTimeout(this.monitor, 1000)
    },

    // Toggles WebRTC stream
    async toggleStream() {
      const ep  = this.streaming ? '/stopStream' : '/startStream'
      const res = await axios.get(config.api + ep)

      if (res.status != 200) {
        console.error(res)
      }
    },

    // Binds WebRTC stream to video element
    bindStream() {
      this.api = new GstWebRTCAPI({
        meta:               { name: 'WebClient-' + Date.now() },
        signalingServerUrl: 'ws://' + window.location.hostname + ':8443'
      })

      this.listener = {
        producerAdded: (producer) => {
          console.log("Producer added", producer)
  
          this.session = this.api.createConsumerSession(producer.id)
          this.session.addEventListener('streamsChanged', () => {
            if (this.session.streams.length > 0) {
              this.player.srcObject = this.session.streams[0]
              this.player.play()
            }
          })
  
          this.session.connect()
        },
  
        producerRemoved: (producer) => {
          console.log("Producer removed", producer)
  
          this.player.pause()
          this.player.srcObject = null
          this.session          = null
        }
      }
  
      this.api.registerProducersListener(this.listener)
    }
  }
}
</script>

<style>
video {
  height: 360px;
  width:  480px;
}
</style>