Post

rtmp拉流直播

docker run -d –name srs -p 1935:1935 -p 1985:1985 -p 8080:8080 -p 8000:8000/udp ossrs/srs:latest

访问

http://localhost:8080/console/ng_index.html#/streams?port=1985&schema=http&host=localhost

推流

ffmpeg -re -stream_loop -1 -i 111.mp4 -c copy -f flv rtmp://localhost/live/livestream1

ffmpeg -re -stream_loop -1 -i 111.mp4 -c copy -f flv rtmp://localhost/live/livestream2

拉流

http://localhost:8080/live/livestream1.flv

http://localhost:8080/live/livestream2.flv

前端

npm install flv.js

npm install video.js

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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
<!--
 * @Author: yurongku
 * @Date: 2025-06-04 14:38:23
 * @LastEditors: yurongku
 * @LastEditTime: 2025-06-27 11:35:28
 * @FilePath: \wurenji_view\src\components\VideoPlayer.vue
-->
<template>
  <div class="video-player-container">
    <div v-if="isLoading" class="loading-overlay">
      <a-spin size="large" />
      <p>正在加载视频流...</p>
    </div>
    <div v-if="hasError && !isLoading" class="error-overlay">
      <a-icon type="exclamation-circle" style="font-size: 48px; color: #ff4d4f" />
      <p>视频流加载失败</p>
      <a-button @click="retryLoad" type="primary" size="small">重新加载</a-button>
    </div>
    <video
      ref="videoPlayer"
      class="video-js vjs-default-skin"
      preload="auto"
      width="600"
      height="338"
      playsinline
      webkit-playsinline
      x5-playsinline
      controls
      :style="{ opacity: isLoading || hasError ? 0.3 : 1 }"
    ></video>
  </div>
</template>

<script>
import videojs from "video.js";
import "video.js/dist/video-js.css";
import flvjs from "flv.js";

export default {
  name: "VideoPlayer",
  props: {
    src: {
      type: String,
      required: true,
    },
    // SRS服务器配置
    server: {
      type: String,
      default: "localhost",
    },
    port: {
      type: [String, Number],
      default: 8080,
    },
    vhost: {
      type: String,
      default: "__defaultVhost__",
    },
    app: {
      type: String,
      default: "live",
    },
    autostart: {
      type: Boolean,
      default: true,
    },
    // 最大重试次数
    maxRetryCount: {
      type: Number,
      default: 3,
    },
  },
  data() {
    return {
      player: null,
      flvPlayer: null,
      switchTimer: null,
      isLoading: false,
      hasError: false,
      retryCount: 0,
      retryTimer: null,
    };
  },
  mounted() {
    this.initPlayer();
  },
  beforeDestroy() {
    this.destroyPlayer();
  },
  watch: {
    src: {
      handler(newSrc, oldSrc) {
        if (newSrc !== oldSrc) {
          console.log('VideoPlayer src changed:', oldSrc, '->', newSrc);
          
          // 重置错误状态和重试计数
          this.hasError = false;
          this.retryCount = 0;
          
          // 防抖处理,避免频繁切换
          if (this.switchTimer) {
            clearTimeout(this.switchTimer);
          }
          
          this.switchTimer = setTimeout(() => {
            this.loadSource(newSrc);
            this.switchTimer = null;
          }, 200);
        }
      },
      immediate: false,
    },
  },
  methods: {
    initPlayer() {
      console.log('VideoPlayer initPlayer with src:', this.src);
      
      // 初始化Video.js播放器,但不设置源
      this.player = videojs(this.$refs.videoPlayer, {
        autoplay: false, // 由flv.js控制自动播放
        controls: true,
        preload: "none", // 不预加载,由flv.js处理
        fluid: true,
        responsive: true,
        techOrder: ['html5'],
        html5: {
          vhs: {
            overrideNative: true,
          }
        },
        controlBar: {
          pictureInPictureToggle: false,
          volumePanel: {
            inline: false
          }
        }
      });

      // 添加播放器事件监听
      this.player.on('error', (event) => {
        console.error('Video.js player error:', event);
        // 对于FLV流,忽略Video.js的错误,因为由flv.js处理
        if (this.src && this.src.includes('.flv')) {
          console.log('忽略Video.js错误,因为使用flv.js处理FLV流');
          return;
        }
        this.handlePlayerError();
      });

      this.player.on('loadstart', () => {
        console.log('Video.js loadstart');
      });

      this.player.on('canplay', () => {
        console.log('Video.js canplay');
        this.isLoading = false;
      });

      // 播放器准备好后再加载源
      this.player.ready(() => {
        console.log('Video.js ready');
        if (this.src) {
          this.loadSource(this.src);
        }
      });
    },

    loadSource(src) {
      if (!src) {
        console.log('VideoPlayer: 无视频源');
        this.hasError = true;
        this.isLoading = false;
        return;
      }

      console.log('VideoPlayer loadSource:', src);
      this.isLoading = true;
      this.hasError = false;

      // 清理重试定时器
      if (this.retryTimer) {
        clearTimeout(this.retryTimer);
        this.retryTimer = null;
      }

      // 暂停当前播放
      const videoElement = this.$refs.videoPlayer;
      if (videoElement && !videoElement.paused) {
        videoElement.pause();
      }

      // 销毁之前的FLV播放器实例
      if (this.flvPlayer) {
        try {
          this.flvPlayer.unload();
          this.flvPlayer.detachMediaElement();
          this.flvPlayer.destroy();
        } catch (error) {
          console.warn('销毁FLV播放器时出错:', error);
        }
        this.flvPlayer = null;
      }

      // 对于FLV流,不要清空src,直接设置flv播放器
      if (src.includes('.flv')) {
        console.log('检测到FLV流,直接使用flv.js处理');
        // 添加短暂延迟确保清理完成
        setTimeout(() => {
          this.setupFlvSource(src);
        }, 100);
      } else {
        // 对于其他格式,清空video源
        if (videoElement) {
          videoElement.src = '';
          videoElement.load(); // 重置video元素
        }
        
        // 添加短暂延迟确保清理完成
        setTimeout(() => {
          this.setupFlvSource(src);
        }, 100);
      }
    },

    setupFlvSource(src) {
      // 构建FLV流地址
      const flvUrl = this.buildFlvUrl(src);
      
      if (flvjs.isSupported()) {
        console.log('使用 flv.js 播放FLV流:', flvUrl);
        
        try {
          // 针对SRS直播流优化的配置
          this.flvPlayer = flvjs.createPlayer({
            type: 'flv',
            url: flvUrl,
            isLive: true,
            hasAudio: true,
            hasVideo: true,
            enableWorker: false,
            enableStashBuffer: false,
            stashInitialSize: 128,
            autoCleanupSourceBuffer: true,
          }, {
            enableWorker: false,
            lazyLoad: false,
            lazyLoadMaxDuration: 3 * 60,
            lazyLoadRecoverDuration: 30,
            deferLoadAfterSourceOpen: false,
            autoCleanupSourceBuffer: true,
            autoCleanupMaxBackwardDuration: 3 * 60,
            autoCleanupMinBackwardDuration: 2 * 60,
            statisticsInfoReportInterval: 600,
            fixAudioTimestampGap: true,
            accurateSeek: false,
            seekType: 'range',
            seekParamStart: 'bstart',
            seekParamEnd: 'bend',
            rangeLoadZeroStart: false,
            lazyLoadStartTime: 0,
            headers: undefined,
            customSeekHandler: undefined,
            reuseRedirectedURL: false,
            // SRS直播流相关配置
            cors: true,
            withCredentials: false,
            timeout: 30000,
            retryCount: 0, // 禁用flv.js内部重试,使用我们自己的重试机制
          });

          // 获取原生video元素(绕过Video.js)
          const videoElement = this.$refs.videoPlayer;
          this.flvPlayer.attachMediaElement(videoElement);
          
          // 监听FLV播放器事件
          this.flvPlayer.on(flvjs.Events.LOADING_COMPLETE, () => {
            console.log('FLV loading complete');
            this.isLoading = false;
            this.hasError = false;
            this.retryCount = 0; // 重置重试计数
          });

          this.flvPlayer.on(flvjs.Events.RECOVERED_EARLY_EOF, () => {
            console.log('FLV recovered from early EOF');
          });

          this.flvPlayer.on(flvjs.Events.MEDIA_INFO, (mediaInfo) => {
            console.log('FLV media info:', mediaInfo);
            this.isLoading = false;
          });

          this.flvPlayer.on(flvjs.Events.STATISTICS_INFO, (statisticsInfo) => {
            // 降低日志输出频率
            if (statisticsInfo.loaderType === 'fetch-stream-loader') {
              console.debug('FLV statistics:', {
                speed: statisticsInfo.speed,
                totalBytes: statisticsInfo.totalBytes
              });
            }
          });

          this.flvPlayer.on(flvjs.Events.ERROR, (errorType, errorDetail, errorInfo) => {
            console.error('FLV播放错误:', errorType, errorDetail, errorInfo);
            this.handleFlvError(errorType, errorDetail);
          });

          // 监听video元素的canplay事件
          videoElement.addEventListener('canplay', () => {
            console.log('Video element canplay');
            this.isLoading = false;
            this.hasError = false;
          }, { once: true });

          // 加载流
          this.flvPlayer.load();
          
          // 自动播放
          if (this.autostart) {
            // 等待一小段时间确保flv.js准备完成
            setTimeout(() => {
              videoElement.play().then(() => {
                console.log('FLV stream started playing');
              }).catch(err => {
                console.warn('自动播放失败:', err);
                // 自动播放失败不算错误,用户可手动播放
              });
            }, 500);
          }

        } catch (error) {
          console.error('创建FLV播放器失败:', error);
          this.handleFlvError('CREATE_ERROR', error.message);
        }

      } else {
        console.error('FLV.js not supported in this browser');
        this.hasError = true;
        this.isLoading = false;
        
        // 降级到直接使用video标签
        try {
          this.$refs.videoPlayer.src = flvUrl;
          this.$refs.videoPlayer.load();
        } catch (error) {
          console.error('降级播放失败:', error);
        }
      }
    },

    buildFlvUrl(streamName) {
      // 如果传入的已经是完整URL,直接使用
      if (streamName.startsWith('http')) {
        return streamName;
      }
      
      // 构建SRS FLV播放地址
      // 格式: http://server:port/live/stream.flv
      const baseUrl = `http://${this.server}:${this.port}`;
      const flvUrl = `${baseUrl}/${this.app}/${streamName}.flv`;
      
      console.log('构建的FLV URL:', flvUrl);
      return flvUrl;
    },

    handleFlvError(errorType, errorDetail) {
      console.log(`FLV错误类型: ${errorType}, 详情: ${errorDetail}`);
      
      this.hasError = true;
      this.isLoading = false;
      
      // 如果还有重试次数,进行自动重试
      if (this.retryCount < this.maxRetryCount) {
        this.retryCount++;
        const retryDelay = Math.min(1000 * Math.pow(2, this.retryCount - 1), 10000); // 指数退避,最大10秒
        
        console.log(`准备第${this.retryCount}次重试,延迟${retryDelay}ms`);
        
        this.retryTimer = setTimeout(() => {
          console.log(`执行第${this.retryCount}次重试`);
          this.loadSource(this.src);
        }, retryDelay);
      } else {
        console.log('已达到最大重试次数,停止重试');
      }
    },

    handlePlayerError() {
      console.error('Video.js播放器错误');
      this.hasError = true;
      this.isLoading = false;
    },

    // 手动重试
    retryLoad() {
      this.retryCount = 0;
      this.hasError = false;
      this.loadSource(this.src);
    },

    destroyPlayer() {
      // 清理定时器
      if (this.switchTimer) {
        clearTimeout(this.switchTimer);
        this.switchTimer = null;
      }
      
      if (this.retryTimer) {
        clearTimeout(this.retryTimer);
        this.retryTimer = null;
      }
      
      // 清理FLV播放器
      if (this.flvPlayer) {
        try {
          this.flvPlayer.unload();
          this.flvPlayer.detachMediaElement();
          this.flvPlayer.destroy();
        } catch (error) {
          console.warn('销毁FLV播放器时出错:', error);
        }
        this.flvPlayer = null;
      }
      
      // 清理Video.js播放器
      if (this.player) {
        try {
          this.player.dispose();
        } catch (error) {
          console.warn('销毁Video.js播放器时出错:', error);
        }
        this.player = null;
      }
    },

    // 手动播放方法
    play() {
      const videoElement = this.$refs.videoPlayer;
      if (videoElement) {
        return videoElement.play();
      }
      return Promise.reject('Video element not found');
    },

    // 手动暂停方法
    pause() {
      const videoElement = this.$refs.videoPlayer;
      if (videoElement) {
        videoElement.pause();
      }
    },

    // 获取播放状态
    isPaused() {
      const videoElement = this.$refs.videoPlayer;
      return videoElement ? videoElement.paused : true;
    },

    // 获取播放器状态
    getPlayerState() {
      return {
        isLoading: this.isLoading,
        hasError: this.hasError,
        retryCount: this.retryCount,
        isPaused: this.isPaused(),
        currentSrc: this.src
      };
    },
  },
};
</script>

<style scoped lang="scss">
.video-player-container {
  position: relative;
  height: 100%;
  width: 100%;
  background: #000;
  border-radius: 4px;
  overflow: hidden;

  .video-js {
    width: 100%;
    height: 100%;
    transition: opacity 0.3s ease;
  }

  .video-js .vjs-big-play-button {
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border-radius: 50%;
    width: 80px;
    height: 80px;
    line-height: 80px;
    font-size: 28px;
    border: 3px solid #fff;
    background: rgba(0, 0, 0, 0.6);
    
    &:hover {
      background: rgba(0, 0, 0, 0.8);
    }
  }

  .loading-overlay,
  .error-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 0.7);
    color: #fff;
    z-index: 10;
    
    p {
      margin: 12px 0;
      font-size: 14px;
    }
  }

  .loading-overlay {
    .ant-spin {
      /deep/ .ant-spin-dot {
        i {
          background-color: #1890ff;
        }
      }
    }
  }

  .error-overlay {
    .ant-btn {
      margin-top: 8px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .video-player-container {
    .video-js .vjs-big-play-button {
      width: 60px;
      height: 60px;
      line-height: 60px;
      font-size: 24px;
    }
    
    .loading-overlay,
    .error-overlay {
      p {
        font-size: 12px;
      }
    }
  }
}
</style>

This post is licensed under CC BY 4.0 by the author.