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.

463 lines
15KB

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