You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

505 lines
17KB

  1. /*
  2. * MOV, 3GP, MP4 muxer RTP hinting
  3. * Copyright (c) 2010 Martin Storsjo
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "movenc.h"
  22. #include "libavutil/intreadwrite.h"
  23. int ff_mov_init_hinting(AVFormatContext *s, int index, int src_index)
  24. {
  25. MOVMuxContext *mov = s->priv_data;
  26. MOVTrack *track = &mov->tracks[index];
  27. MOVTrack *src_track = &mov->tracks[src_index];
  28. AVStream *src_st = s->streams[src_index];
  29. int ret = AVERROR(ENOMEM);
  30. AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
  31. track->tag = MKTAG('r','t','p',' ');
  32. track->src_track = src_index;
  33. if (!rtp_format) {
  34. ret = AVERROR(ENOENT);
  35. goto fail;
  36. }
  37. track->enc = avcodec_alloc_context();
  38. if (!track->enc)
  39. goto fail;
  40. track->enc->codec_type = AVMEDIA_TYPE_DATA;
  41. track->enc->codec_tag = track->tag;
  42. track->rtp_ctx = avformat_alloc_context();
  43. if (!track->rtp_ctx)
  44. goto fail;
  45. track->rtp_ctx->oformat = rtp_format;
  46. if (!av_new_stream(track->rtp_ctx, 0))
  47. goto fail;
  48. /* Copy stream parameters */
  49. track->rtp_ctx->streams[0]->sample_aspect_ratio =
  50. src_st->sample_aspect_ratio;
  51. /* Remove the allocated codec context, link to the original one
  52. * instead, to give the rtp muxer access to codec parameters. */
  53. av_free(track->rtp_ctx->streams[0]->codec);
  54. track->rtp_ctx->streams[0]->codec = src_st->codec;
  55. if ((ret = url_open_dyn_packet_buf(&track->rtp_ctx->pb,
  56. RTP_MAX_PACKET_SIZE)) < 0)
  57. goto fail;
  58. ret = av_write_header(track->rtp_ctx);
  59. if (ret)
  60. goto fail;
  61. /* Copy the RTP AVStream timebase back to the hint AVStream */
  62. track->timescale = track->rtp_ctx->streams[0]->time_base.den;
  63. /* Mark the hinted track that packets written to it should be
  64. * sent to this track for hinting. */
  65. src_track->hint_track = index;
  66. return 0;
  67. fail:
  68. av_log(s, AV_LOG_WARNING,
  69. "Unable to initialize hinting of stream %d\n", src_index);
  70. if (track->rtp_ctx && track->rtp_ctx->pb) {
  71. uint8_t *buf;
  72. url_close_dyn_buf(track->rtp_ctx->pb, &buf);
  73. av_free(buf);
  74. }
  75. if (track->rtp_ctx && track->rtp_ctx->streams[0]) {
  76. av_metadata_free(&track->rtp_ctx->streams[0]->metadata);
  77. av_free(track->rtp_ctx->streams[0]);
  78. }
  79. if (track->rtp_ctx) {
  80. av_metadata_free(&track->rtp_ctx->metadata);
  81. av_free(track->rtp_ctx->priv_data);
  82. av_freep(&track->rtp_ctx);
  83. }
  84. av_freep(&track->enc);
  85. /* Set a default timescale, to avoid crashes in dump_format */
  86. track->timescale = 90000;
  87. return ret;
  88. }
  89. /**
  90. * Remove the first sample from the sample queue.
  91. */
  92. static void sample_queue_pop(HintSampleQueue *queue)
  93. {
  94. if (queue->len <= 0)
  95. return;
  96. if (queue->samples[0].own_data)
  97. av_free(queue->samples[0].data);
  98. queue->len--;
  99. memmove(queue->samples, queue->samples + 1, sizeof(HintSample)*queue->len);
  100. }
  101. /**
  102. * Empty the sample queue, releasing all memory.
  103. */
  104. static void sample_queue_free(HintSampleQueue *queue)
  105. {
  106. int i;
  107. for (i = 0; i < queue->len; i++)
  108. if (queue->samples[i].own_data)
  109. av_free(queue->samples[i].data);
  110. av_freep(&queue->samples);
  111. queue->len = 0;
  112. queue->size = 0;
  113. }
  114. /**
  115. * Add a reference to the sample data to the sample queue. The data is
  116. * not copied. sample_queue_retain should be called before pkt->data
  117. * is reused/freed.
  118. */
  119. static void sample_queue_push(HintSampleQueue *queue, AVPacket *pkt, int sample)
  120. {
  121. /* No need to keep track of smaller samples, since describing them
  122. * with immediates is more efficient. */
  123. if (pkt->size <= 14)
  124. return;
  125. if (!queue->samples || queue->len >= queue->size) {
  126. HintSample* samples;
  127. queue->size += 10;
  128. samples = av_realloc(queue->samples, sizeof(HintSample)*queue->size);
  129. if (!samples)
  130. return;
  131. queue->samples = samples;
  132. }
  133. queue->samples[queue->len].data = pkt->data;
  134. queue->samples[queue->len].size = pkt->size;
  135. queue->samples[queue->len].sample_number = sample;
  136. queue->samples[queue->len].offset = 0;
  137. queue->samples[queue->len].own_data = 0;
  138. queue->len++;
  139. }
  140. /**
  141. * Make local copies of all referenced sample data in the queue.
  142. */
  143. static void sample_queue_retain(HintSampleQueue *queue)
  144. {
  145. int i;
  146. for (i = 0; i < queue->len; ) {
  147. HintSample *sample = &queue->samples[i];
  148. if (!sample->own_data) {
  149. uint8_t* ptr = av_malloc(sample->size);
  150. if (!ptr) {
  151. /* Unable to allocate memory for this one, remove it */
  152. memmove(queue->samples + i, queue->samples + i + 1,
  153. sizeof(HintSample)*(queue->len - i - 1));
  154. queue->len--;
  155. continue;
  156. }
  157. memcpy(ptr, sample->data, sample->size);
  158. sample->data = ptr;
  159. sample->own_data = 1;
  160. }
  161. i++;
  162. }
  163. }
  164. /**
  165. * Find matches of needle[n_pos ->] within haystack. If a sufficiently
  166. * large match is found, matching bytes before n_pos are included
  167. * in the match, too (within the limits of the arrays).
  168. *
  169. * @param haystack buffer that may contain parts of needle
  170. * @param h_len length of the haystack buffer
  171. * @param needle buffer containing source data that have been used to
  172. * construct haystack
  173. * @param n_pos start position in needle used for looking for matches
  174. * @param n_len length of the needle buffer
  175. * @param match_h_offset_ptr offset of the first matching byte within haystack
  176. * @param match_n_offset_ptr offset of the first matching byte within needle
  177. * @param match_len_ptr length of the matched segment
  178. * @return 0 if a match was found, < 0 if no match was found
  179. */
  180. static int match_segments(const uint8_t *haystack, int h_len,
  181. const uint8_t *needle, int n_pos, int n_len,
  182. int *match_h_offset_ptr, int *match_n_offset_ptr,
  183. int *match_len_ptr)
  184. {
  185. int h_pos;
  186. for (h_pos = 0; h_pos < h_len; h_pos++) {
  187. int match_len = 0;
  188. int match_h_pos, match_n_pos;
  189. /* Check how many bytes match at needle[n_pos] and haystack[h_pos] */
  190. while (h_pos + match_len < h_len && n_pos + match_len < n_len &&
  191. needle[n_pos + match_len] == haystack[h_pos + match_len])
  192. match_len++;
  193. if (match_len <= 8)
  194. continue;
  195. /* If a sufficiently large match was found, try to expand
  196. * the matched segment backwards. */
  197. match_h_pos = h_pos;
  198. match_n_pos = n_pos;
  199. while (match_n_pos > 0 && match_h_pos > 0 &&
  200. needle[match_n_pos - 1] == haystack[match_h_pos - 1]) {
  201. match_n_pos--;
  202. match_h_pos--;
  203. match_len++;
  204. }
  205. if (match_len <= 14)
  206. continue;
  207. *match_h_offset_ptr = match_h_pos;
  208. *match_n_offset_ptr = match_n_pos;
  209. *match_len_ptr = match_len;
  210. return 0;
  211. }
  212. return -1;
  213. }
  214. /**
  215. * Look for segments in samples in the sample queue matching the data
  216. * in ptr. Samples not matching are removed from the queue. If a match
  217. * is found, the next time it will look for matches starting from the
  218. * end of the previous matched segment.
  219. *
  220. * @param data data to find matches for in the sample queue
  221. * @param len length of the data buffer
  222. * @param queue samples used for looking for matching segments
  223. * @param pos the offset in data of the matched segment
  224. * @param match_sample the number of the sample that contained the match
  225. * @param match_offset the offset of the matched segment within the sample
  226. * @param match_len the length of the matched segment
  227. * @return 0 if a match was found, < 0 if no match was found
  228. */
  229. static int find_sample_match(const uint8_t *data, int len,
  230. HintSampleQueue *queue, int *pos,
  231. int *match_sample, int *match_offset,
  232. int *match_len)
  233. {
  234. while (queue->len > 0) {
  235. HintSample *sample = &queue->samples[0];
  236. /* If looking for matches in a new sample, skip the first 5 bytes,
  237. * since they often may be modified/removed in the output packet. */
  238. if (sample->offset == 0 && sample->size > 5)
  239. sample->offset = 5;
  240. if (match_segments(data, len, sample->data, sample->offset,
  241. sample->size, pos, match_offset, match_len) == 0) {
  242. *match_sample = sample->sample_number;
  243. /* Next time, look for matches at this offset, with a little
  244. * margin to this match. */
  245. sample->offset = *match_offset + *match_len + 5;
  246. if (sample->offset + 10 >= sample->size)
  247. sample_queue_pop(queue); /* Not enough useful data left */
  248. return 0;
  249. }
  250. if (sample->offset < 10 && sample->size > 20) {
  251. /* No match found from the start of the sample,
  252. * try from the middle of the sample instead. */
  253. sample->offset = sample->size/2;
  254. } else {
  255. /* No match for this sample, remove it */
  256. sample_queue_pop(queue);
  257. }
  258. }
  259. return -1;
  260. }
  261. static void output_immediate(const uint8_t *data, int size,
  262. ByteIOContext *out, int *entries)
  263. {
  264. while (size > 0) {
  265. int len = size;
  266. if (len > 14)
  267. len = 14;
  268. put_byte(out, 1); /* immediate constructor */
  269. put_byte(out, len); /* amount of valid data */
  270. put_buffer(out, data, len);
  271. data += len;
  272. size -= len;
  273. for (; len < 14; len++)
  274. put_byte(out, 0);
  275. (*entries)++;
  276. }
  277. }
  278. static void output_match(ByteIOContext *out, int match_sample,
  279. int match_offset, int match_len, int *entries)
  280. {
  281. put_byte(out, 2); /* sample constructor */
  282. put_byte(out, 0); /* track reference */
  283. put_be16(out, match_len);
  284. put_be32(out, match_sample);
  285. put_be32(out, match_offset);
  286. put_be16(out, 1); /* bytes per block */
  287. put_be16(out, 1); /* samples per block */
  288. (*entries)++;
  289. }
  290. static void describe_payload(const uint8_t *data, int size,
  291. ByteIOContext *out, int *entries,
  292. HintSampleQueue *queue)
  293. {
  294. /* Describe the payload using different constructors */
  295. while (size > 0) {
  296. int match_sample, match_offset, match_len, pos;
  297. if (find_sample_match(data, size, queue, &pos, &match_sample,
  298. &match_offset, &match_len) < 0)
  299. break;
  300. output_immediate(data, pos, out, entries);
  301. data += pos;
  302. size -= pos;
  303. output_match(out, match_sample, match_offset, match_len, entries);
  304. data += match_len;
  305. size -= match_len;
  306. }
  307. output_immediate(data, size, out, entries);
  308. }
  309. /**
  310. * Write an RTP hint (that may contain one or more RTP packets)
  311. * for the packets in data. data contains one or more packets with a
  312. * BE32 size header.
  313. *
  314. * @param out buffer where the hints are written
  315. * @param data buffer containing RTP packets
  316. * @param size the size of the data buffer
  317. * @param trk the MOVTrack for the hint track
  318. * @param pts pointer where the timestamp for the written RTP hint is stored
  319. * @return the number of RTP packets in the written hint
  320. */
  321. static int write_hint_packets(ByteIOContext *out, const uint8_t *data,
  322. int size, MOVTrack *trk, int64_t *pts)
  323. {
  324. int64_t curpos;
  325. int64_t count_pos, entries_pos;
  326. int count = 0, entries;
  327. count_pos = url_ftell(out);
  328. /* RTPsample header */
  329. put_be16(out, 0); /* packet count */
  330. put_be16(out, 0); /* reserved */
  331. while (size > 4) {
  332. uint32_t packet_len = AV_RB32(data);
  333. uint16_t seq;
  334. uint32_t ts;
  335. data += 4;
  336. size -= 4;
  337. if (packet_len > size || packet_len <= 12)
  338. break;
  339. if (data[1] >= 200 && data[1] <= 204) {
  340. /* RTCP packet, just skip */
  341. data += packet_len;
  342. size -= packet_len;
  343. continue;
  344. }
  345. if (packet_len > trk->max_packet_size)
  346. trk->max_packet_size = packet_len;
  347. seq = AV_RB16(&data[2]);
  348. ts = AV_RB32(&data[4]);
  349. if (trk->prev_rtp_ts == 0)
  350. trk->prev_rtp_ts = ts;
  351. /* Unwrap the 32-bit RTP timestamp that wraps around often
  352. * into a not (as often) wrapping 64-bit timestamp. */
  353. trk->cur_rtp_ts_unwrapped += (int32_t) (ts - trk->prev_rtp_ts);
  354. trk->prev_rtp_ts = ts;
  355. if (*pts == AV_NOPTS_VALUE)
  356. *pts = trk->cur_rtp_ts_unwrapped;
  357. count++;
  358. /* RTPpacket header */
  359. put_be32(out, 0); /* relative_time */
  360. put_buffer(out, data, 2); /* RTP header */
  361. put_be16(out, seq); /* RTPsequenceseed */
  362. put_be16(out, 0); /* reserved + flags */
  363. entries_pos = url_ftell(out);
  364. put_be16(out, 0); /* entry count */
  365. data += 12;
  366. size -= 12;
  367. packet_len -= 12;
  368. entries = 0;
  369. /* Write one or more constructors describing the payload data */
  370. describe_payload(data, packet_len, out, &entries, &trk->sample_queue);
  371. data += packet_len;
  372. size -= packet_len;
  373. curpos = url_ftell(out);
  374. url_fseek(out, entries_pos, SEEK_SET);
  375. put_be16(out, entries);
  376. url_fseek(out, curpos, SEEK_SET);
  377. }
  378. curpos = url_ftell(out);
  379. url_fseek(out, count_pos, SEEK_SET);
  380. put_be16(out, count);
  381. url_fseek(out, curpos, SEEK_SET);
  382. return count;
  383. }
  384. int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt,
  385. int track_index, int sample)
  386. {
  387. MOVMuxContext *mov = s->priv_data;
  388. MOVTrack *trk = &mov->tracks[track_index];
  389. AVFormatContext *rtp_ctx = trk->rtp_ctx;
  390. uint8_t *buf = NULL;
  391. int size;
  392. ByteIOContext *hintbuf = NULL;
  393. AVPacket hint_pkt;
  394. AVPacket local_pkt;
  395. int ret = 0, count;
  396. if (!rtp_ctx)
  397. return AVERROR(ENOENT);
  398. if (!rtp_ctx->pb)
  399. return AVERROR(ENOMEM);
  400. sample_queue_push(&trk->sample_queue, pkt, sample);
  401. /* Feed the packet to the RTP muxer */
  402. local_pkt = *pkt;
  403. local_pkt.stream_index = 0;
  404. local_pkt.pts = av_rescale_q(pkt->pts,
  405. s->streams[pkt->stream_index]->time_base,
  406. rtp_ctx->streams[0]->time_base);
  407. local_pkt.dts = av_rescale_q(pkt->dts,
  408. s->streams[pkt->stream_index]->time_base,
  409. rtp_ctx->streams[0]->time_base);
  410. av_write_frame(rtp_ctx, &local_pkt);
  411. /* Fetch the output from the RTP muxer, open a new output buffer
  412. * for next time. */
  413. size = url_close_dyn_buf(rtp_ctx->pb, &buf);
  414. if ((ret = url_open_dyn_packet_buf(&rtp_ctx->pb,
  415. RTP_MAX_PACKET_SIZE)) < 0)
  416. goto done;
  417. if (size <= 0)
  418. goto done;
  419. /* Open a buffer for writing the hint */
  420. if ((ret = url_open_dyn_buf(&hintbuf)) < 0)
  421. goto done;
  422. av_init_packet(&hint_pkt);
  423. count = write_hint_packets(hintbuf, buf, size, trk, &hint_pkt.dts);
  424. av_freep(&buf);
  425. /* Write the hint data into the hint track */
  426. hint_pkt.size = size = url_close_dyn_buf(hintbuf, &buf);
  427. hint_pkt.data = buf;
  428. hint_pkt.pts = hint_pkt.dts;
  429. hint_pkt.stream_index = track_index;
  430. if (pkt->flags & AV_PKT_FLAG_KEY)
  431. hint_pkt.flags |= AV_PKT_FLAG_KEY;
  432. if (count > 0)
  433. ff_mov_write_packet(s, &hint_pkt);
  434. done:
  435. av_free(buf);
  436. sample_queue_retain(&trk->sample_queue);
  437. return ret;
  438. }
  439. void ff_mov_close_hinting(MOVTrack *track) {
  440. AVFormatContext* rtp_ctx = track->rtp_ctx;
  441. uint8_t *ptr;
  442. av_freep(&track->enc);
  443. sample_queue_free(&track->sample_queue);
  444. if (!rtp_ctx)
  445. return;
  446. if (rtp_ctx->pb) {
  447. av_write_trailer(rtp_ctx);
  448. url_close_dyn_buf(rtp_ctx->pb, &ptr);
  449. av_free(ptr);
  450. }
  451. av_metadata_free(&rtp_ctx->streams[0]->metadata);
  452. av_metadata_free(&rtp_ctx->metadata);
  453. av_free(rtp_ctx->streams[0]);
  454. av_freep(&rtp_ctx);
  455. }