index.vue 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <template>
  2. <div class="wrap">
  3. <n-button
  4. type="success"
  5. @click.stop="handleVideoFrameByCanvas"
  6. >
  7. 选择视频
  8. <input
  9. ref="uploadRef"
  10. type="file"
  11. class="input-upload"
  12. @change="uploadChange"
  13. />
  14. </n-button>
  15. <span>
  16. 进度:{{ total ? ((total / videoDuration) * 100).toFixed() : 0 }}%
  17. </span>
  18. <div
  19. ref="listRef"
  20. class="frame-list"
  21. :style="{ height: height + 'px' }"
  22. >
  23. <div
  24. v-for="(item, index) in canvasList"
  25. :key="index"
  26. class="item"
  27. >
  28. <canvas ref="canvasListRef"></canvas>
  29. <div class="time">{{ item }}</div>
  30. </div>
  31. </div>
  32. </div>
  33. </template>
  34. <script lang="ts" setup>
  35. import { createVideo, formatDownTime2 } from '@/utils';
  36. import MP4Box from 'mp4box';
  37. import { nextTick, onMounted, ref } from 'vue';
  38. const uploadRef = ref<HTMLInputElement>();
  39. const total = ref(0);
  40. const videoDuration = ref(0);
  41. const height = ref(0);
  42. const canvasList = ref<any[]>([]);
  43. const canvasListRef = ref<HTMLCanvasElement[]>([]);
  44. const listRef = ref<HTMLDivElement>();
  45. function handleVideoFrameByWebcodec() {
  46. // const mp4url = 'mini-video.mp4';
  47. // const mp4url = '2024-02-25-10s.mp4';
  48. const mp4url = 'ddd.mp4';
  49. const mp4box = MP4Box.createFile();
  50. console.log(mp4box);
  51. // 这个是额外的处理方法,不需要关心里面的细节
  52. const getExtradata = () => {
  53. // 生成VideoDecoder.configure需要的description信息
  54. const entry = mp4box.moov.traks[0].mdia.minf.stbl.stsd.entries[0];
  55. console.log('mp4box', mp4box);
  56. console.log('entry', entry);
  57. const box = entry.avcC ?? entry.hvcC ?? entry.vpcC;
  58. console.log('box', box);
  59. if (box != null) {
  60. const stream = new MP4Box.DataStream(
  61. undefined,
  62. 0,
  63. MP4Box.DataStream.BIG_ENDIAN
  64. );
  65. box.write(stream);
  66. // slice()方法的作用是移除moov box的header信息
  67. return new Uint8Array(stream.buffer.slice(8));
  68. }
  69. };
  70. // 视频轨道,解码用
  71. let videoTrack: any = null;
  72. let videoDecoder: VideoDecoder | null = null;
  73. // 这个就是最终解码出来的视频画面序列文件
  74. const videoFrames = [];
  75. let nbSampleTotal = 0;
  76. let countSample = 0;
  77. mp4box.onReady = function (info) {
  78. // 记住视频轨道信息,onSamples匹配的时候需要
  79. videoTrack = info.videoTracks[0];
  80. if (videoTrack != null) {
  81. mp4box.setExtractionOptions(videoTrack.id, 'video', {
  82. nbSamples: 100,
  83. });
  84. }
  85. // 视频的宽度和高度
  86. const videoW = videoTrack.track_width;
  87. const videoH = videoTrack.track_height;
  88. const ctx = canvasRef.value!.getContext('2d')!;
  89. let flag = false;
  90. // 设置视频解码器
  91. videoDecoder = new VideoDecoder({
  92. output: (videoFrame) => {
  93. createImageBitmap(videoFrame).then((img) => {
  94. console.log(img, 22);
  95. if (!flag) {
  96. flag = true;
  97. canvasRef.value!.style.width = `${img.width / 3}px`;
  98. // canvasRef.value!.style.height = `${img.height}px`;
  99. // console.log(img.width, canvasRef.value!.style);
  100. }
  101. // ctx.drawImage(img, 0, 0);
  102. ctx.drawImage(img, 0, 0, img.width, img.height);
  103. videoFrames.push({
  104. img,
  105. duration: videoFrame.duration,
  106. timestamp: videoFrame.timestamp,
  107. });
  108. videoFrame.close();
  109. });
  110. },
  111. error: (err) => {
  112. console.error('videoDecoder错误:', err);
  113. },
  114. });
  115. nbSampleTotal = videoTrack.nb_samples;
  116. console.log(videoTrack, 22);
  117. videoDecoder.configure({
  118. codec: videoTrack.codec,
  119. codedWidth: videoW,
  120. codedHeight: videoH,
  121. description: getExtradata(),
  122. });
  123. mp4box.start();
  124. };
  125. mp4box.onSamples = function (trackId, ref, samples) {
  126. // samples其实就是采用数据了
  127. if (videoTrack.id === trackId) {
  128. mp4box.stop();
  129. countSample += samples.length;
  130. Object.keys(samples).forEach((key) => {
  131. const sample = samples[key];
  132. const type = sample.is_sync ? 'key' : 'delta';
  133. const chunk = new EncodedVideoChunk({
  134. type,
  135. timestamp: sample.cts,
  136. duration: sample.duration,
  137. data: sample.data,
  138. });
  139. videoDecoder.decode(chunk);
  140. });
  141. if (countSample === nbSampleTotal) {
  142. videoDecoder.flush();
  143. }
  144. }
  145. };
  146. // 获取视频的arraybuffer数据
  147. fetch(mp4url)
  148. .then((res) => res.arrayBuffer())
  149. .then((buffer) => {
  150. // 因为文件较小,所以直接一次性写入
  151. // 如果文件较大,则需要res.body.getReader()创建reader对象,每次读取一部分数据
  152. // reader.read().then(({ done, value })
  153. // @ts-ignore
  154. buffer.fileStart = 0;
  155. mp4box.appendBuffer(buffer);
  156. mp4box.flush();
  157. console.log('buffer', buffer);
  158. setTimeout(() => {
  159. console.log('videoFrames', videoFrames.length, videoFrames);
  160. }, 1000);
  161. });
  162. }
  163. function uploadChange() {
  164. canvasList.value = [];
  165. total.value = 0;
  166. videoDuration.value = 0;
  167. nextTick(() => {
  168. const file = uploadRef.value?.files?.[0];
  169. if (!file) return;
  170. const url = URL.createObjectURL(file);
  171. const videoEl = createVideo({
  172. appendChild: false,
  173. });
  174. videoEl.src = url;
  175. let videoWidth = 0;
  176. let videoHeight = 0;
  177. let currentTime = 0;
  178. function captureFrame() {
  179. const res = formatDownTime2({
  180. startTime: +new Date(),
  181. endTime: +new Date() + (currentTime + 1) * 1000,
  182. addZero: true,
  183. });
  184. let time = '';
  185. if (res.d) {
  186. time = `${res.d}天${res.h}:${res.m}:${res.s}`;
  187. } else {
  188. time = `${res.h}:${res.m}:${res.s}`;
  189. }
  190. canvasList.value.push(time);
  191. nextTick(() => {
  192. // 确保视频已足够加载以获取当前帧
  193. const canvas = canvasListRef.value[canvasListRef.value.length - 1];
  194. if (canvas) {
  195. const ctx = canvas.getContext('2d')!;
  196. canvas.width = videoWidth;
  197. canvas.height = videoHeight;
  198. ctx.drawImage(videoEl, 0, 0, videoWidth, videoHeight);
  199. total.value = total.value + 1;
  200. if (videoDuration.value > currentTime) {
  201. // 移动到下一帧
  202. videoEl.currentTime += 1;
  203. currentTime += 1;
  204. }
  205. }
  206. });
  207. }
  208. videoEl.onloadeddata = () => {
  209. videoWidth = videoEl.videoWidth;
  210. videoHeight = videoEl.videoHeight;
  211. currentTime = videoEl.currentTime;
  212. videoDuration.value = Math.ceil(videoEl.duration);
  213. captureFrame();
  214. };
  215. videoEl.onseeked = () => {
  216. if (currentTime < videoDuration.value) {
  217. captureFrame();
  218. }
  219. };
  220. });
  221. }
  222. function handleVideoFrameByCanvas() {
  223. uploadRef.value?.click();
  224. }
  225. function getHeight() {
  226. const h =
  227. document.documentElement.clientHeight -
  228. (listRef.value?.getBoundingClientRect().top || 0);
  229. height.value = h;
  230. }
  231. onMounted(() => {
  232. getHeight();
  233. });
  234. </script>
  235. <style lang="scss" scoped>
  236. .wrap {
  237. padding-top: 10px;
  238. padding-left: 30px;
  239. .input-upload {
  240. width: 0;
  241. height: 0;
  242. opacity: 0;
  243. }
  244. .frame-list {
  245. display: flex;
  246. overflow: scroll;
  247. align-content: baseline;
  248. flex-wrap: wrap;
  249. margin-top: 10px;
  250. @extend %customScrollbar;
  251. .item {
  252. position: relative;
  253. margin-right: 10px;
  254. margin-bottom: 10px;
  255. padding: 3px;
  256. width: 200px;
  257. height: fit-content;
  258. border: 1px solid black;
  259. border-radius: 5px;
  260. .time {
  261. position: absolute;
  262. right: 3px;
  263. bottom: 3px;
  264. padding: 3px 4px;
  265. border-radius: 3px;
  266. background-color: rgba($color: #000000, $alpha: 0.5);
  267. color: white;
  268. font-size: 13px;
  269. }
  270. canvas {
  271. width: 100%;
  272. height: 100%;
  273. }
  274. }
  275. }
  276. }
  277. </style>