encoder_utils.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. function fourColorsFrame(ctx, width, height, text) {
  2. const kYellow = "#FFFF00";
  3. const kRed = "#FF0000";
  4. const kBlue = "#0000FF";
  5. const kGreen = "#00FF00";
  6. ctx.fillStyle = kYellow;
  7. ctx.fillRect(0, 0, width / 2, height / 2);
  8. ctx.fillStyle = kRed;
  9. ctx.fillRect(width / 2, 0, width / 2, height / 2);
  10. ctx.fillStyle = kBlue;
  11. ctx.fillRect(0, height / 2, width / 2, height / 2);
  12. ctx.fillStyle = kGreen;
  13. ctx.fillRect(width / 2, height / 2, width / 2, height / 2);
  14. ctx.fillStyle = 'white';
  15. ctx.font = (height / 10) + 'px sans-serif';
  16. ctx.fillText(text, width / 2, height / 2);
  17. }
  18. // Paints |count| black dots on the |ctx|, so their presence can be validated
  19. // later. This is an analog of the most basic bar code.
  20. function putBlackDots(ctx, width, height, count) {
  21. ctx.fillStyle = 'black';
  22. const dot_size = 10;
  23. const step = dot_size * 3;
  24. for (let i = 1; i <= count; i++) {
  25. let x = i * step;
  26. let y = step * (x / width + 1);
  27. x %= width;
  28. ctx.fillRect(x, y, dot_size, dot_size);
  29. }
  30. }
  31. // Validates that frame has |count| black dots in predefined places.
  32. function validateBlackDots(frame, count) {
  33. const width = frame.displayWidth;
  34. const height = frame.displayHeight;
  35. let cnv = new OffscreenCanvas(width, height);
  36. var ctx = cnv.getContext('2d');
  37. ctx.drawImage(frame, 0, 0);
  38. const dot_size = 10;
  39. const step = dot_size * 3;
  40. for (let i = 1; i <= count; i++) {
  41. let x = i * step + dot_size / 2;
  42. let y = step * (x / width + 1) + dot_size / 2;
  43. x %= width;
  44. let rgba = ctx.getImageData(x, y, 1, 1).data;
  45. const tolerance = 40;
  46. if (rgba[0] > tolerance || rgba[1] > tolerance || rgba[2] > tolerance) {
  47. // The dot is too bright to be a black dot.
  48. return false;
  49. }
  50. }
  51. return true;
  52. }
  53. function createFrame(width, height, ts) {
  54. let text = ts.toString();
  55. let cnv = new OffscreenCanvas(width, height);
  56. var ctx = cnv.getContext('2d');
  57. fourColorsFrame(ctx, width, height, text);
  58. putBlackDots(ctx, width, height, ts);
  59. return new VideoFrame(cnv, { timestamp: ts });
  60. }